Chương 15 — Kubernetes & Nền tảng AI Đám mây Chuẩn Sản xuất (Helmfile, HashiCorp Vault + ESO, KEDA, KServe & Lập lịch GPU MIG/DRA)
Từ nội tại Control Plane/QoS OOMKill (Guaranteed 100% sống vs BestEffort 0%) & lập lịch GPU MIG/DRA v1 (mật độ 3.0x–5.0x, 0 neighbor kill) đến Helmfile (dev->DRA, prod->MIG) + Vault ESO (4 lease quay vòng, 0 plaintext secret), KEDA TriggerAuthentication cắt p95 burst 8x 52.52x (525.25s -> 10.0s, 100% SLA), LWS/Gateway API GAIE & FastAPI Async Queue (14 OTel spans).
Unit ID:
T2-P3-U03
Track & Part: Track 2 (EDAI) — Part 3: Distributed Systems, Kubernetes, Distributed Training & Cloud Infrastructure (part-03-distributed-k8s-cloud-and-gateway)
Cầu nối Từ Chương 13 & Chương 14: Sau khi trang bị kỹ năng phòng vệ mô hình AI/LLM (Ch 13) và các nguyên lý hệ phân tán như đồng thuận Raft, CAP/PACELC và định tuyến phân mảnh (Ch 14), Chương 15 đưa toàn bộ ứng dụng FastAPI, hàng đợi xử lý bất đồng bộ và mô hình suy luận lên Kubernetes chuẩn sản xuất — làm tiền đề cho huấn luyện phân tán Kubeflow (Ch 16), tối ưu chi phí Cloud FinOps (Ch 17), AI Gateway (Ch 18) và IaC/Service Mesh (Ch 19).
Truy xuất Giáo trình Gốc (R44— Kubernetes): K8s architecture; k8s objects (pod, deployment, service, ingress, PV/PVC); k8s patterns (sidecars, init containers, operators); k8s deployment strategies; manage k8s applications with Helm and helmfile; secret management; resource management; Labs: Implement an async job processing system, Deploy your API applications locally on k8s (k8s, Helm, KServe, HashiCorp Vault) trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 13): labs/lab-13-k8s-helm-vault-async-job-platform/README.md (k8s_ai_platform_lab)
Tình huống Mở đầu: Bốn Thảm họa Hạ tầng Khi Đưa Hệ thống AI Lên Kubernetes Ngây thơ#
Một mô hình AI đạt 100% độ chính xác trên máy trạm vẫn có thể sập hoàn toàn trong giờ cao điểm đầu tiên trên cụm Kubernetes nếu kỹ sư nền tảng phạm phải bốn sai lầm kiến trúc kinh điển sau:
- Pod API Rơi Vào Lớp
BestEffort(oom_score_adj = 1000) & GPUTime-SlicingGây Chết Chéo Dây chuyền: Nhóm triển khai bỏ trốngresources.requests/limitscho cụm FastAPI và nhét4dịch vụ suy luận lên chung GPU bằng cơ chếTime-Slicingkhông cách ly VRAM. Trong mô phỏng áp lực bộ nhớ Node củaLab 13(39,130 MiBsử dụng trên Node32,768 MiB),kubeletkích hoạt thu hồi bộ nhớ và tiêu diệt sạch100.0%PodBestEffortđầu tiên trong khi chỉ có3/3(100.0%) Pod APIGuaranteed(oom_score_adj = -997) sống sót. Đồng thời trên GPU chia sẻ, một tác vụ bùng VRAM (52 GB) đã kích hoạtCUDA OOMđánh sập thêm2workload hàng xóm — điều hoàn toàn biến mất (0lỗi lan truyền) khi chuyển sangNVIDIA MIG(3.0xmật độ đóng gói) hoặcKubernetes DRA(5.0xcông suất tối đa). - Dùng
CPU-Only HPACho Hàng đợi Async AI Khiến Thời gian Chờp95Vọt525.25s(18.33%SLA): Khi lưu lượng tăng đột biến8x(4 -> 32job/tick), các worker xử lý OCR/Embedding/LLM dành phần lớn thời gian chờ GPU và I/O nên mức sử dụng CPU chỉ đạt đỉnh61.8%— thấp hơn ngưỡng kích hoạt70%củaHPA! Hậu quả là cụm worker kẹt cứng ở2Pod, hàng đợi ùn tắc lên432job,p95độ trễ vọt525.25 giây(18.33%đạt SLA<= 30s). Thay bằngKEDA ScaledObjectco giãn trực tiếp theo độ sâu hàng đợi (queue lag) đẩy công suất lên8Pod tức thì, hạ đỉnh nghẽn còn32job và kéop95về10.0 giây(nhanh hơn52.52x, đạt100.0%SLA). RollingUpdateMù Đẩy Bản Suy luận Lỗi8.5%Lên100%Lưu lượng Dù/healthVẫn200 OK: Phiên bản mô hìnhv2.1-bad-thresholdvượt qua kiểm tra cổng sống/healthnhưng phát sinh8.5%lỗi nghiệp vụ vàp95 = 148 ms. Chiến lượcRollingUpdatetruyền thống đẩy lỗi này tới100.0%người dùng, trong khiKServe Canary SLO Gatecắt cầu dao và tự động rollback ngay ở nấc10.0%, cònBlue-Greenkèm kiểm tra khói trước khi chuyển hướng đạt0.0%bán kính nổ.- Rò rỉ Bí mật Tĩnh Trong
HelmGit Repo & Gián đoạn Khi Xoay vòng Thủ công: Ghi thẳng token hoặc chuỗi DSN DB vàovalues.yamltạo lỗ hổng lộ thông tin nghiêm trọng; ngược lại, xoay mật khẩu tĩnh bằng tay buộc phải khởi động lại toàn bộ Pod. Kiến trúc chuẩnHashiCorp Vault+External Secrets Operator (ESO)đổi JWT củaServiceAccountlấy bí mật động KV v2 tự xoay4lease liên tiếp trong900s(TTL 300s, làm mới60s) với0lỗi xác thực và0lần khởi động lại Pod.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 15 và bài thực hành k8s_ai_platform_lab (Lab 13), kỹ sư Nền tảng Dữ liệu & AI nắm vững:
- Giải phẫu
Control Plane(kube-apiserver,etcdRaft/Watch,kube-schedulerFilter/Score,kubelet,CNI/CSI) & Chuyển dịchIngress\(\to\)Gateway API Inference Extension(R44+ SOTA): Phân tích luồng đối chiếu trạng thái mong muốn (reconciliation loop), định tuyếnHTTPRoutevà cơ chếInferencePool/InferenceObjectivenhận biếtKV-cacheprefix trên GPU. - Thiết kế Hệ thống Bất đồng bộ Bằng
K8s Objects,Patterns(Init,Sidecar,Ambassador,Operator) &KServe(R44): Thành thạoPod,Deployment,StatefulSet,Job/CronJob,PV/PVC(RWOvsRWX),NetworkPolicydefault-deny,PodDisruptionBudget,KServe InferenceService, cùng năm chiến lược triển khai (RollingUpdate,Recreate,Blue-Green,Canary,Shadow) và dịch vụFastAPIAsync Queue (202 Accepted, idempotency, retry, Dead Letter Queue). - Đóng gói Đa môi trường Với
Helm/Helmfile& Bí mật ĐộngHashiCorp Vault+ESO(R44): Tổ chức đồ thị phụ thuộc đa Chart quahelmfile.yaml.gotmpl(dev/prod), kiểm toán loại bỏ100%bí mật tĩnh khỏi YAML, cấu hìnhSecretStore/ExternalSecretxác thực JWT và siết bảo mậtPod Security Standards (PSS)mứcRestricted. - Quản trị Tài nguyên (
QoS&OOMKill), Co giãnKEDAQueue-Depth & Lập lịch GPUMIG/DRA/Kueue(R44+ SOTA 2025–2026): Kiểm soát chính xácrequests == limits(Guaranteed-997), cấu hình bộ ba probe (startup/readiness/liveness) +preStopthoát êm, thay thếCPU HPAbằngKEDA, và lựa chọn giữaWhole GPU,Time-Slicing,NVIDIA MIGvàKubernetes DRA(ResourceClaim).
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P3-U03, R44)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R44) |
Nâng cấp Chuẩn SOTA 2026 (ch-15) |
Mục trong Chương 15 | Tạo tác & Kiểm thử (k8s_ai_platform_lab) |
|---|---|---|---|
1. K8s architecture (R44) |
kube-apiserver admission pipeline, etcd Raft + SharedInformer MVCC Watch-List, kube-scheduler 2 pha Filter -> Score, kubelet cgroups v2, Cilium eBPF CNI & CSI |
Trụ cột 1 (§1.1) + Mermaid 1 | scheduler_keda_and_async_app.py (schedule_pods_two_phase), Test 07 |
2. K8s objects: Pod, Deployment, Service, Ingress, PV/PVC (R44) |
Deployment, StatefulSet, Job/CronJob, Headless Service, Gateway API (HTTPRoute) & Inference Extension (InferencePool), RWO/RWX PVC, NetworkPolicy default-deny, PDB |
Trụ cột 1 (§1.1, §1.3) | serviceaccount.yaml, networkpolicy.yaml, pdb.yaml, Tests 04, 06 |
3. K8s patterns: Sidecars, Init Containers, Operators (R44) |
Init Container kiểm tra trọng số, Native Sidecar (K8s 1.29+), Ambassador proxy, Operator (CRD + Reconciliation) trên ESO, KEDA, KServe & Kueue |
Trụ cột 1 (§1.2) + Mermaid 2 | worker-deployment.yaml, keda-scaledobject.yaml, Tests 05–06 |
4. K8s deployment strategies & KServe (R44) |
RollingUpdate, Recreate, Blue-Green (0.0% blast), KServe v0.14+ Canary (10.0% rollback vs 100.0% Rolling), Shadow mirroring |
Trụ cột 1 (§1.2) + Widget 3 | kserve-inferenceservice.yaml, evaluate_rollout_safety_and_vault_leases, Tests 13–14 |
5. Manage k8s with Helm & helmfile (R44) |
Helm v3 Chart templating (dev/prod) + Helmfile DAG needs: (vault-eso/keda \(\to\) kserve \(\to\) ml-async-platform) + trình kiểm toán template thuần Python |
Trụ cột 1 (§1.3) | helmfile.yaml.gotmpl, charts/ml-async-platform/, manifest_and_vault_audit.py, Tests 02, 06, 20–21 |
6. Secret management (HashiCorp Vault, R44) |
HashiCorp Vault KV v2 + ESO (SecretStore JWT auth + ExternalSecret), xoay vòng 4 lease/900s (0 restart), 0 plaintext secrets & PSS Restricted |
Trụ cột 1 (§1.3) + Widget 3 | external-secret-vault.yaml, scan_directory_secret_hygiene, Tests 03, 14, 20 |
7. Resource management & Async Job Lab (R44) |
QoS (Guaranteed -997 100% sống vs BestEffort 1000 100% chết), KEDA (10.0s vs 525.25s CPU HPA), MIG (3.0x) & DRA (5.0x) + FastAPI Async Job (202 + Idempotency + DLQ + OTel) |
Trụ cột 1 (§1.3, §1.4) + Mermaid 3 + Widgets 1–2 | scheduler_keda_and_async_app.py, Tests 08–12, 15–19 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 15 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 15 & k8s_ai_platform_lab |
Giá trị Thực nghiệm Lab 13 (seed=42) |
|---|---|---|---|
| \(S_{\text{oom}}\) | \([-997, 1000]\) | Điểm ưu tiên thu hồi oom_score_adj: Guaranteed \(= -997\), Burstable \(\in [2, 999]\), BestEffort \(= 1000\) |
Guaranteed sống 100.0% (3/3) vs BestEffort 0.0% (0/3) |
| \(N_{\text{gpu}}, V_{\text{gpu}}\) | Thẻ, \(\text{GB}\) | Cụm GPU vật lý (4 × 80 GB = 320.0 GB VRAM) phục vụ các microservice 16 GB |
Whole: 4/12 (20.0% VRAM) vs Time-Slice: 2 neighbor kills |
| \(\rho_{\text{pack}}\) | \(\times\) | Hệ số đóng gói workload cô lập phần cứng so với Whole GPU (1:1) |
MIG 2g.20gb: 3.0x (12 slice, 0 kill); DRA: 5.0x (20 claim, 100% VRAM) |
| \(t_{\text{wait}, 95}\) | \(\text{giây}\) | Độ trễ chờ hàng đợi bách phân vị thứ 95 trong 600s tải burst 8x (744 job) |
CPU HPA: 525.25s (18.33% SLA) vs KEDA: 10.0s (100.0% SLA, 52.52x) |
| \(R_{\text{blast}}\) | \(\%\) | Tỷ lệ lưu lượng production chạm phải bản lỗi (8.5% err, /health 200) trước khi cắt |
Rolling: 100.0% vs Canary: 10.0% vs Blue-Green: 0.0% |
| \(T_{\text{lease}}, \Delta t_{\text{ref}}\) | \(\text{giây}\) | Chu kỳ sống lease HashiCorp Vault (300s) và tần suất đồng bộ ESO (60s) |
4 lease (vault-lease-004), 0 lỗi auth, 0 Pod restart |
Trụ cột 1 — Nguyên lý Gốc: Kiến trúc Kubernetes, Mẫu Triển khai, Helmfile + Vault, QoS/KEDA & Lập lịch GPU MIG/DRA#
1.1 Giải phẫu Control Plane, Worker Node, Đối tượng Lõi & Gateway API Inference Extension (R44)#
Khác với cách viết script chạy Docker thủ công theo trình tự (imperative) ở Chương 6, Kubernetes hoạt động theo kiến trúc đối chiếu trạng thái khai báo (declarative level-triggered control loop): người vận hành khai báo trạng thái mong muốn (Desired Spec) qua YAML/Helm, và hệ thống liên tục quan sát trạng thái thực tế (Observed State) để tự hội tụ lại mỗi khi Node chết hoặc lưu lượng biến động.
-
Mặt phẳng Điều khiển (
Control Plane):kube-apiserver: Cổng giao tiếp REST duy nhất; mọi thành phần bên trong lẫn bên ngoài đều nói chuyện qua đây. Mọi lệnh ghi trải qua chuỗi: Xác thực (x509/OIDC/JWT) \(\to\) Phân quyền (RBAC) \(\to\) Mutating Admission Webhooks (tiêm sidecar Vault/OTel) \(\to\) Schema Validation \(\to\) Validating Admission Webhooks (Pod Security Admission) \(\to\) lưu trữ kèm khóa lạc quanresourceVersion.etcd(Raft+MVCC Watch/List): Cơ sở dữ liệu key-value phân tán dùng đồng thuậnRaft(3hoặc5nút để chịu lỗi \(\lfloor (N-1)/2 \rfloor\) nút). Mọi controller vàkubeletdùng mẫuSharedInformer: tải snapshot ban đầu bằngList, sau đó mở kết nối dàiWatchtheoresourceVersionđể nhận sự kiện thay đổi vàoDeltaFIFO/Indexercục bộ mà không spam truy vấn đọc lênetcd.kube-scheduler(SchedulingCycle:Filter\(\to\)Score\(\to\)Binding):- Pha
Filter(Loại bỏ Cứng): Kiểm traNodeResourcesFit(đủ CPU/RAM/GPU khả dụng),TaintToleration(NoSchedulecho Node GPU đắt tiền),NodeSelectorvà gắn kết đĩaPVC. TrongLab 13(Test 07), Pod GPU thiếu tolerationgpu=nvidia:NoSchedulebịFilterchặn ngay tạiPendingkhông cho lọt lên Node sai. - Pha
Score(Chấm điểm Mềm0..100): Xếp hạng các Node vượt quaFilterdựa trênImageLocality(ưu tiên Node đã cache sẵn container image lớnvLLM/PyTorch),PodTopologySpread(rải đềuml-async-apiquazone-a/zone-b/zone-c), và cân bằng tài nguyên (LeastAllocatedcho API vsBinPackingdồn GPU trống nguyên thẻ cho job huấn luyện lớn).
- Pha
kube-controller-manager: Hợp nhất hàng chục vòng lặp đối chiếu (Deployment,ReplicaSet,StatefulSet,Job,Node,EndpointSlice).
-
Nút Tính toán (
Worker Node),CNI&CSI:kubelet&CRI(containerd): Tiếp nhậnPodSpec, gọicontainerdtạo sandbox và container, áp giới hạn CPU/RAM thông qua nhân Linuxcgroups v2, chạystartup/readiness/livenessprobes và thực thi Node-Pressure Eviction khi thiếu RAM.CNI(Cilium eBPF/Calico) &kube-proxy: Cấp mạng phẳng Pod-to-Pod không NAT và thực thi chính sách tường lửaNetworkPolicy(L3/L4);kube-proxy(hoặcCilium eBPF) cân bằng tải choClusterIPqua danh sáchEndpointSlicesẵn sàng.CSI(Container Storage Interface): Điều phối gắn ổ đĩa choPV/PVC/StorageClass(WaitForFirstConsumertrì hoãn tạo đĩa tới khi biết Pod chạy ở Availability Zone nào!). Lưu ý quy tắc sống còn: đĩaReadWriteOnce(RWO) chỉ gắn được cho 1 Node tại một thời điểm (dùng cho DB/stateful worker), còn kho trọng số chia sẻ nhiều Pod đọc song song cầnReadWriteMany(RWX) hoặc cache cục bộ (LocalModelCache/emptyDir).
-
Từ
IngressSangGateway API&Gateway API Inference Extension(GAIE):- Cảnh báo Khẩn cấp
kubernetes/ingress-nginxRetirement / EOL (Tháng 3/2026):Ingress(networking.k8s.io/v1) cũ và bộ điều khiểnkubernetes/ingress-nginxbước vào ngừng hỗ trợ / kết thúc vòng đời (Retirement / EOL, tháng 3/2026) — đồng nghĩa không còn bản vá bảo mật CVE mới và bắt buộc di trú sangKubernetes Gateway API(GatewayClass\(\to\)Gateway\(\to\)HTTPRoute) để tách bạch hạ tầng TLS khỏi định tuyến L7 (weightCanary,RequestMirrorShadow). - Đột phá 2025–2026 (
GAIE): Cân bằng tải Round-Robin L7 làm vỡ bộ nhớ đệmKV-Cache Prefixcủa LLM!Gateway API Inference Extension(InferencePool,InferenceObjective, bộ chọn Endpoint PickerEPP) đọc trực tiếp tải hàng đợi và trạng tháiKV-cachecủa các PodvLLM/SGLangđể gửi các prompt chung tiền tố hệ thống/RAG về đúng GPU đang giữ cache, đồng thời ưu tiên loại tải êm (criticality-aware load shedding) cho lưu lượng chat tương tác trước lô batch nền.
- Cảnh báo Khẩn cấp
1.2 Mẫu Kiến trúc (Patterns), Năm Chiến lược Triển khai & KServe (R44 + SOTA)#
1. Bốn Mẫu Thiết kế Pod & Cụm Cốt lõi#
Init Container: Chạy tuần tự tới khi thoát mã0trước container chính. Trongworker-deployment.yaml(Lab 13),model-weights-precheckkiểm tra tính toàn vẹnSHA-256củamodel.safetensorsvào volume dùng chung/modelstrước khi worker khởi chạy suy luận.Sidecar(Native Sidecar K8s1.29+): Khai báo tronginitContainerskèmrestartPolicy: Alwaysgiúp sidecar (như OpenTelemetry Collector, Envoy mTLS, hoặc Vault Agent) khởi động trước app chính và tắt sau cùng, loại bỏ lỗi mất log/trace hoặcJobbị kẹt vĩnh viễn vì sidecar không chịu thoát.Ambassador: Container proxy cục bộ trênlocalhostche giấu logic kết nối phức tạp ra bên ngoài (gộp kết nối Postgres, định tuyến Redis Cluster hay tự động gắn token Vault).Operator(CRD+Controller): Cặp đôi CustomResourceDefinition + bộ điều khiển đối chiếu liên tục, biến tri thức vận hành chuyên sâu thành tài nguyên chuẩn K8s (ExternalSecret,ScaledObjectcủaKEDA,InferenceServicecủaKServe,ClusterQueuecủaKueue).
2. Năm Chiến lược Triển khai & KServe InferenceService (v0.14+)#
RollingUpdate: Thay thế từng phần quamaxSurgevàmaxUnavailable. Đòi hỏi tương thích ngược API/schema vàreadinessProbenghiêm ngặt; nếu chỉ kiểm tra/healthmà không đo tỷ lệ lỗi suy luận, bản lỗi vẫn lan lên100.0%lưu lượng!Recreate: Giết toàn bộ Pod cũ trước khi bật Pod mới (có downtime). Chỉ dùng khi bắt buộc nhả khóa độc quyền trên GPU đơn lẻ hoặc đĩaRWOPVC.Blue-Green: Dựng song song cụmGreen(2xtài nguyên tạm thời), chạy kiểm định khói (smoke test) xong mới trỏServiceselector hoặcHTTPRoutesangGreen. Nếu bản mới lỗi, chặn cắt mạch ngay tại bước smoke test (0.0%bán kính nổ, kiểm chứng tạiLab 13).Canary(Gắn Cổng SLO Tự động): Chuyển dần trọng số10% -> 30% -> 100%thông quaHTTPRoutehoặcKServe canaryTrafficPercent. TrongLab 13, khi ứng viênv2.1-bad-thresholdphát sinh8.5%lỗi vàp95 = 148 ms(dù/healthvẫn200 OK), cổng SLO (err <= 1.0%,p95 <= 80 ms) tự động rollback về0%ngay tại bước đầu (bán kính nổ tối đa10.0%).Shadow(Traffic Mirroring): Nhân bản luồng đọc thực tế gửi âm thầm sang mô hình mới để đo độ trễ/chất lượng mà không trả kết quả về khách hàng (cấm dùng cho endpoint ghi vì gây nhân đôi giao dịch!).
KServe v0.14+,LeaderWorkerSet (LWS)&DisaggregatedSetTrong Thực tế: Chuẩn hóa triển khaiInferenceServicegồmpredictor(bắt buộc),transformer(tiền xử lý / Guardrails đầu vào-ra từ Chương 13) vàexplainer. Ở chế độStandard(RawDeployment+Gateway API),KServebỏ bớt tầngKnative/Istiocồng kềnh, kết hợp trực tiếp vớiKEDAvàLocalModelCacheđể nạp nhanh các LLM/VLM cỡ lớn (vLLM/SGLang). Khi phục vụ mô hình đa nút hoặc suy luận tách phaPrefill / Decode(P/D Disaggregation),LeaderWorkerSet (LWS)vàDisaggregatedSetquản lý đồng bộ từng nhóm bầy đàn (gang-scheduled replica groups qua NVLink/RDMA), đảm bảo khởi động lại nguyên cụm suy luận khi một rank đơn lẻ gặp sự cố.
1.3 Đóng gói Đa tầng Helm/Helmfile, Bí mật Động HashiCorp Vault, Bảo mật Cụm & QoS/OOMKill (R44)#
-
Helm v3&Helmfile(helmfile.yaml.gotmpl):Helmđóng gói tập manifest thành Chart (Chart.yaml,values.yaml,templates/*.yaml) với trạng thái release lưu dưới dạngSecretngay trong cụm.Helmfilenâng cấp lên mức điều phối đa Chart có DAG phụ thuộc (needs:) giữa các môi trườngdevvàprod. TrongLab 13(Test 02),helmfile.yaml.gotmplgiải quyết thứ tự tô-pô chính xác: càivault-esovàkedatrước \(\to\)kserve\(\to\)ml-async-platform(vớidevbậtgpuMode=dra,canaryPercent=20vàprodbậtgpuMode=mig,canaryPercent=10).
-
Quản trị Bí mật Chuẩn Sản xuất (
HashiCorp Vault+ESO) & Siết ChặtPSS Restricted:- Đối tượng
Secretmặc định của K8s chỉ mã hóaBase64(ai có quyền đọc hoặc truy cập snapshotetcdchưa mã hóa đều giải mã tức thì). Tuyệt đối không đặt mật khẩu/API key/private key vào Git hay Helmvalues.yaml. - Với
HashiCorp Vault KV v2+External Secrets Operator (ESO), cụm dùng Kubernetes Auth Method:SecretStoregắnserviceAccountRefđể đổi JWT ngắn hạn của Pod lấy quyền đọc bí mật động tạisecret/data/ml-async-platform/runtime, cònExternalSecrettự động đồng bộ mỗirefreshInterval: 1m. Trong thí nghiệm900scủaLab 13(Test 14), leaseTTL 300sđược xoay tự động4lần (vault-lease-001\(\to\)004) với0lỗi xác thực và0lần khởi động lại Pod. - Làm cứng Pod (
PSS Restricted),NetworkPolicy&PDB: Mọi container trongLab 13tuân thủrunAsNonRoot: true,allowPrivilegeEscalation: false,readOnlyRootFilesystem: true(kèmemptyDircho/tmp),capabilities: drop: ["ALL"],seccompProfile: RuntimeDefault; cô lập mạng bằngNetworkPolicyDefault Deny All Ingress & Egresskèm luật tối thiểu cho API \(\to\) Broker/Worker/DNS/Vault; và gắnPodDisruptionBudget(minAvailable) chống gián đoạn khi bảo trì Node.
- Đối tượng
-
Phân loại Tài nguyên
CPUvsMemory, LớpQoS& Thứ tự Thu hồicgroup OOMKill:CPUlà tài nguyên nén được (compressible): Vượtlimits.cpukhiến bộ lập lịch Linux CFS throttling bóp thời gian CPU gây gai trễp99, không giết tiến trình.Memorylà tài nguyên không nén được (incompressible): Vượtlimits.memorykích hoạt ngay nhâncgroup OOMKill(Exit Code137).- Khi Node cạn RAM,
kubeletsắp xếp giết Pod theo điểmoom_score_adj:BestEffort(oom_score_adj = 1000, không khai báorequests/limits): Bị tiêu diệt đầu tiên.Burstable(oom_score_adj\(\in [2, 999]\),requests < limits): Bị tiêu diệt tiếp theo nếu dùng vượtrequests.Guaranteed(oom_score_adj = -997,requests == limitscho cả CPU & RAM ở mọi container): Được bảo vệ tối đa. Trong mô phỏng Node32,768 MiBchịu tải39,130 MiB(Lab 13,Test 08),100.0%(3/3) PodBestEffortbị giết trước, kế đến1/4PodBurstablevượt ngưỡng, còn100.0%(3/3) Pod API/KServeGuaranteedsống sót trọn vẹn.
-
Ba Tầng Probe (
startup/readiness/liveness) & Lập lịch GPU (WholevsTime-SlicingvsMIGvsDRA+Kueue):- Khai báo
startupProbecó ngưỡng thử lại rộng cho phép worker nạp trọng số mô hình chậm (18 × 5s = 90s) mà không bịlivenessProbegiết vòng lặp (CrashLoopBackOff); kết hợpreadinessProbe,preStop: sleepvàterminationGracePeriodSeconds: 60để xả hết request đang chạy khiRollingUpdate. - Bước nhảy Lập lịch GPU 2025–2026 (
NVIDIA GPU Operator+MIG+DRAGA K8s1.34):Device Plugintruyền thống (nvidia.com/gpu: 1) chỉ cấp cả thẻ GPU nguyên vẹn (4/12workload,20.0%VRAM trên cụm4 × 80 GB).Time-Slicingghép12/12workload nhưng thiếu cách ly VRAM phần cứng: một sự cố tăng52 GBđánh sập dây chuyền2workload hàng xóm.NVIDIA MIG(mig-2g.20gb) phân chia phần cứng độc lập SM, bộ nhớ HBM và L2 cache (12slice20 GBtrên4 × 80 GB=3.0xmật độ,0lỗi chéo).Kubernetes DRAv1(Dynamic Resource Allocation, GA K8s1.34): Thay thế mô hình đếm số nguyên cứng nhắc bằngDeviceClass,ResourceClaimvàResourceClaimTemplate, cho phép cấp phát tham số cấu trúc (16 GB/claim =20claim,5.0xcông suất,100.0%đóng gói VRAM,0lỗi chéo) kết hợp biểu thứcCEL(selectors) kiểm tra thuộc tính phần cứng/băng thông và chính sách dự phòngfirstAvailable(tự động chọn phần cứng theo thứ tự ưu tiênB200 -> H200 -> H100kèm nhận biết topo NVLink/PCIe). Khi chạy các job huấn luyện/suy luận nhiều GPU đồng thời,KueuevàLWS/DisaggregatedSetbổ sung lập lịch bầy đàn (Gang Scheduling) chống deadlock giữ GPU nửa vời (chi tiết ởCh 16).
- Khai báo
1.4 Tự động Co giãn (HPA/VPA/KEDA) & Nền tảng Xử lý Job Bất đồng bộ (R44 + Lab 13)#
-
Vì sao
CPU-Only HPAThất bại Trước Tải AI Bất đồng bộ & Đột pháKEDA:- Worker xử lý OCR, embedding hay gọi LLM/GPU có đặc trưng nghẽn I/O / GPU wait: dù hàng đợi đang ùn ứ hàng trăm tác vụ, CPU của Pod worker chỉ quanh quẩn mức
25%–62%(dưới ngưỡng mục tiêu70%củaHPA!). Hơn nữaHPAchịu độ trễ thu thập metric và cửa sổ ổn định. KEDA(ScaledObject) gắn trực tiếp vào độ dài hàng đợi (Redislist /RabbitMQ/Kafkalag), hỗ trợ đánh thức từ0(scale-to-zero) hoặc giữ vùng đệm tối thiểu (minReplicaCount: 2), mở rộng mạnh tay khi burst (+4Pod/bước) và gắnstabilizationWindowSeconds: 90chiều giảm tải để tránh co giãn giật cục (flapping).- Kết quả benchmark
60tick (600s,744job đến với pha burst8xtừ4 -> 32job/tick) trongLab 13(Test 12):CPU-Only HPAkẹt ở2Pod, tồn đỉnh432job,p95chờ525.25 giây(18.33%SLA<= 30s);KEDAnâng lên8Pod, đỉnh tồn chỉ32job, hạp95xuống10.0 giây(52.52xnhanh hơn, đạt100.0%SLA)!
- Worker xử lý OCR, embedding hay gọi LLM/GPU có đặc trưng nghẽn I/O / GPU wait: dù hàng đợi đang ùn ứ hàng trăm tác vụ, CPU của Pod worker chỉ quanh quẩn mức
-
Kiến trúc Dịch vụ Xử lý Job AI Bất đồng bộ Chuẩn Sản xuất (
FastAPI+Bounded OTel):- Tách biệt rõ mặt phẳng tiếp nhận (
POST /v1/jobstrảHTTP 202 Accepted) khỏi mặt phẳng thực thi nền (Worker Deploymentrút queue): tránh treo kết nối HTTP khi tác vụ OCR/LLM mất nhiều giây. - Bốn Bất biến Độ tin cậy Bắt buộc:
- Khử trùng lặp Idempotency (
idempotency_key): Gửi lại cùng khóa trả về đúngjob_idhiện có (deduplicated=True) mà không đẩy trùng vào hàng đợi. - Kiểm định Đầu vào Chặt (
Pydantic v2 ConfigDict(extra="forbid")): Từ chối tức thì mọi trường lạ hoặc loại tác vụ trái phép bằngHTTP 422(Tests 15–16). - Thử lại Có Giới hạn & Hàng đợi Thư chết (
Retry + DLQ): Lỗi tạm thời (timeout GPU) được thử lại tối đamax_retries=2; gói lỗi độc hại (poison_payload) tự động tách sangDEAD_LETTERED(DLQ) tránh làm tắc toàn bộ worker (Test 17). - Truy vết
BoundedOpenTelemetrySạch Bí mật: Ghi nhận đầy đủ luồngenqueue -> drain -> processquaBoundedInMemorySpanExporter(maxlen=256)mà không bao giờ ghi chuỗi token hay mật khẩu vào thuộc tính span (Test 18).
- Khử trùng lặp Idempotency (
- Tách biệt rõ mặt phẳng tiếp nhận (
Trụ cột 2 — Kiến trúc Hệ thống & Cẩm nang Quyết định Sản xuất (Production Decision Playbook)#
| Bài toán Thiết kế Hạ tầng AI | Phương án Ngây thơ (Gây sự cố) | Phương án Chuẩn SOTA 2026 (Ch 15 + Lab 13) |
Liên thông Chặng Tiếp theo (Ch 16–Ch 20) |
|---|---|---|---|
| Định tuyến Lưu lượng & API Biên | Ingress cũ gắn annotation đặc thù, cân bằng Round-Robin làm vỡ KV-Cache |
Gateway API (HTTPRoute) + Inference Extension (InferencePool) định tuyến theo prefix KV-cache & queue depth |
Mở rộng sang AI Gateway Token Rate-Limit & Semantic Cache (Ch 18) |
| Quản trị Tài nguyên & Bảo vệ API | Để trống requests/limits (BestEffort, 100% bị OOMKill trước) & chạy quyền root |
Guaranteed QoS (requests == limits, -997) + PSS Restricted + 3 Probes + NetworkPolicy + PDB |
Tối ưu chi phí Node & Spot preemption (Ch 17) |
| Co giãn Worker Async AI / GPU | CPU-Only HPA (61.8% CPU \(\to\) kẹt 2 Pod, p95 525.25s) |
KEDA ScaledObject bám độ sâu hàng đợi (10.0s p95, 52.52x nhanh hơn, 100% SLA) + stabilizationWindow |
Áp dụng cho Autoscaling Inference Dưới Tải Burst (Ch 20) |
| Chia sẻ GPU Cụm Đa Dịch vụ | Whole GPU (20% VRAM) hoặc Time-Slicing (2 lỗi OOM lan truyền hàng xóm) |
NVIDIA MIG (3.0x, 0 kill) cho phân vùng cứng hoặc K8s DRA ResourceClaim (5.0x, 100% VRAM, 0 kill) |
Lập lịch bầy đàn Kubeflow Training + Kueue (Ch 16) |
| Đóng gói, Bí mật & Phát hành Mô hình | Hardcode mật khẩu trong Helm Git + RollingUpdate mù (100% blast radius) |
Helmfile DAG + Vault KV v2 + ESO (4 lease/0 restart) kết hợp KServe Canary (10%) / Blue-Green (0%) |
Tự động hóa hạ tầng Terraform/OpenTofu + Istio (Ch 19) |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#
Đoạn mã dưới đây chạy độc lập hoàn toàn trong .venv (chỉ dùng numpy, pydantic và thư viện chuẩn Python), minh họa trực tiếp bốn cơ chế lõi của Chương 15: (1) Phân loại QoS & oom_score_adj dưới áp lực bộ nhớ Node; (2) So sánh công suất & cách ly GPU giữa Whole GPU, Time-Slicing, MIG 2g.20gb và K8s DRA; (3) Mô phỏng KEDA Queue-Depth vs CPU HPA dưới tải burst 8x; và (4) Cổng an toàn Canary SLO + xoay vòng lease động HashiCorp Vault.
from __future__ import annotations
import math
from collections import deque
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, ValidationError
def classify_qos(cpu_req: int, cpu_lim: int, mem_req: int, mem_lim: int, node_mem: int = 32768) -> tuple[str, int]:
if cpu_req > 0 and mem_req > 0 and cpu_req == cpu_lim and mem_req == mem_lim:
return "Guaranteed", -997
if cpu_req == 0 and cpu_lim == 0 and mem_req == 0 and mem_lim == 0:
return "BestEffort", 1000
adj = max(2, min(999, round(1000.0 - 10.0 * (mem_req / node_mem * 100.0))))
return "Burstable", adj
def demo_qos_and_gpu_packing() -> None:
g_qos, g_oom = classify_qos(1000, 1000, 2048, 2048)
be_qos, be_oom = classify_qos(0, 0, 0, 0)
assert (g_qos, g_oom) == ("Guaranteed", -997) and (be_qos, be_oom) == ("BestEffort", 1000)
n_gpus, gpu_vram, req_vram = 4, 80, 16.0
whole_cap = n_gpus
mig_cap = n_gpus * 3 # 3x mig-2g.20gb hardware slices per 80GB GPU
dra_cap = n_gpus * math.floor(gpu_vram / req_vram)
assert whole_cap == 4 and mig_cap == 12 and dra_cap == 20
print(f"[1. QoS & GPU] Guaranteed={g_oom} vs BestEffort={be_oom} | Whole={whole_cap} MIG={mig_cap} DRA={dra_cap}")
def sim_autoscaler(arrivals: list[int], use_keda: bool) -> float:
replicas, backlog, waits = 2, 0, []
cpu_buf: deque[float] = deque([15.0, 15.0], maxlen=2)
cooldown = 0
for inc in arrivals:
backlog += inc
cap = replicas * 4
done = min(backlog, cap)
backlog -= done
cpu = min(92.0, 12.0 + 30.0 * min(1.0, (backlog + done) / cap) + 0.09 * min(backlog, 220))
cpu_buf.append(cpu)
waits.append(round((backlog / cap) * 10.0, 2))
if not use_keda:
desired = max(2, min(12, math.ceil(replicas * (cpu_buf[0] / 70.0))))
replicas = min(12, replicas + 1) if desired > replicas else replicas
else:
desired = max(2, min(12, math.ceil(backlog / 4.0)))
if desired > replicas:
replicas = min(12, min(desired, replicas + 4))
cooldown = 4
elif desired < replicas:
cooldown = cooldown - 1 if cooldown > 0 else 0
if cooldown == 0:
replicas = max(2, max(desired, replicas - max(1, replicas // 4)))
return round(float(np.percentile(np.array(waits), 95)), 2)
class JobSchema(BaseModel):
model_config = ConfigDict(extra="forbid")
task_type: str = Field(pattern=r"^(ocr_extract|embed_batch|llm_rerank)$")
idempotency_key: str = Field(min_length=4)
def demo_keda_canary_and_vault() -> None:
arrivals = [32 if 10 <= t <= 27 else 4 for t in range(60)]
hpa_p95 = sim_autoscaler(arrivals, use_keda=False)
keda_p95 = sim_autoscaler(arrivals, use_keda=True)
assert hpa_p95 > 500.0 and keda_p95 <= 15.0
# Vault 300s TTL lease rotation every <=90s remaining across 900s at 60s ESO refresh
leases, issued_at = 1, 0
for t in range(60, 901, 60):
if 300 - (t - issued_at) <= 90:
leases += 1
issued_at = t
assert leases == 4
blocked = False
try:
JobSchema.model_validate({"task_type": "ocr_extract", "idempotency_key": "k-01", "admin": True})
except ValidationError:
blocked = True
assert blocked is True
print(f"[2. KEDA & Vault] CPU_HPA_p95={hpa_p95}s vs KEDA_p95={keda_p95}s | Vault Leases={leases} (0 err)")
if __name__ == "__main__":
demo_qos_and_gpu_packing()
demo_keda_canary_and_vault()
print("Pillar 3 Kubernetes & Cloud-Native AI Verification PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (Lab 13: k8s_ai_platform_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Lab 13 (labs/lab-13-k8s-helm-vault-async-job-platform/)#
Lab 13 kết hợp đầy đủ Tầng 1 (Khai báo Hạ tầng Chuẩn Sản xuất) và Tầng 2 (Kiểm toán, Mô phỏng & Dịch vụ FastAPI Offline 100% Trong .venv):
- Tầng 1 —
helmfile.yaml.gotmpl&charts/ml-async-platform/:helmfile.yaml.gotmpl: Điều phối DAG4release (vault-eso,keda,kserve,ml-async-platform) qua môi trườngdev(gpuMode: dra,canaryPercent: 20) vàprod(gpuMode: mig,canaryPercent: 10).templates/*.yaml: Khai báo đầy đủServiceAccount(automountServiceAccountToken: false),ClusterIP Service,Gateway API HTTPRoute,DeploymentAPI (GuaranteedQoS +PSS Restricted+3Probes +topologySpreadConstraints+envFrom), WorkerDeployment(initContainerstạo/models/ready.ok+ chuyển mạchMIG/DRA ResourceClaimTemplate+terminationGracePeriodSeconds: 60),KEDA ScaledObject+TriggerAuthentication(ml-async-keda-vault-auth),KServe InferenceService(securityContextPSS Restricted+3Probes +nvidia.com/gpu),Vault SecretStore+ExternalSecret(0bí mật tĩnh),NetworkPolicydefault-deny +doc-ocr-rerankerpredictor/S3443/Prometheus8080/9090, vàPodDisruptionBudget(replicas > minAvailablebảo toànDisruptionsAllowed >= 1).
- Tầng 2 — Gói
k8s_ai_platform_lab:manifest_and_vault_audit.py: Bộ giải mã Go-template (if/else/end,.Values.*) render trực tiếp Chart Helm thành đối tượng YAML K8s để kiểm toán toàn bộ DAG, quét lộ bí mật, kiểm traQoS,PSS Restricted,MIGvsDRA,KEDA,KServe,NetworkPolicy&PDB.scheduler_keda_and_async_app.py: Thực thi bộ lập lịchkube-scheduler2 pha, mô phỏngOOMKilltheoQoS, so sánh đóng gói GPUWhole/Time-Slicing/MIG/DRA, benchmarkKEDAvsCPU HPA, cổngCanary/Blue-Green+ xoay vòng leaseVault, và ứng dụngFastAPI(/health,POST /v1/jobs202 Accepted+ idempotency,POST /v1/jobs/drainretry + DLQ,GET /v1/jobs/{job_id}) gắnBoundedInMemorySpanExporter(maxlen=256).
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch15_lab13_results.json, seed=42)#
Thực nghiệm (k8s_ai_platform_lab) |
Thông số Đo được (Xác định seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Kiểm toán Tầng 1 (Helmfile, Vault ESO, PSS, MIG/DRA) |
Quét 12 tệp YAML/Template (0 bí mật tĩnh); prod MIG render 16 đối tượng, dev DRA render 17 đối tượng (ResourceClaimTemplate), DAG 4 release hợp lệ |
Bảo đảm cấu hình hạ tầng sạch bí mật & đúng chuẩn trước khi apply |
Áp lực Bộ nhớ Node 32 GiB (39,130 MiB Yêu cầu Thực) |
BestEffort (1000) sống 0.0% (0/3); Burstable sống 75.0% (3/4); Guaranteed (-997) sống 100.0% (3/3) |
Đặt requests == limits bảo vệ tuyệt đối API & KServe trước OOMKill |
Lập lịch GPU Cụm 4 × 80 GB (12 Workload 16 GB) |
Whole: 4/12 (20% VRAM); Time-Slice: 2 neighbor kills; MIG 2g.20gb: 12/12 (3.0x, 0 kill); DRA 16GB: 20 max claims (5.0x, 100% peak VRAM, 0 kill) |
MIG & DRA nhân 3x–5x mật độ mà giữ bán kính lỗi bằng 0 |
Tự động Co giãn Tải Burst 8x (600s, 744 Jobs) |
CPU HPA: kẹt 2 Pod, peak 432 job, p95 525.25s (18.33% SLA); KEDA: 8 Pod, peak 32 job, p95 10.0s (52.52x, 100.0% SLA) |
KEDA bám queue lag xử lý gọn bài toán worker nghẽn GPU/I/O |
Cổng Canary/Blue-Green & Xoay Lease Vault (900s) |
Bản lỗi 8.5% err: Rolling lộ 100.0%, Canary cắt tại 10.0%, Blue-Green 0.0%; Vault + ESO xoay 4 lease (vault-lease-004), 0 err, 0 restart |
Ngăn chặn phát hành suy thoái và loại bỏ hoàn toàn mật khẩu tĩnh |
Dịch vụ FastAPI Async Queue + Bounded OpenTelemetry |
/v1/jobs (202 + dedup), /v1/jobs/drain (2 OK gồm retry + 1 DEAD_LETTERED DLQ), thu 14 OTel spans sạch bí mật |
Tách đường dẫn HTTP khỏi thực thi nặng, chống lỗi lặp & bảo toàn DLQ |
4.3 Quy trình Kiểm định Tự động (21/21 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/lab-13-k8s-helm-vault-async-job-platform
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch15_lab13_results.json
ruff check src tests scripts
mypy src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (7 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#
- Burns, B. et al. & Kubernetes Documentation (2016–2026). Kubernetes Internals: kube-apiserver, etcd MVCC Watch/List, kube-scheduler Filter/Score, QoS Classes & Pod Security Standards. — Nền tảng cơ chế đối chiếu khai báo, bảo vệ tiến trình bằng
oom_score_adjvà chuẩn bảo mậtRestricted. - Kubernetes SIG Network & SIG Serving (2024–2026).
kubernetes/ingress-nginxRetirement / EOL (March 2026) -> Migration to Kubernetes Gateway API & Gateway API Inference Extension (GAIE:InferencePool,Endpoint Picker). — Cảnh báo ngừng hỗ trợingress-nginxtháng 3/2026 và chuẩn hóa định tuyến suy luận AI theo tiền tốKV-Cache+ độ dài hàng đợi. - Kubernetes SIG Node, SIG Apps & NVIDIA (2025–2026). Dynamic Resource Allocation (
DRA v1GA in K8s1.34: CELselectors,firstAvailableB200 -> H200 -> H100),LeaderWorkerSet (LWS)/DisaggregatedSet& NVIDIA GPU Operator (MIGvsTime-Slicing). — Cách mạng hóa lập lịch GPU chia sẻ có cách ly phần cứng, điều phối P/D đa nút và cấu hình NVLink linh hoạt. - Helm & Helmfile Maintainers (2024–2026). Helm v3 Chart Architecture & Helmfile Declarative Multi-Release Orchestration (
needs:DAG & Environments). — Quản trị vòng đời chuỗi phụ thuộc đa môi trườngdev/prod. - HashiCorp & CNCF External Secrets Operator (2024–2026). HashiCorp Vault KV v2 / Dynamic Secrets Engine & ESO Kubernetes Auth (
SecretStore,ExternalSecret). — Loại bỏ bí mật tĩnh khỏi kho mã nguồn và tự động xoay vòng lease không cần khởi động lại Pod. - CNCF
KEDA&KueueWorking Groups (2024–2026). KEDA Event-Driven Autoscaling (ScaledObject) & Kueue Multi-Tenant Queueing / Gang Scheduling. — Giải quyết độ trễ mù CPU trên worker GPU/I/O và ngăn deadlock khi cấp phát nhiều GPU. - CNCF
KServe(v0.14+) & FastAPI / OpenTelemetry (2025–2026). KServe Standard InferenceService, Canary Rollouts, LocalModelCache & Async Queue Resilience (Idempotency + DLQ). — Chuẩn hóa phục vụ mô hình và tách biệt hàng đợi tác vụ nặng.
5.2 Sáu Bài tập Tự luận & Thực hành (ex1 – ex6) Kèm Thang điểm (Grading Rubric)#
-
Bài tập 1 (
ex1, 15%) — Kiểm toán DAGHelmfile,Vault ESO& Làm cứngPSS Restricted: Phân tích đồ thịneeds:tronghelmfile.yaml.gotmpl(dev/prod), giải thích cơ chế đổi JWTServiceAccountlấy bí mậtVault KV v2quaSecretStore/ExternalSecret(và vì sao không dùngkind: Secrettĩnh trong Chart), đồng thời chứng minh cáchmanifest_and_vault_audit.pyphát hiện hành vi giả mạo hạ cấprunAsNonRoothoặc lộ token (Tests 02–04, 06, 20–21).Thang điểm: Đúng luồng Auth Vault JWT (
5%), đúng cấu hìnhPSS Restricted/NetworkPolicy/PDB(5%), passTests 02–04, 06, 20–21(5%). -
Bài tập 2 (
ex2, 15%) — Bộ lập lịch 2 Pha & Thứ tự Thu hồiQoS/OOMKill: Giải thích phaFiltervsScoretrongkube-scheduler, dẫn xuất quy tắc phân lớpGuaranteed(oom_score_adj = -997),Burstable(2..999) vàBestEffort(1000), và phân tích kết quả thực nghiệm khi Node32 GiBchịu áp lực39,130 MiB(Tests 07–09).Thang điểm: Đúng cơ chế
Filter/Score(5%), chứng minh bất biếnoom_score_adj& thứ tự eviction (5%), passTests 07–09(5%). -
Bài tập 3 (
ex3, 20%) — Lập lịch GPUWholevsTime-SlicingvsNVIDIA MIGvsKubernetes DRA: So sánh trên cụm4 × 80 GBvới12workload16 GB(Test 10) và kiểm thử thuộc tínhHypothesis(Test 11): giải thích nguyên nhânTime-Slicinggây2lỗi chết chéo khi một tác vụ tăng52 GB, trong khiMIG 2g.20gbđạt3.0xvàDRA ResourceClaimđạt5.0xcông suất tối đa (20claim,100.0%VRAM) với0lỗi lan truyền.Thang điểm: Đúng kiến trúc phần cứng/scheduler của 4 phương án (
7%), phân tích chính xác cách ly bộ nhớ & bất biến dung lượng (7%), passTests 10–11(6%). -
Bài tập 4 (
ex4, 20%) — So sánhKEDAQueue-Depth vsCPU-Only HPADưới Tải Burst8x: Chứng minh vì sao worker GPU/I/O giữ CPU đỉnh ở61.8%(<70%target) khiếnCPU-Only HPAkẹt ở2Pod và vọtp95 = 525.25s(18.33%SLA), cònKEDA ScaledObjectbám độ sâu hàng đợi mở rộng tới8Pod để giảmp95xuống10.0s(52.52x,100.0%SLA,Test 12) cùng vai trò cửa sổ ổn địnhscaleUp/scaleDown.Thang điểm: Giải thích thấu đáo bẫy mù CPU (
8%), phân tích thông sốScaledObjectchống flapping (7%), passTest 12(5%). -
Bài tập 5 (
ex5, 15%) — Cổng An toànCanary/Blue-Green& Xoay vòng LeaseVaultKhông Gián đoạn: Đối chiếu phản ứng củaRollingUpdate(100.0%lộ lỗi),KServe Canary SLO Gate(10.0%rollback) vàBlue-Green(0.0%blast radius) trước bản lỗi8.5%có/health 200 OK, kết hợp mô phỏngESOxoay4leaseVaulttrong900s(Tests 13–14).Thang điểm: Đúng phép đo bán kính nổ 3 chiến lược (
6%), phân tích chu kỳ gia hạn TTL70%(5%), passTests 13–14(4%). -
Bài tập 6 (
ex6, 15%) — Dịch vụFastAPIAsync Job Queue (202+Idempotency+Retry/DLQ) &BoundedOTel: Kiểm chứng bằngTestClientluồngPOST /v1/jobs(202+ khử trùngidempotency_key),422vớiextra="forbid",POST /v1/jobs/drainchạy tối đa3lần thử (1gốc +2lần retry —attempts == 3) vs đẩypoison_payloadvàoDLQ, thu14spanOpenTelemetrysạch bí mật,0# type: ignorevà21/21pytest +ruff+mypy+uv lock --check(Tests 01, 15–19, 21).Thang điểm: Đúng bất biến HTTP async/idempotency/DLQ (
6%), sạch AST/0# type: ignore(5%), passTests 01, 15–19, 21(4%).
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— Kiến trúcControl Plane&Gateway API Inference Extension): Trong luồng điều khiển Kubernetes và định tuyến AI hiện đại (Test 07), vai trò củaetcdMVCC Watch-List, hai phaFilter -> Scorecủakube-schedulervàGateway API Inference Extensionkhác gì so vớiIngressRound-Robin cổ điển? - (
q2—QoSClasses & Thứ tự Thu hồiOOMKill): Trong thí nghiệm áp lực bộ nhớ39,130 MiBtrên Node32,768 MiBcủaLab 13(Tests 08–09), điểmoom_score_adjvà tỷ lệ sống sót của ba lớpGuaranteed,BurstablevàBestEffortdiễn biến thế nào? - (
q3— Lập lịch GPUWholevsTime-SlicingvsMIGvsDRA): Trên cụm4 × 80 GBphục vụ12tác vụ16 GB(Tests 10–11), vì saoTime-Slicinggây chết chéo2workload hàng xóm khi gặp sự cố tăng VRAM52 GB, trong khiNVIDIA MIG 2g.20gbvàKubernetes DRAxử lý ra sao? - (
q4—KEDAQueue-Depth vsCPU-Only HPADưới Tải Burst8x): Tại saoCPU-Only HPA(mục tiêu70%CPU) lại làmp95thời gian chờ hàng đợi vọt lên525.25s(432job ùn ứ) ở tải burst8xtrongLab 13(Test 12), cònKEDA ScaledObjectgiải quyết thế nào? - (
q5— Chiến lược Triển khaiRollingUpdate,Blue-Green,Canary&KServe): Khi ứng viên mô hìnhv2.1-bad-thresholdvẫn trả/health 200 OKnhưng phát sinh8.5%lỗi thực tế (Test 13), bán kính nổ trên production củaRollingUpdate,KServe Canary SLO GatevàBlue-Greenkhác nhau ra sao? - (
q6—HelmfileDAG,HashiCorp Vault+ESO& Bảo mậtPSS Restricted): TrongLab 13(Tests 02–04, 14),Helmfile,External Secrets Operatorkết hợpVault KV v2và chuẩnPSS Restrictedbảo vệ chuỗi cung ứng và thông tin xác thực như thế nào? - (
q7— MẫuInit Container,Native Sidecar,Operator&PVCRWO/RWX): Sự khác biệt cốt lõi giữaInit Container,Native Sidecar(K8s 1.29+),Operator/CRDvà quy tắc chọnRWOvsRWX/ chiến lượcRecreatelà gì? - (
q8— Dịch vụFastAPIAsync Job Queue,Idempotency,DLQ&Bounded OTel): Trong ứng dụngFastAPIcủaLab 13(Tests 15–18), cơ chếHTTP 202 Accepted, khóaidempotency_key, xử lýpoison_payloadvàBoundedInMemorySpanExporterđảm bảo tính bền vững như thế nào?
8x Bursty Async AI Queue p95 Wait Time (sec): CPU-Only HPA vs KEDA
4x 80 GB Cluster GPU Workload Capacity: Whole vs Time-Slice vs MIG vs DRA
Node Memory Pressure (39.1 / 32 GiB) Pod Survival Rate (%) by QoS Class
Faulty Release (8.5% Error Rate, /health 200 OK) Production Blast Radius (%)
Tier-1 Helmfile, Vault ESO, QoS, NetworkPolicy & GPU Manifest Audit
| audit_target | checks_verified | gpu_or_auth_mode | status |
|---|---|---|---|
| helmfile.yaml.gotmpl (4 releases, 2 envs) | keda-system/keda -> security-system/vault-eso -> kserve-system/kserve -> {{ .Values.namespace }}/ml-async-platform | dev, prod | PASS |
| Secret Hygiene Scan (YAML + Templates) | 12 files scanned | Vault KV v2 + K8s SA JWT (0 inline) | PASS |
| Helm Chart Render (prod MIG profile) | 16 K8s objects | Guaranteed QoS + nvidia.com/mig-2g.20gb | PASS |
| Helm Chart Render (dev DRA profile) | 17 K8s objects | K8s 1.34+ DRA ResourceClaimTemplate | PASS |
4x 80 GB GPU Scheduling Comparison: Whole vs Time-Slicing vs MIG vs DRA
| strategy | admitted_cap | vram_isolation | spillover_risk |
|---|---|---|---|
| Whole GPU (nvidia.com/gpu: 1) | 4/12 (cap 4) | 20.0% VRAM | HW=True | 0 kills (1.0x) |
| GPU Time-Slicing (Shared Context) | 12/12 (cap 16) | 60.0% VRAM | HW=False | 2 kills (3.0x) |
| NVIDIA MIG (mig-2g.20gb) | 12/12 (cap 12) | 60.0% VRAM | HW=True | 0 kills (3.0x) |
| K8s DRA (ResourceClaim 16GB) | 12/12 (cap 20) | 60.0% VRAM | HW=True | 0 kills (5.0x) |
8x Bursty Async AI Traffic Benchmark: CPU-Only HPA vs KEDA Queue-Depth
| autoscaler | peak_queue_pods | p95_max_wait | sla_compliance |
|---|---|---|---|
| CPU-Only HPA (70% CPU Target) | Peak 432 jobs | max 2 pods | p95 525.25s (max 540.0s) | 18.33% (<=30s SLA) |
| KEDA ScaledObject (Queue Lag=4/pod) | Peak 32 jobs | max 8 pods | p95 10.0s (max 30.0s) | 100.0% (52.52x faster) |
Canary / Blue-Green Rollout Gate & HashiCorp Vault Lease Rotation (900s)
| mechanism | candidate_or_ttl | exposure_or_leases | verdict |
|---|---|---|---|
| RollingUpdate (Health-Probe Only) | v2.1-bad-threshold | Final 100% | Blast 100.0% | PROMOTED_UNSAFE_100PCT |
| Blue-Green (Pre-Cutover Smoke Gate) | v2.1-bad-threshold | Final 0% | Blast 0.0% | ABORTED_AT_SMOKE_ZERO_BLAST |
| KServe Canary SLO-Gated (10->30->100%) | v2.1-bad-threshold | Final 0% | Blast 10.0% | AUTO_ROLLED_BACK_AT_10PCT |
| KServe Canary SLO-Gated (10->30->100%) | v2.2-calibrated | Final 100% | Blast 0.0% | PROMOTED_100PCT |
| HashiCorp Vault + ESO Dynamic Lease | TTL 300s / 60s | 4 leases (vault-lease-004) | 0 err | 0 rst |
03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/lab-13-k8s-helm-vault-async-job-platform
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "k8s-ai-platform-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 13: Production Kubernetes, Helmfile, HashiCorp Vault ESO, KEDA Queue Autoscaling, KServe Canary, MIG/DRA GPU Scheduling & FastAPI Async Job Platform"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"fastapi>=0.115",
"httpx>=0.27",
"pyyaml>=6.0",
"opentelemetry-sdk>=1.28",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.6",
"mypy>=1.11",
"hypothesis>=6.100",
]
[project.scripts]
fsds-k8s-ai-platform-lab = "k8s_ai_platform_lab.scheduler_keda_and_async_app:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = [
"yaml",
"hypothesis",
"hypothesis.*",
]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
environments:
dev:
values:
- env: dev
namespace: ml-platform-dev
apiReplicas: 3
workerMinReplicas: 2
workerMaxReplicas: 6
canaryPercent: 20
gpuMode: dra
prod:
values:
- env: prod
namespace: ml-platform-prod
apiReplicas: 3
workerMinReplicas: 2
workerMaxReplicas: 16
canaryPercent: 10
gpuMode: mig
repositories:
- name: external-secrets
url: https://charts.external-secrets.io
- name: kedacore
url: https://kedacore.github.io/charts
- name: kserve
url: https://kserve.github.io/charts
releases:
- name: vault-eso
namespace: security-system
chart: external-secrets/external-secrets
version: 0.14.3
wait: true
values:
- installCRDs: true
serviceAccount:
create: true
name: external-secrets-controller
- name: keda
namespace: keda-system
chart: kedacore/keda
version: 2.16.1
wait: true
values:
- watchNamespace: ""
- name: kserve
namespace: kserve-system
chart: kserve/kserve
version: 0.14.1
wait: true
needs:
- security-system/vault-eso
values:
- kserve:
controller:
deploymentMode: Standard
gateway:
disableIngressCreation: true
- name: ml-async-platform
namespace: "{{ .Values.namespace }}"
chart: ./charts/ml-async-platform
version: 0.1.0
wait: true
needs:
- security-system/vault-eso
- keda-system/keda
- kserve-system/kserve
values:
- environment: "{{ .Values.env }}"
api:
replicas: {{ .Values.apiReplicas }}
worker:
gpuMode: "{{ .Values.gpuMode }}"
keda:
minReplicaCount: {{ .Values.workerMinReplicas }}
maxReplicaCount: {{ .Values.workerMaxReplicas }}
kserve:
canaryTrafficPercent: {{ .Values.canaryPercent }}
apiVersion: v2
name: ml-async-platform
description: Cloud-Native AI Async Job Processing & KServe Platform managed with Helmfile, HashiCorp Vault ESO, KEDA, and MIG/DRA GPU scheduling
type: application
version: 0.1.0
appVersion: "2026.1.0"
keywords:
- kubernetes
- kserve
- keda
- vault
- gpu-dra
- async-jobs
environment: prod
fullnameOverride: ml-async-platform
serviceAccount:
create: true
name: ml-async-platform-sa
automountServiceAccountToken: false
securityContext:
pod:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
container:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
api:
replicas: 3
image:
repository: ghcr.io/fsds-sota/ml-async-api
tag: "2026.1.0"
pullPolicy: IfNotPresent
port: 8080
terminationGracePeriodSeconds: 45
resources:
requests:
cpu: "1000m"
memory: "1Gi"
limits:
cpu: "1000m"
memory: "1Gi"
probes:
startup:
path: /health
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 12
readiness:
path: /health
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
liveness:
path: /health
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 3
worker:
replicas: 2
image:
repository: ghcr.io/fsds-sota/ml-async-worker
tag: "2026.1.0"
pullPolicy: IfNotPresent
initImage:
repository: ghcr.io/fsds-sota/model-preflight
tag: "2026.1.0"
modelArtifactUri: "s3://ml-model-registry-prod/ocr-rerank-v3/model.safetensors"
terminationGracePeriodSeconds: 60
gpuMode: mig
migResourceName: "nvidia.com/mig-2g.20gb"
migCount: 1
draDeviceClassName: "gpu.nvidia.com"
resources:
requests:
cpu: "2000m"
memory: "8Gi"
limits:
cpu: "2000m"
memory: "8Gi"
keda:
enabled: true
pollingInterval: 5
cooldownPeriod: 60
minReplicaCount: 2
maxReplicaCount: 16
queueName: "ml_async_jobs"
targetQueueDepthPerReplica: "4"
scaleUpStabilizationSeconds: 15
scaleDownStabilizationSeconds: 90
kserve:
enabled: true
modelName: "doc-ocr-reranker"
modelFormat: "pytorch"
protocolVersion: "v2"
storageUri: "s3://ml-model-registry-prod/kserve/doc-ocr-reranker-v3"
canaryTrafficPercent: 10
minReplicas: 2
maxReplicas: 8
gatewayName: "ai-inference-gateway"
gatewayNamespace: "gateway-system"
gpuCount: "1"
resources:
requests:
cpu: "1000m"
memory: "4Gi"
limits:
cpu: "1000m"
memory: "4Gi"
vault:
server: "https://vault.security-system.svc.cluster.local:8200"
kvMountPath: "secret"
kvVersion: "v2"
authMountPath: "kubernetes"
role: "ml-async-platform-role"
secretPath: "ml-async-platform/runtime"
targetSecretName: "ml-async-vault-runtime-secret"
refreshInterval: "1m"
pdb:
apiMinAvailable: 2
workerMinAvailable: 1
networkPolicy:
gatewayNamespace: "gateway-system"
brokerNamespace: "messaging-system"
vaultNamespace: "security-system"
brokerPort: 6379
vaultPort: 8200
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-async-api
labels:
app.kubernetes.io/name: ml-async-api
app.kubernetes.io/component: api
app.kubernetes.io/part-of: ml-async-platform
environment: {{ .Values.environment }}
spec:
replicas: {{ .Values.api.replicas }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app.kubernetes.io/name: ml-async-api
template:
metadata:
labels:
app.kubernetes.io/name: ml-async-api
app.kubernetes.io/component: api
qos-class: guaranteed
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
serviceAccountName: {{ .Values.serviceAccount.name }}
terminationGracePeriodSeconds: {{ .Values.api.terminationGracePeriodSeconds }}
securityContext:
runAsNonRoot: {{ .Values.securityContext.pod.runAsNonRoot }}
runAsUser: {{ .Values.securityContext.pod.runAsUser }}
runAsGroup: {{ .Values.securityContext.pod.runAsGroup }}
fsGroup: {{ .Values.securityContext.pod.fsGroup }}
seccompProfile:
type: {{ .Values.securityContext.pod.seccompProfile.type }}
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app.kubernetes.io/name: ml-async-api
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: ml-async-api
containers:
- name: api
image: "{{ .Values.api.image.repository }}:{{ .Values.api.image.tag }}"
imagePullPolicy: {{ .Values.api.image.pullPolicy }}
ports:
- name: http
containerPort: {{ .Values.api.port }}
protocol: TCP
envFrom:
- secretRef:
name: {{ .Values.vault.targetSecretName }}
env:
- name: APP_ENV
value: {{ .Values.environment }}
- name: OTEL_SERVICE_NAME
value: ml-async-api
securityContext:
runAsNonRoot: {{ .Values.securityContext.container.runAsNonRoot }}
allowPrivilegeEscalation: {{ .Values.securityContext.container.allowPrivilegeEscalation }}
readOnlyRootFilesystem: {{ .Values.securityContext.container.readOnlyRootFilesystem }}
capabilities:
drop:
- ALL
resources:
requests:
cpu: {{ .Values.api.resources.requests.cpu }}
memory: {{ .Values.api.resources.requests.memory }}
limits:
cpu: {{ .Values.api.resources.limits.cpu }}
memory: {{ .Values.api.resources.limits.memory }}
startupProbe:
httpGet:
path: {{ .Values.api.probes.startup.path }}
port: http
initialDelaySeconds: {{ .Values.api.probes.startup.initialDelaySeconds }}
periodSeconds: {{ .Values.api.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.api.probes.startup.failureThreshold }}
readinessProbe:
httpGet:
path: {{ .Values.api.probes.readiness.path }}
port: http
initialDelaySeconds: {{ .Values.api.probes.readiness.initialDelaySeconds }}
periodSeconds: {{ .Values.api.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.api.probes.readiness.failureThreshold }}
livenessProbe:
httpGet:
path: {{ .Values.api.probes.liveness.path }}
port: http
initialDelaySeconds: {{ .Values.api.probes.liveness.initialDelaySeconds }}
periodSeconds: {{ .Values.api.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.api.probes.liveness.failureThreshold }}
lifecycle:
preStop:
exec:
command:
- /bin/sh
- -c
- sleep 5
volumeMounts:
- name: tmp-scratch
mountPath: /tmp
volumes:
- name: tmp-scratch
emptyDir:
sizeLimit: 128Mi
{{- if eq .Values.worker.gpuMode "dra" }}
apiVersion: resource.k8s.io/v1
kind: ResourceClaimTemplate
metadata:
name: ml-async-worker-gpu-claim
labels:
app.kubernetes.io/name: ml-async-worker
gpu-scheduling: dra
spec:
spec:
devices:
requests:
- name: inference-gpu-slice
exactly:
deviceClassName: {{ .Values.worker.draDeviceClassName }}
allocationMode: ExactCount
count: 1
---
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-async-worker
labels:
app.kubernetes.io/name: ml-async-worker
app.kubernetes.io/component: worker
app.kubernetes.io/part-of: ml-async-platform
environment: {{ .Values.environment }}
spec:
replicas: {{ .Values.worker.replicas }}
selector:
matchLabels:
app.kubernetes.io/name: ml-async-worker
template:
metadata:
labels:
app.kubernetes.io/name: ml-async-worker
app.kubernetes.io/component: worker
qos-class: guaranteed
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
prometheus.io/path: "/metrics"
spec:
serviceAccountName: {{ .Values.serviceAccount.name }}
terminationGracePeriodSeconds: {{ .Values.worker.terminationGracePeriodSeconds }}
securityContext:
runAsNonRoot: {{ .Values.securityContext.pod.runAsNonRoot }}
runAsUser: {{ .Values.securityContext.pod.runAsUser }}
runAsGroup: {{ .Values.securityContext.pod.runAsGroup }}
fsGroup: {{ .Values.securityContext.pod.fsGroup }}
seccompProfile:
type: {{ .Values.securityContext.pod.seccompProfile.type }}
initContainers:
- name: model-weights-precheck
image: "{{ .Values.worker.initImage.repository }}:{{ .Values.worker.initImage.tag }}"
command:
- /bin/sh
- -c
- echo "Verified artifact checksum for {{ .Values.worker.modelArtifactUri }}" && touch /models/ready.ok
securityContext:
runAsNonRoot: {{ .Values.securityContext.container.runAsNonRoot }}
allowPrivilegeEscalation: {{ .Values.securityContext.container.allowPrivilegeEscalation }}
readOnlyRootFilesystem: {{ .Values.securityContext.container.readOnlyRootFilesystem }}
capabilities:
drop:
- ALL
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "250m"
memory: "256Mi"
volumeMounts:
- name: model-cache
mountPath: /models
containers:
- name: worker
image: "{{ .Values.worker.image.repository }}:{{ .Values.worker.image.tag }}"
imagePullPolicy: {{ .Values.worker.image.pullPolicy }}
envFrom:
- secretRef:
name: {{ .Values.vault.targetSecretName }}
env:
- name: QUEUE_NAME
value: {{ .Values.keda.queueName }}
- name: MODEL_ARTIFACT_URI
value: {{ .Values.worker.modelArtifactUri }}
securityContext:
runAsNonRoot: {{ .Values.securityContext.container.runAsNonRoot }}
allowPrivilegeEscalation: {{ .Values.securityContext.container.allowPrivilegeEscalation }}
readOnlyRootFilesystem: {{ .Values.securityContext.container.readOnlyRootFilesystem }}
capabilities:
drop:
- ALL
resources:
requests:
cpu: {{ .Values.worker.resources.requests.cpu }}
memory: {{ .Values.worker.resources.requests.memory }}
{{- if eq .Values.worker.gpuMode "mig" }}
{{ .Values.worker.migResourceName }}: {{ .Values.worker.migCount }}
{{- end }}
limits:
cpu: {{ .Values.worker.resources.limits.cpu }}
memory: {{ .Values.worker.resources.limits.memory }}
{{- if eq .Values.worker.gpuMode "mig" }}
{{ .Values.worker.migResourceName }}: {{ .Values.worker.migCount }}
{{- end }}
{{- if eq .Values.worker.gpuMode "dra" }}
claims:
- name: gpu-dra-claim
{{- end }}
startupProbe:
exec:
command:
- /bin/sh
- -c
- test -f /models/ready.ok
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 18
readinessProbe:
exec:
command:
- /bin/sh
- -c
- test -f /tmp/worker.ready
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
livenessProbe:
exec:
command:
- /bin/sh
- -c
- test -f /tmp/worker.alive
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 3
lifecycle:
preStop:
exec:
command:
- /bin/sh
- -c
- sleep 10
volumeMounts:
- name: model-cache
mountPath: /models
- name: tmp-scratch
mountPath: /tmp
{{- if eq .Values.worker.gpuMode "dra" }}
resourceClaims:
- name: gpu-dra-claim
resourceClaimTemplateName: ml-async-worker-gpu-claim
{{- end }}
volumes:
- name: model-cache
emptyDir:
sizeLimit: 2Gi
- name: tmp-scratch
emptyDir:
sizeLimit: 256Mi
{{- if .Values.keda.enabled }}
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: ml-async-worker-scaler
labels:
app.kubernetes.io/name: ml-async-worker
autoscaler: keda-queue-depth
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: ml-async-worker
pollingInterval: {{ .Values.keda.pollingInterval }}
cooldownPeriod: {{ .Values.keda.cooldownPeriod }}
minReplicaCount: {{ .Values.keda.minReplicaCount }}
maxReplicaCount: {{ .Values.keda.maxReplicaCount }}
fallback:
failureThreshold: 3
replicas: {{ .Values.keda.minReplicaCount }}
advanced:
restoreToOriginalReplicaCount: false
horizontalPodAutoscalerConfig:
behavior:
scaleUp:
stabilizationWindowSeconds: {{ .Values.keda.scaleUpStabilizationSeconds }}
policies:
- type: Pods
value: 4
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: {{ .Values.keda.scaleDownStabilizationSeconds }}
policies:
- type: Percent
value: 25
periodSeconds: 30
triggers:
- type: redis
metadata:
addressFromEnv: REDIS_QUEUE_ADDR
listName: {{ .Values.keda.queueName }}
listLength: "{{ .Values.keda.targetQueueDepthPerReplica }}"
enableTLS: "true"
authenticationRef:
name: ml-async-keda-vault-auth
{{- end }}
{{- if .Values.keda.enabled }}
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
name: ml-async-keda-vault-auth
labels:
app.kubernetes.io/name: ml-async-worker
autoscaler: keda-queue-depth
spec:
hashicorpVault:
address: {{ .Values.vault.server }}
authentication: kubernetes
mount: {{ .Values.vault.authMountPath }}
role: {{ .Values.vault.role }}
secrets:
- parameter: address
key: {{ .Values.vault.kvMountPath }}/data/{{ .Values.vault.secretPath }}
vaultSecretKey: redis_queue_addr
{{- end }}
{{- if .Values.kserve.enabled }}
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: {{ .Values.kserve.modelName }}
labels:
app.kubernetes.io/name: {{ .Values.kserve.modelName }}
app.kubernetes.io/part-of: ml-async-platform
annotations:
serving.kserve.io/deploymentMode: Standard
gateway.networking.k8s.io/gateway-name: {{ .Values.kserve.gatewayName }}
gateway.networking.k8s.io/gateway-namespace: {{ .Values.kserve.gatewayNamespace }}
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
predictor:
serviceAccountName: {{ .Values.serviceAccount.name }}
automountServiceAccountToken: false
minReplicas: {{ .Values.kserve.minReplicas }}
maxReplicas: {{ .Values.kserve.maxReplicas }}
canaryTrafficPercent: {{ .Values.kserve.canaryTrafficPercent }}
model:
modelFormat:
name: {{ .Values.kserve.modelFormat }}
protocolVersion: {{ .Values.kserve.protocolVersion }}
storageUri: {{ .Values.kserve.storageUri }}
securityContext:
runAsNonRoot: {{ .Values.securityContext.container.runAsNonRoot }}
allowPrivilegeEscalation: {{ .Values.securityContext.container.allowPrivilegeEscalation }}
readOnlyRootFilesystem: {{ .Values.securityContext.container.readOnlyRootFilesystem }}
capabilities:
drop:
- ALL
startupProbe:
httpGet:
path: /v2/health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 12
readinessProbe:
httpGet:
path: /v2/health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
livenessProbe:
httpGet:
path: /v2/health/live
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 3
resources:
requests:
cpu: {{ .Values.kserve.resources.requests.cpu }}
memory: {{ .Values.kserve.resources.requests.memory }}
nvidia.com/gpu: {{ .Values.kserve.gpuCount }}
limits:
cpu: {{ .Values.kserve.resources.limits.cpu }}
memory: {{ .Values.kserve.resources.limits.memory }}
nvidia.com/gpu: {{ .Values.kserve.gpuCount }}
{{- end }}
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
name: vault-kv-secret-store
labels:
app.kubernetes.io/name: ml-async-platform
secrets-backend: hashicorp-vault
spec:
provider:
vault:
server: {{ .Values.vault.server }}
path: {{ .Values.vault.kvMountPath }}
version: {{ .Values.vault.kvVersion }}
auth:
kubernetes:
mountPath: {{ .Values.vault.authMountPath }}
role: {{ .Values.vault.role }}
serviceAccountRef:
name: {{ .Values.serviceAccount.name }}
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: ml-async-runtime-external-secret
labels:
app.kubernetes.io/name: ml-async-platform
secrets-backend: hashicorp-vault
spec:
refreshInterval: {{ .Values.vault.refreshInterval }}
secretStoreRef:
name: vault-kv-secret-store
kind: SecretStore
target:
name: {{ .Values.vault.targetSecretName }}
creationPolicy: Owner
data:
- secretKey: REDIS_QUEUE_ADDR
remoteRef:
key: {{ .Values.vault.secretPath }}
property: redis_queue_addr
- secretKey: MODEL_REGISTRY_API_TOKEN
remoteRef:
key: {{ .Values.vault.secretPath }}
property: model_registry_api_token
- secretKey: DB_DYNAMIC_DSN
remoteRef:
key: {{ .Values.vault.secretPath }}
property: db_dynamic_dsn
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ml-async-default-deny-all
labels:
app.kubernetes.io/name: ml-async-platform
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ml-async-api-least-privilege
labels:
app.kubernetes.io/name: ml-async-api
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: ml-async-api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.gatewayNamespace }}
ports:
- protocol: TCP
port: {{ .Values.api.port }}
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- protocol: TCP
port: {{ .Values.api.port }}
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.brokerNamespace }}
ports:
- protocol: TCP
port: {{ .Values.networkPolicy.brokerPort }}
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: ml-async-worker
ports:
- protocol: TCP
port: 9090
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ml-async-worker-least-privilege
labels:
app.kubernetes.io/name: ml-async-worker
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: ml-async-worker
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app.kubernetes.io/name: ml-async-api
ports:
- protocol: TCP
port: 9090
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- protocol: TCP
port: 9090
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.brokerNamespace }}
ports:
- protocol: TCP
port: {{ .Values.networkPolicy.brokerPort }}
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.vaultNamespace }}
ports:
- protocol: TCP
port: {{ .Values.networkPolicy.vaultPort }}
- ports:
- protocol: TCP
port: 443
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ .Values.kserve.modelName }}-least-privilege
labels:
app.kubernetes.io/name: {{ .Values.kserve.modelName }}
spec:
podSelector:
matchLabels:
serving.kserve.io/inferenceservice: {{ .Values.kserve.modelName }}
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.gatewayNamespace }}
- podSelector:
matchLabels:
app.kubernetes.io/name: ai-gateway
ports:
- protocol: TCP
port: 8080
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
ports:
- protocol: TCP
port: 8080
egress:
- ports:
- protocol: TCP
port: 443
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: {{ .Values.networkPolicy.vaultNamespace }}
ports:
- protocol: TCP
port: {{ .Values.networkPolicy.vaultPort }}
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: ml-async-api-pdb
labels:
app.kubernetes.io/name: ml-async-api
spec:
minAvailable: {{ .Values.pdb.apiMinAvailable }}
selector:
matchLabels:
app.kubernetes.io/name: ml-async-api
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: ml-async-worker-pdb
labels:
app.kubernetes.io/name: ml-async-worker
spec:
minAvailable: {{ .Values.pdb.workerMinAvailable }}
selector:
matchLabels:
app.kubernetes.io/name: ml-async-worker
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ .Values.serviceAccount.name }}
labels:
app.kubernetes.io/name: ml-async-platform
app.kubernetes.io/part-of: fsds-sota-ai-platform
automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
---
apiVersion: v1
kind: Service
metadata:
name: ml-async-api
labels:
app.kubernetes.io/name: ml-async-api
app.kubernetes.io/component: api
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: ml-async-api
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: ml-async-api-route
labels:
app.kubernetes.io/name: ml-async-api
spec:
parentRefs:
- name: {{ .Values.kserve.gatewayName }}
namespace: {{ .Values.kserve.gatewayNamespace }}
rules:
- matches:
- path:
type: PathPrefix
value: /v1/jobs
backendRefs:
- name: ml-async-api
port: 80
weight: 100
"""FSDS-SOTA-2026 Track 2 Lab 13: Cloud-Native K8s, Helmfile, Vault, KEDA, KServe & Async AI Platform."""
from __future__ import annotations
__all__ = [
"manifest_and_vault_audit",
"scheduler_keda_and_async_app",
]
"""Pure-Python Tier-1 Kubernetes, Helmfile, Helm Template & Vault Secret Hygiene Auditor."""
from __future__ import annotations
import copy
import re
from pathlib import Path
from typing import Any
import yaml
_DEFAULT_LAB_ROOT = Path(__file__).resolve().parents[2]
_IF_START_RE = re.compile(r"^\s*\{\{-?\s*if\s+(.+?)\s*-?\}\}\s*$")
_ELSE_RE = re.compile(r"^\s*\{\{-?\s*else\s*-?\}\}\s*$")
_END_RE = re.compile(r"^\s*\{\{-?\s*end\s*-?\}\}\s*$")
_VAR_EXPR_RE = re.compile(r"\{\{\s*\.Values\.([A-Za-z0-9_.-]+)\s*\}\}")
_PLAINTEXT_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
("private_key_block", re.compile(r"-----BEGIN\s+(?:RSA|EC|OPENSSH|DSA)?\s*PRIVATE KEY-----")),
("vault_root_or_service_token", re.compile(r"\bhv[sb]\.[A-Za-z0-9_-]{12,}\b")),
("aws_access_key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
("github_pat", re.compile(r"\bgh[ps]_[A-Za-z0-9]{20,}\b")),
("bearer_literal", re.compile(r"\bBearer\s+[A-Za-z0-9._-]{12,}\b")),
)
_SENSITIVE_KEY_EXACT = {
"password",
"passwd",
"secret",
"api_key",
"apikey",
"private_key",
"client_secret",
"vault_token",
"db_password",
"access_token",
"refresh_token",
}
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
merged = copy.deepcopy(base)
for k, v in override.items():
if isinstance(v, dict) and isinstance(merged.get(k), dict):
merged[k] = _deep_merge(merged[k], v)
else:
merged[k] = copy.deepcopy(v)
return merged
def _resolve_dot_path(values: dict[str, Any], dotted_path: str) -> Any:
cur: Any = values
for part in dotted_path.split("."):
if isinstance(cur, dict) and part in cur:
cur = cur[part]
else:
return None
return cur
def _eval_helm_condition(expr: str, values: dict[str, Any]) -> bool:
stripped = expr.strip()
if stripped.startswith("eq "):
# Support `eq .Values.a.b "literal"`
parts = stripped[3:].strip().split(maxsplit=1)
if len(parts) == 2 and parts[0].startswith(".Values."):
lhs = _resolve_dot_path(values, parts[0][len(".Values.") :])
rhs = parts[1].strip().strip('"').strip("'")
return str(lhs) == rhs
return False
if stripped.startswith(".Values."):
return bool(_resolve_dot_path(values, stripped[len(".Values.") :]))
return False
def render_helm_template_text(raw_text: str, values: dict[str, Any]) -> str:
"""Deterministically evaluate Helm `if/else/end` blocks and `.Values.*` substitutions."""
out_lines: list[str] = []
# Stack entries: (branch_active, any_branch_matched)
cond_stack: list[bool] = []
for line in raw_text.splitlines():
m_if = _IF_START_RE.match(line)
if m_if:
parent_active = all(cond_stack)
cond_val = parent_active and _eval_helm_condition(m_if.group(1), values)
cond_stack.append(cond_val)
continue
if _ELSE_RE.match(line):
if cond_stack:
parent_active = all(cond_stack[:-1])
cond_stack[-1] = parent_active and (not cond_stack[-1])
continue
if _END_RE.match(line):
if cond_stack:
cond_stack.pop()
continue
if not all(cond_stack):
continue
def _sub(match: re.Match[str]) -> str:
val = _resolve_dot_path(values, match.group(1))
if isinstance(val, bool):
return "true" if val else "false"
return "" if val is None else str(val)
out_lines.append(_VAR_EXPR_RE.sub(_sub, line))
return "\n".join(out_lines) + "\n"
def load_and_render_helm_chart(
chart_dir: Path,
overrides: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""Render all templates in `chart_dir` against `values.yaml` (+ optional overrides)."""
chart_meta = yaml.safe_load((chart_dir / "Chart.yaml").read_text(encoding="utf-8"))
if not isinstance(chart_meta, dict) or not chart_meta.get("name"):
raise ValueError("Invalid Chart.yaml metadata")
base_values = yaml.safe_load((chart_dir / "values.yaml").read_text(encoding="utf-8"))
if not isinstance(base_values, dict):
raise ValueError("Invalid values.yaml structure")
merged_values = _deep_merge(base_values, overrides or {})
templates_dir = chart_dir / "templates"
rendered_docs: list[dict[str, Any]] = []
for tpl_path in sorted(templates_dir.glob("*.yaml")):
rendered_yaml = render_helm_template_text(
tpl_path.read_text(encoding="utf-8"), merged_values
)
for doc in yaml.safe_load_all(rendered_yaml):
if isinstance(doc, dict) and doc:
rendered_docs.append(doc)
return rendered_docs
def _topological_sort_releases(releases: list[dict[str, Any]]) -> list[str]:
names = [f"{r['namespace']}/{r['name']}" for r in releases]
short_to_full = {str(r["name"]): f"{r['namespace']}/{r['name']}" for r in releases}
deps: dict[str, set[str]] = {n: set() for n in names}
for rel in releases:
full_name = f"{rel['namespace']}/{rel['name']}"
for need in rel.get("needs", []) or []:
need_str = str(need)
target = need_str if need_str in deps else short_to_full.get(need_str, need_str)
if target not in deps:
raise ValueError(f"Helmfile release '{full_name}' depends on unknown '{need_str}'")
deps[full_name].add(target)
ordered: list[str] = []
remaining = {k: set(v) for k, v in deps.items()}
while remaining:
ready = sorted(k for k, v in remaining.items() if not v)
if not ready:
raise ValueError(f"Cyclic dependency detected in helmfile releases: {remaining}")
for node in ready:
ordered.append(node)
del remaining[node]
for v in remaining.values():
v.difference_update(ready)
return ordered
def _render_helmfile_for_env(raw_text: str, env_values: dict[str, Any]) -> dict[str, Any]:
def _sub(match: re.Match[str]) -> str:
key = match.group(1)
val = env_values.get(key)
return "null" if val is None else str(val)
rendered = _VAR_EXPR_RE.sub(_sub, raw_text)
loaded = yaml.safe_load(rendered)
if not isinstance(loaded, dict):
raise ValueError("helmfile.yaml.gotmpl must parse to a mapping")
return loaded
def audit_helmfile(helmfile_path: Path) -> dict[str, Any]:
"""Validate Helmfile `.yaml.gotmpl`, `dev`/`prod` envs, unquoted ints, PDB headroom & DAG."""
raw_text = helmfile_path.read_text(encoding="utf-8")
violations: list[str] = []
has_go_templates = bool(re.search(r"\{\{.*?\}\}", raw_text))
if not helmfile_path.name.endswith(".gotmpl"):
if has_go_templates:
violations.append(
f"Helmfile '{helmfile_path.name}' uses Go templates without '.gotmpl' extension"
)
try:
yaml.safe_load(raw_text)
except yaml.YAMLError:
violations.append(
f"Plain '.yaml' Helmfile '{helmfile_path.name}' failed YAML parsing "
"(raw unquoted Go template '{{ ... }}')"
)
sanitized = re.sub(r'(?<!")(\{\{[-]?.*?[-]?\}\})(?!")', r'"\1"', raw_text)
data = yaml.safe_load(sanitized)
if not isinstance(data, dict):
raise ValueError("helmfile.yaml.gotmpl must parse to a mapping")
envs_map = data.get("environments") or {}
envs = sorted(envs_map.keys())
releases = data.get("releases") or []
release_names = [str(r["name"]) for r in releases]
topo_order = _topological_sort_releases(releases)
for req_env in ("dev", "prod"):
if req_env not in envs:
violations.append(f"Missing helmfile environment '{req_env}'")
for req_rel in ("vault-eso", "keda", "kserve", "ml-async-platform"):
if req_rel not in release_names:
violations.append(f"Missing helmfile release '{req_rel}'")
expected_gpu = {"dev": "dra", "prod": "mig"}
for env_name in ("dev", "prod"):
env_vals_list = (envs_map.get(env_name) or {}).get("values") or []
env_vals = env_vals_list[0] if env_vals_list and isinstance(env_vals_list[0], dict) else {}
if env_vals:
if env_vals.get("gpuMode") != expected_gpu[env_name]:
violations.append(
f"Environment '{env_name}' must use gpuMode={expected_gpu[env_name]}"
)
if int(env_vals.get("apiReplicas", 0)) <= 2:
violations.append(f"Environment '{env_name}' apiReplicas must be > 2 for PDB headroom")
if int(env_vals.get("workerMinReplicas", 0)) <= 1:
violations.append(
f"Environment '{env_name}' workerMinReplicas must be > 1 for PDB headroom"
)
rendered_hf = _render_helmfile_for_env(raw_text, env_vals)
app_rel = next(
(r for r in (rendered_hf.get("releases") or []) if r.get("name") == "ml-async-platform"),
None,
)
if app_rel and isinstance(app_rel.get("values"), list) and app_rel["values"]:
rv = app_rel["values"][0]
if not isinstance(rv.get("api", {}).get("replicas"), int) or isinstance(
rv.get("api", {}).get("replicas"), bool
):
violations.append(f"helmfile '{env_name}' api.replicas must be unquoted integer")
keda_v = rv.get("keda", {})
for k_field in ("minReplicaCount", "maxReplicaCount"):
if not isinstance(keda_v.get(k_field), int) or isinstance(
keda_v.get(k_field), bool
):
violations.append(
f"helmfile '{env_name}' keda.{k_field} must be unquoted integer"
)
kserve_v = rv.get("kserve", {})
if not isinstance(kserve_v.get("canaryTrafficPercent"), int) or isinstance(
kserve_v.get("canaryTrafficPercent"), bool
):
violations.append(
f"helmfile '{env_name}' kserve.canaryTrafficPercent must be unquoted integer"
)
return {
"passed": len(violations) == 0,
"environments": envs,
"release_names": release_names,
"topological_order": topo_order,
"violations": violations,
}
def _scan_yaml_mapping_for_secrets(obj: Any, path_prefix: str, findings: list[str]) -> None:
if isinstance(obj, dict):
if obj.get("kind") == "Secret" and (obj.get("data") or obj.get("stringData")):
findings.append(f"{path_prefix}: Raw K8s Secret with inline data/stringData found")
for k, v in obj.items():
key_l = str(k).lower()
next_path = f"{path_prefix}.{k}"
if key_l in _SENSITIVE_KEY_EXACT and isinstance(v, str):
cleaned = v.strip()
if cleaned and "{{" not in cleaned and not cleaned.startswith("vault:"):
findings.append(f"{next_path}: Plaintext sensitive credential assignment")
_scan_yaml_mapping_for_secrets(v, next_path, findings)
elif isinstance(obj, list):
for idx, item in enumerate(obj):
_scan_yaml_mapping_for_secrets(item, f"{path_prefix}[{idx}]", findings)
def scan_directory_secret_hygiene(root_dir: Path) -> dict[str, Any]:
"""Scan all YAML/Helm manifests for hardcoded secrets, tokens, or raw K8s Secrets."""
findings: list[str] = []
scanned_files: list[str] = []
yaml_files = sorted(
[
*root_dir.rglob("*.yaml"),
*root_dir.rglob("*.yml"),
*root_dir.rglob("*.gotmpl"),
]
)
for yf in yaml_files:
rel = yf.relative_to(root_dir).as_posix()
scanned_files.append(rel)
raw_text = yf.read_text(encoding="utf-8")
for label, pat in _PLAINTEXT_SECRET_PATTERNS:
if pat.search(raw_text):
findings.append(f"{rel}: Matched forbidden secret pattern '{label}'")
# Strip template tags safely to allow structured YAML key-value inspection
sanitized_text = re.sub(r"\{\{[-]?.*?[-]?\}\}", "TEMPLATE_PLACEHOLDER", raw_text)
try:
for doc in yaml.safe_load_all(sanitized_text):
if doc is not None:
_scan_yaml_mapping_for_secrets(doc, rel, findings)
except yaml.YAMLError:
# Templates with conditional YAML indentation are audited after Helm rendering too
pass
return {
"passed": len(findings) == 0,
"scanned_files_count": len(scanned_files),
"scanned_files": scanned_files,
"findings": findings,
}
def _find_resource(
docs: list[dict[str, Any]], kind: str, name: str | None = None
) -> dict[str, Any] | None:
for doc in docs:
if doc.get("kind") != kind:
continue
if name is None or doc.get("metadata", {}).get("name") == name:
return doc
return None
def _is_guaranteed_container(container: dict[str, Any]) -> bool:
res = container.get("resources") or {}
req = res.get("requests") or {}
lim = res.get("limits") or {}
return bool(
req.get("cpu")
and lim.get("cpu")
and req.get("memory")
and lim.get("memory")
and str(req["cpu"]) == str(lim["cpu"])
and str(req["memory"]) == str(lim["memory"])
)
def _check_container_hardened(container: dict[str, Any]) -> list[str]:
issues: list[str] = []
sc = container.get("securityContext") or {}
cname = str(container.get("name", "unknown"))
if sc.get("runAsNonRoot") is not True:
issues.append(f"container {cname}: runAsNonRoot != true")
if sc.get("allowPrivilegeEscalation") is not False:
issues.append(f"container {cname}: allowPrivilegeEscalation != false")
if sc.get("readOnlyRootFilesystem") is not True:
issues.append(f"container {cname}: readOnlyRootFilesystem != true")
dropped = [str(c) for c in (sc.get("capabilities") or {}).get("drop") or []]
if "ALL" not in dropped:
issues.append(f"container {cname}: capabilities.drop missing ALL")
return issues
def audit_rendered_manifests(
docs: list[dict[str, Any]],
expected_gpu_mode: str = "mig",
) -> dict[str, Any]:
"""Audit rendered K8s objects for QoS, PSS, Probes, Vault ESO, KEDA, KServe, NetPol, PDB."""
violations: list[str] = []
# 1. API Deployment
api_dep = _find_resource(docs, "Deployment", "ml-async-api")
if api_dep is None:
violations.append("Missing Deployment ml-async-api")
else:
pod_spec = api_dep["spec"]["template"]["spec"]
pod_sc = pod_spec.get("securityContext") or {}
if pod_sc.get("runAsNonRoot") is not True:
violations.append("ml-async-api pod securityContext.runAsNonRoot != true")
if (pod_sc.get("seccompProfile") or {}).get("type") != "RuntimeDefault":
violations.append("ml-async-api pod seccompProfile.type != RuntimeDefault")
if not pod_spec.get("topologySpreadConstraints"):
violations.append("ml-async-api missing topologySpreadConstraints")
api_c = pod_spec["containers"][0]
if not _is_guaranteed_container(api_c):
violations.append(
"ml-async-api container does not satisfy Guaranteed QoS (requests==limits)"
)
violations.extend(_check_container_hardened(api_c))
for probe in ("startupProbe", "readinessProbe", "livenessProbe"):
if probe not in api_c:
violations.append(f"ml-async-api missing {probe}")
secret_refs = [
ef.get("secretRef", {}).get("name")
for ef in (api_c.get("envFrom") or [])
if isinstance(ef, dict) and ef.get("secretRef")
]
if "ml-async-vault-runtime-secret" not in secret_refs:
violations.append("ml-async-api missing Vault-backed envFrom secretRef")
# 2. Worker Deployment (Init Container + ready.ok, MIG or DRA, graceful drain)
wrk_dep = _find_resource(docs, "Deployment", "ml-async-worker")
if wrk_dep is None:
violations.append("Missing Deployment ml-async-worker")
else:
wrk_spec = wrk_dep["spec"]["template"]["spec"]
init_cs = wrk_spec.get("initContainers") or []
if not init_cs:
violations.append("ml-async-worker missing initContainers preflight check")
else:
init_cmd = " ".join(str(x) for x in (init_cs[0].get("command") or []))
if "/models/ready.ok" not in init_cmd:
violations.append("ml-async-worker initContainer must write /models/ready.ok")
if int(wrk_spec.get("terminationGracePeriodSeconds", 0)) < 30:
violations.append("ml-async-worker terminationGracePeriodSeconds < 30")
wrk_c = wrk_spec["containers"][0]
if not _is_guaranteed_container(wrk_c):
violations.append("ml-async-worker missing Guaranteed CPU/memory parity")
violations.extend(_check_container_hardened(wrk_c))
for probe in ("startupProbe", "readinessProbe", "livenessProbe"):
if probe not in wrk_c:
violations.append(f"ml-async-worker missing {probe}")
if expected_gpu_mode == "mig":
lim = wrk_c.get("resources", {}).get("limits", {})
if "nvidia.com/mig-2g.20gb" not in lim:
violations.append("ml-async-worker mig mode missing nvidia.com/mig-2g.20gb limit")
elif expected_gpu_mode == "dra":
rct = _find_resource(docs, "ResourceClaimTemplate", "ml-async-worker-gpu-claim")
if rct is None:
violations.append("dra mode missing ResourceClaimTemplate")
if not wrk_spec.get("resourceClaims"):
violations.append("dra mode missing pod resourceClaims")
# 3. ServiceAccount least privilege + Vault SecretStore + ExternalSecret
sa = _find_resource(docs, "ServiceAccount", "ml-async-platform-sa")
if sa is None or sa.get("automountServiceAccountToken") is not False:
violations.append("ServiceAccount must disable automountServiceAccountToken by default")
ss = _find_resource(docs, "SecretStore", "vault-kv-secret-store")
es = _find_resource(docs, "ExternalSecret", "ml-async-runtime-external-secret")
if ss is None or es is None:
violations.append("Missing Vault SecretStore or ExternalSecret")
else:
vault_cfg = ss.get("spec", {}).get("provider", {}).get("vault", {})
if vault_cfg.get("version") != "v2":
violations.append("Vault SecretStore must use KV v2")
sa_ref = vault_cfg.get("auth", {}).get("kubernetes", {}).get("serviceAccountRef", {})
if not sa_ref.get("name"):
violations.append("Vault SecretStore missing Kubernetes serviceAccountRef")
if not es.get("spec", {}).get("data"):
violations.append("ExternalSecret missing remoteRef data mappings")
# 4. KEDA ScaledObject + TriggerAuthentication
keda = _find_resource(docs, "ScaledObject", "ml-async-worker-scaler")
if keda is None:
violations.append("Missing KEDA ScaledObject")
else:
ks = keda.get("spec", {})
if ks.get("scaleTargetRef", {}).get("name") != "ml-async-worker":
violations.append("KEDA ScaledObject scaleTargetRef mismatch")
if int(ks.get("minReplicaCount", 0)) < 1:
violations.append("KEDA minReplicaCount must be >= 1 for warm SLA pool")
triggers = ks.get("triggers") or []
if not triggers:
violations.append("KEDA ScaledObject missing triggers")
else:
auth_name = (triggers[0].get("authenticationRef") or {}).get("name")
if not auth_name or _find_resource(docs, "TriggerAuthentication", str(auth_name)) is None:
violations.append(
f"KEDA TriggerAuthentication '{auth_name}' missing for authenticationRef"
)
# 5. KServe InferenceService + Gateway API HTTPRoute
isvc = _find_resource(docs, "InferenceService")
http_route = _find_resource(docs, "HTTPRoute", "ml-async-api-route")
if isvc is None:
violations.append("Missing KServe InferenceService")
else:
pred = isvc.get("spec", {}).get("predictor", {})
if "canaryTrafficPercent" not in pred:
violations.append("KServe InferenceService missing canaryTrafficPercent")
if pred.get("automountServiceAccountToken") is not False:
violations.append(
"KServe InferenceService predictor must disable automountServiceAccountToken"
)
if isvc.get("metadata", {}).get("annotations", {}).get("prometheus.io/scrape") != "true":
violations.append("KServe InferenceService missing prometheus.io/scrape annotation")
model_spec = pred.get("model") or {}
violations.extend(_check_container_hardened({"name": "kserve-model", **model_spec}))
for probe in ("startupProbe", "readinessProbe", "livenessProbe"):
if probe not in model_spec:
violations.append(f"KServe InferenceService model missing {probe}")
k_res = model_spec.get("resources") or {}
if "nvidia.com/gpu" not in (k_res.get("requests") or {}) or "nvidia.com/gpu" not in (
k_res.get("limits") or {}
):
violations.append("KServe InferenceService model missing explicit nvidia.com/gpu resources")
if http_route is None:
violations.append("Missing Gateway API HTTPRoute")
# 6. NetworkPolicy + PDB (with DisruptionsAllowed >= 1)
np_deny = _find_resource(docs, "NetworkPolicy", "ml-async-default-deny-all")
np_api = _find_resource(docs, "NetworkPolicy", "ml-async-api-least-privilege")
np_wrk = _find_resource(docs, "NetworkPolicy", "ml-async-worker-least-privilege")
np_kserve = _find_resource(docs, "NetworkPolicy", "doc-ocr-reranker-least-privilege")
pdb_api = _find_resource(docs, "PodDisruptionBudget", "ml-async-api-pdb")
pdb_wrk = _find_resource(docs, "PodDisruptionBudget", "ml-async-worker-pdb")
if np_deny is None or np_api is None or np_wrk is None or np_kserve is None:
violations.append(
"Missing default-deny, api, worker, or kserve predictor NetworkPolicy"
)
else:
wrk_egress_ports = {
p.get("port")
for rule in (np_wrk.get("spec", {}).get("egress") or [])
for p in (rule.get("ports") or [])
}
if 443 not in wrk_egress_ports:
violations.append("ml-async-worker NetworkPolicy missing TCP 443 egress for S3 artifacts")
api_ingress_ports = {
p.get("port")
for rule in (np_api.get("spec", {}).get("ingress") or [])
for p in (rule.get("ports") or [])
}
wrk_ingress_ports = {
p.get("port")
for rule in (np_wrk.get("spec", {}).get("ingress") or [])
for p in (rule.get("ports") or [])
}
if 8080 not in api_ingress_ports or 9090 not in wrk_ingress_ports:
violations.append("NetworkPolicy missing Prometheus metrics scrape ingress ports")
if pdb_api is None or pdb_wrk is None:
violations.append("Missing PodDisruptionBudget for API or Worker")
else:
api_min_av = int(pdb_api.get("spec", {}).get("minAvailable", 0))
wrk_min_av = int(pdb_wrk.get("spec", {}).get("minAvailable", 0))
if api_dep is not None and int(api_dep["spec"].get("replicas", 0)) <= api_min_av:
violations.append("ml-async-api replicas <= PDB minAvailable (DisruptionsAllowed == 0)")
if keda is not None and int(keda.get("spec", {}).get("minReplicaCount", 0)) <= wrk_min_av:
violations.append(
"ml-async-worker minReplicaCount <= PDB minAvailable (DisruptionsAllowed == 0)"
)
# Ensure zero inline plaintext Secret documents exist in rendered output
if _find_resource(docs, "Secret") is not None:
violations.append(
"Rendered chart must NOT contain inline Secret objects (use ESO ExternalSecret)"
)
kinds_rendered = sorted({str(d.get("kind")) for d in docs})
return {
"passed": len(violations) == 0,
"gpu_mode": expected_gpu_mode,
"rendered_resource_count": len(docs),
"kinds_rendered": kinds_rendered,
"violations": violations,
}
def run_tier1_manifest_audit(lab_root: Path | None = None) -> dict[str, Any]:
"""Run complete Tier-1 verification across Helmfile, secret hygiene, MIG mode, and DRA mode."""
root = lab_root or _DEFAULT_LAB_ROOT
helmfile_res = audit_helmfile(root / "helmfile.yaml.gotmpl")
secret_res = scan_directory_secret_hygiene(root)
chart_dir = root / "charts" / "ml-async-platform"
mig_docs = load_and_render_helm_chart(chart_dir, overrides={"worker": {"gpuMode": "mig"}})
mig_audit = audit_rendered_manifests(mig_docs, expected_gpu_mode="mig")
dra_docs = load_and_render_helm_chart(
chart_dir,
overrides={
"environment": "dev",
"worker": {"gpuMode": "dra"},
"kserve": {"canaryTrafficPercent": 20},
},
)
dra_audit = audit_rendered_manifests(dra_docs, expected_gpu_mode="dra")
all_passed = bool(
helmfile_res["passed"]
and secret_res["passed"]
and mig_audit["passed"]
and dra_audit["passed"]
)
return {
"all_passed": all_passed,
"helmfile": helmfile_res,
"secret_hygiene": secret_res,
"prod_mig_render": mig_audit,
"dev_dra_render": dra_audit,
}
"""K8s Scheduler, QoS/OOMKill, MIG/DRA GPU Packing, KEDA vs HPA, Canary/Vault & FastAPI Async Jobs."""
from __future__ import annotations
import math
import threading
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Any, Literal
import numpy as np
from fastapi import FastAPI, HTTPException, status
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from pydantic import BaseModel, ConfigDict, Field
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded FIFO OpenTelemetry span exporter backed by deque(maxlen=256)."""
def __init__(self, maxlen: int = 256) -> None:
self._spans: deque[ReadableSpan] = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def create_in_memory_telemetry(
service_name: str = "fsds-lab13-k8s-async-platform",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create a real OpenTelemetry TracerProvider backed by BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("k8s_ai_platform_lab")
return provider, exporter, tracer
def summarize_finished_spans(
exporter: BoundedInMemorySpanExporter | InMemorySpanExporter,
) -> dict[str, Any]:
"""Serialize captured OpenTelemetry spans into JSON-safe artifact records."""
spans = exporter.get_finished_spans()
return {
"span_count": len(spans),
"span_names": [span.name for span in spans],
"spans": [
{
"name": span.name,
"status": span.status.status_code.name,
"attributes": dict(span.attributes or {}),
}
for span in spans
],
}
# ---------------------------------------------------------------------------
# 1. K8s Two-Phase Scheduler (Filter -> Score), QoS/OOMKill & GPU Sharing
# ---------------------------------------------------------------------------
class ClusterNode(BaseModel):
model_config = ConfigDict(extra="forbid")
node_id: str
zone: str
allocatable_cpu_m: int = Field(gt=0)
allocatable_mem_mib: int = Field(gt=0)
total_gpus: int = Field(ge=0)
taints: list[str] = Field(default_factory=list)
cached_images: list[str] = Field(default_factory=list)
class PodScheduleRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
pod_name: str
cpu_request_m: int = Field(ge=0)
cpu_limit_m: int = Field(ge=0)
mem_request_mib: int = Field(ge=0)
mem_limit_mib: int = Field(ge=0)
gpu_request: int = Field(default=0, ge=0)
image: str = "ghcr.io/fsds-sota/ml-async-api:2026.1.0"
tolerations: list[str] = Field(default_factory=list)
def classify_pod_qos(
cpu_request_m: int,
cpu_limit_m: int,
mem_request_mib: int,
mem_limit_mib: int,
node_mem_mib: int = 32_768,
) -> dict[str, Any]:
"""Classify Kubernetes Pod QoS (`Guaranteed`, `Burstable`, `BestEffort`) and `oom_score_adj`."""
if (
cpu_request_m > 0
and cpu_limit_m > 0
and mem_request_mib > 0
and mem_limit_mib > 0
and cpu_request_m == cpu_limit_m
and mem_request_mib == mem_limit_mib
):
return {
"qos_class": "Guaranteed",
"oom_score_adj": -997,
"eviction_tier": 3,
}
if cpu_request_m == 0 and cpu_limit_m == 0 and mem_request_mib == 0 and mem_limit_mib == 0:
return {
"qos_class": "BestEffort",
"oom_score_adj": 1000,
"eviction_tier": 1,
}
mem_pct = (mem_request_mib / max(1, node_mem_mib)) * 100.0
oom_adj = max(2, min(999, round(1000.0 - 10.0 * mem_pct)))
return {
"qos_class": "Burstable",
"oom_score_adj": int(oom_adj),
"eviction_tier": 2,
}
def schedule_pods_two_phase(
nodes: list[ClusterNode],
pods: list[PodScheduleRequest],
) -> dict[str, Any]:
"""Simulate kube-scheduler `Filter` (Fit + Taints) and `Score` (Image + Topology + Fit)."""
used_cpu: dict[str, int] = {n.node_id: 0 for n in nodes}
used_mem: dict[str, int] = {n.node_id: 0 for n in nodes}
used_gpu: dict[str, int] = {n.node_id: 0 for n in nodes}
zone_counts: dict[str, int] = {}
placements: list[dict[str, Any]] = []
unschedulable: list[str] = []
for pod in pods:
feasible: list[ClusterNode] = []
for node in nodes:
if any(t not in pod.tolerations for t in node.taints):
continue
if used_cpu[node.node_id] + pod.cpu_request_m > node.allocatable_cpu_m:
continue
if used_mem[node.node_id] + pod.mem_request_mib > node.allocatable_mem_mib:
continue
if used_gpu[node.node_id] + pod.gpu_request > node.total_gpus:
continue
feasible.append(node)
if not feasible:
unschedulable.append(pod.pod_name)
placements.append(
{
"pod_name": pod.pod_name,
"status": "Pending",
"node_id": None,
"zone": None,
"score": 0.0,
}
)
continue
scored: list[tuple[float, str, ClusterNode]] = []
max_zone_cnt = max((zone_counts.get(n.zone, 0) for n in feasible), default=0)
for node in feasible:
rem_cpu_ratio = (
node.allocatable_cpu_m - used_cpu[node.node_id] - pod.cpu_request_m
) / node.allocatable_cpu_m
rem_mem_ratio = (
node.allocatable_mem_mib - used_mem[node.node_id] - pod.mem_request_mib
) / node.allocatable_mem_mib
fit_score = 30.0 * ((rem_cpu_ratio + rem_mem_ratio) / 2.0)
image_score = 30.0 if pod.image in node.cached_images else 0.0
z_cnt = zone_counts.get(node.zone, 0)
topo_score = 40.0 * (1.0 - (z_cnt / max(1, max_zone_cnt + 1)))
total_score = round(fit_score + image_score + topo_score, 2)
scored.append((total_score, node.node_id, node))
scored.sort(key=lambda item: (-item[0], item[1]))
best_score, _, best_node = scored[0]
used_cpu[best_node.node_id] += pod.cpu_request_m
used_mem[best_node.node_id] += pod.mem_request_mib
used_gpu[best_node.node_id] += pod.gpu_request
zone_counts[best_node.zone] = zone_counts.get(best_node.zone, 0) + 1
placements.append(
{
"pod_name": pod.pod_name,
"status": "Scheduled",
"node_id": best_node.node_id,
"zone": best_node.zone,
"score": best_score,
}
)
return {
"scheduled_count": len(pods) - len(unschedulable),
"pending_count": len(unschedulable),
"unschedulable_pods": unschedulable,
"zone_distribution": zone_counts,
"placements": placements,
}
def simulate_qos_and_oomkill_eviction(node_mem_mib: int = 32_768) -> dict[str, Any]:
"""Simulate kubelet eviction priority under memory pressure (`BestEffort` -> `Guaranteed`)."""
workload_specs = [
("api-pod-0", 1000, 1000, 2048, 2048, 1950),
("api-pod-1", 1000, 1000, 2048, 2048, 1980),
("kserve-pred-0", 1000, 1000, 4096, 4096, 3900),
("etl-burst-0", 500, 2000, 2048, 8192, 6800),
("etl-burst-1", 500, 2000, 2048, 8192, 6200),
("embed-burst-2", 500, 2000, 4096, 8192, 7100),
("embed-burst-3", 500, 2000, 4096, 8192, 5400),
("debug-shell-0", 0, 0, 0, 0, 1800),
("adhoc-nb-1", 0, 0, 0, 0, 2100),
("adhoc-nb-2", 0, 0, 0, 0, 1900),
]
pods: list[dict[str, Any]] = []
for name, c_req, c_lim, m_req, m_lim, actual_mib in workload_specs:
cls = classify_pod_qos(c_req, c_lim, m_req, m_lim, node_mem_mib=node_mem_mib)
over_req = max(0, actual_mib - m_req)
bump = 40 if cls["qos_class"] == "Burstable" and over_req > 0 else 0
effective_oom = cls["oom_score_adj"] + bump
pods.append(
{
"pod_name": name,
"qos_class": cls["qos_class"],
"oom_score_adj": cls["oom_score_adj"],
"effective_oom_score": min(1000, effective_oom),
"mem_request_mib": m_req,
"mem_actual_mib": actual_mib,
"evicted": False,
"evicted_at_pressure_pct": None,
}
)
# Total initial actual memory = 39,130 MiB > 32,768 MiB -> pressure relief loop to <= 85% target
target_limit_mib = int(node_mem_mib * 0.85)
pressure_steps = [
("86% High Pressure", int(node_mem_mib * 0.88)),
("94% Severe Pressure", int(node_mem_mib * 0.85)),
("98% Critical OOM", target_limit_mib),
]
current_used = sum(int(p["mem_actual_mib"]) for p in pods)
eviction_order: list[str] = []
# Sort candidates by highest effective_oom_score (BestEffort=1000 first, Guaranteed=-997 last)
candidates = sorted(
pods,
key=lambda p: (-int(p["effective_oom_score"]), -int(p["mem_actual_mib"]), str(p["pod_name"])),
)
for step_label, threshold in pressure_steps:
for cand in candidates:
if current_used <= threshold:
break
if cand["evicted"] or cand["qos_class"] == "Guaranteed":
continue
cand["evicted"] = True
cand["evicted_at_pressure_pct"] = step_label
current_used -= int(cand["mem_actual_mib"])
eviction_order.append(str(cand["pod_name"]))
by_qos: dict[str, dict[str, int]] = {
q: {"total": 0, "alive": 0, "evicted": 0}
for q in ("Guaranteed", "Burstable", "BestEffort")
}
for p in pods:
q = str(p["qos_class"])
by_qos[q]["total"] += 1
if p["evicted"]:
by_qos[q]["evicted"] += 1
else:
by_qos[q]["alive"] += 1
guaranteed_survival_pct = round(
(by_qos["Guaranteed"]["alive"] / max(1, by_qos["Guaranteed"]["total"])) * 100.0, 2
)
best_effort_evicted_pct = round(
(by_qos["BestEffort"]["evicted"] / max(1, by_qos["BestEffort"]["total"])) * 100.0, 2
)
return {
"node_mem_mib": node_mem_mib,
"initial_used_mib": sum(int(p["mem_actual_mib"]) for p in pods),
"final_used_mib": current_used,
"guaranteed_survival_pct": guaranteed_survival_pct,
"best_effort_evicted_pct": best_effort_evicted_pct,
"eviction_order": eviction_order,
"by_qos": by_qos,
"pods": pods,
}
def evaluate_gpu_scheduling_strategies(
n_gpus: int = 4,
gpu_vram_gb: int = 80,
n_workloads: int = 12,
workload_vram_gb: float = 16.0,
spike_vram_gb: float = 52.0,
) -> dict[str, Any]:
"""Compare Whole GPU, Time-Slicing, NVIDIA MIG 2g.20gb, and Kubernetes DRA ResourceClaims."""
total_cluster_vram = float(n_gpus * gpu_vram_gb)
# 1. Whole GPU (Device Plugin 1:1)
whole_cap = n_gpus
whole_admitted = min(n_workloads, whole_cap)
whole_util_pct = round((whole_admitted * workload_vram_gb / total_cluster_vram) * 100.0, 2)
# 2. Time-Slicing (4 virtual replicas/GPU, 0% VRAM hardware isolation)
ts_slices_per_gpu = 4
ts_cap = n_gpus * ts_slices_per_gpu
ts_admitted = min(n_workloads, ts_cap)
ts_per_gpu0 = math.ceil(ts_admitted / n_gpus)
gpu0_spike_total = (max(0, ts_per_gpu0 - 1) * workload_vram_gb) + spike_vram_gb
ts_spillover_kills = max(0, ts_per_gpu0 - 1) if gpu0_spike_total > gpu_vram_gb else 0
ts_util_pct = round((ts_admitted * workload_vram_gb / total_cluster_vram) * 100.0, 2)
# 3. NVIDIA MIG 2g.20gb (3x20GB on 80GB GPU, 2x20GB on 40GB GPU)
mig_slice_vram = 20.0
max_mig_slots = 3 if gpu_vram_gb >= 80 else (2 if gpu_vram_gb >= 40 else 1)
if workload_vram_gb <= mig_slice_vram:
mig_slices_per_gpu = max_mig_slots
elif workload_vram_gb <= gpu_vram_gb:
mig_slices_per_gpu = 1
else:
mig_slices_per_gpu = 0
mig_cap = n_gpus * mig_slices_per_gpu
mig_admitted = min(n_workloads, mig_cap)
mig_util_pct = round((mig_admitted * workload_vram_gb / total_cluster_vram) * 100.0, 2)
# 4. Kubernetes DRA ResourceClaim (right-sized 16 GB fractional claims + NVLink awareness)
dra_claims_per_gpu = math.floor(gpu_vram_gb / workload_vram_gb)
dra_cap = n_gpus * dra_claims_per_gpu
dra_admitted = min(n_workloads, dra_cap)
dra_max_util_pct = round((dra_cap * workload_vram_gb / total_cluster_vram) * 100.0, 2)
dra_admitted_util_pct = round((dra_admitted * workload_vram_gb / total_cluster_vram) * 100.0, 2)
profiles = [
{
"strategy": "whole_gpu",
"label": "Whole GPU (nvidia.com/gpu: 1)",
"max_workload_capacity": whole_cap,
"admitted_workloads": whole_admitted,
"pending_workloads": max(0, n_workloads - whole_admitted),
"admission_rate_pct": round((whole_admitted / max(1, n_workloads)) * 100.0, 2),
"vram_utilization_pct": whole_util_pct,
"hardware_vram_isolation": True,
"spillover_neighbor_kills": 0,
"packing_density_vs_whole_x": 1.0,
},
{
"strategy": "time_slicing",
"label": "GPU Time-Slicing (Shared Context)",
"max_workload_capacity": ts_cap,
"admitted_workloads": ts_admitted,
"pending_workloads": max(0, n_workloads - ts_admitted),
"admission_rate_pct": round((ts_admitted / max(1, n_workloads)) * 100.0, 2),
"vram_utilization_pct": ts_util_pct,
"hardware_vram_isolation": False,
"spillover_neighbor_kills": ts_spillover_kills,
"packing_density_vs_whole_x": round(ts_admitted / max(1, whole_admitted), 2),
},
{
"strategy": "mig_2g_20gb",
"label": "NVIDIA MIG (mig-2g.20gb)",
"max_workload_capacity": mig_cap,
"admitted_workloads": mig_admitted,
"pending_workloads": max(0, n_workloads - mig_admitted),
"admission_rate_pct": round((mig_admitted / max(1, n_workloads)) * 100.0, 2),
"vram_utilization_pct": mig_util_pct,
"hardware_vram_isolation": True,
"spillover_neighbor_kills": 0,
"packing_density_vs_whole_x": round(mig_admitted / max(1, whole_admitted), 2),
},
{
"strategy": "dra_resource_claim",
"label": "K8s DRA (ResourceClaim 16GB)",
"max_workload_capacity": dra_cap,
"admitted_workloads": dra_admitted,
"pending_workloads": max(0, n_workloads - dra_admitted),
"admission_rate_pct": round((dra_admitted / max(1, n_workloads)) * 100.0, 2),
"vram_utilization_pct": dra_admitted_util_pct,
"peak_packable_vram_util_pct": dra_max_util_pct,
"hardware_vram_isolation": True,
"spillover_neighbor_kills": 0,
"packing_density_vs_whole_x": round(dra_cap / max(1, whole_admitted), 2),
},
]
return {
"n_gpus": n_gpus,
"gpu_vram_gb": gpu_vram_gb,
"total_cluster_vram_gb": total_cluster_vram,
"requested_workloads": n_workloads,
"workload_vram_gb": workload_vram_gb,
"mig_density_gain_x": profiles[2]["packing_density_vs_whole_x"],
"dra_peak_capacity_gain_x": profiles[3]["packing_density_vs_whole_x"],
"profiles": profiles,
}
# ---------------------------------------------------------------------------
# 2. KEDA Queue-Depth vs CPU-Only HPA Bursty AI Traffic Benchmark
# ---------------------------------------------------------------------------
def _simulate_autoscaler_trace(
arrivals: list[int],
mode: Literal["cpu_hpa", "keda_queue"],
jobs_per_worker_tick: int = 4,
min_replicas: int = 2,
max_replicas: int = 12,
tick_sec: int = 10,
sla_wait_sec: float = 30.0,
) -> dict[str, Any]:
replicas = min_replicas
backlog = 0
history: list[dict[str, Any]] = []
cpu_lag_buffer: deque[float] = deque([15.0, 15.0], maxlen=2)
scale_down_cooldown = 0
total_jobs_arrived = sum(arrivals)
sla_compliant_ticks = 0
for tick, incoming in enumerate(arrivals):
backlog += incoming
capacity = replicas * jobs_per_worker_tick
processed = min(backlog, capacity)
backlog -= processed
# GPU/I/O-bound worker: ~12% idle CPU + 30% busy + light queue polling overhead
busy_ratio = min(1.0, (backlog + processed) / max(1, capacity))
cpu_util_pct = round(min(92.0, 12.0 + 30.0 * busy_ratio + 0.09 * min(backlog, 220)), 1)
cpu_lag_buffer.append(cpu_util_pct)
wait_sec = round((backlog / max(1, capacity)) * tick_sec, 2)
if wait_sec <= sla_wait_sec:
sla_compliant_ticks += 1
history.append(
{
"tick": tick,
"time_sec": tick * tick_sec,
"arrivals": incoming,
"replicas": replicas,
"backlog": backlog,
"cpu_util_pct": cpu_util_pct,
"queue_wait_sec": wait_sec,
}
)
# Compute next tick replicas
if mode == "cpu_hpa":
delayed_cpu = cpu_lag_buffer[0]
target_cpu = 70.0
raw_desired = math.ceil(replicas * (delayed_cpu / target_cpu))
desired = max(min_replicas, min(max_replicas, raw_desired))
if desired > replicas:
replicas = min(max_replicas, replicas + 1) # Slow HPA ramp
scale_down_cooldown = 3
elif desired < replicas:
if scale_down_cooldown > 0:
scale_down_cooldown -= 1
else:
replicas = max(min_replicas, replicas - 1)
else:
# KEDA ScaledObject: scale on post-drain pending queue depth (no arrival double-count)
target_queue_per_replica = 4.0
desired_from_lag = math.ceil(backlog / target_queue_per_replica)
desired = max(min_replicas, min(max_replicas, desired_from_lag))
if desired > replicas:
# Up to +4 pods per scaling step as configured in keda-scaledobject.yaml
replicas = min(max_replicas, min(desired, replicas + 4))
scale_down_cooldown = 4
elif desired < replicas:
if scale_down_cooldown > 0:
scale_down_cooldown -= 1
else:
step_down = max(1, math.floor(replicas * 0.25))
replicas = max(min_replicas, max(desired, replicas - step_down))
wait_vals = [float(h["queue_wait_sec"]) for h in history]
backlogs = [int(h["backlog"]) for h in history]
replica_vals = [int(h["replicas"]) for h in history]
p95_wait_sec = round(float(np.percentile(np.array(wait_vals, dtype=np.float64), 95)), 2)
max_backlog = max(backlogs)
sla_compliance_pct = round((sla_compliant_ticks / max(1, len(arrivals))) * 100.0, 2)
return {
"mode": mode,
"total_jobs_arrived": total_jobs_arrived,
"final_backlog": backlog,
"peak_backlog": max_backlog,
"peak_replicas": max(replica_vals),
"p95_queue_wait_sec": p95_wait_sec,
"max_queue_wait_sec": round(max(wait_vals), 2),
"sla_target_sec": sla_wait_sec,
"sla_compliance_pct": sla_compliance_pct,
"history": history,
}
def run_keda_vs_hpa_autoscaling_benchmark(burst_multiplier: int = 8) -> dict[str, Any]:
"""Compare CPU-Only HPA vs KEDA queue-depth scaling under bursty GPU/I/O-bound AI traffic."""
baseline = 4
burst_rate = baseline * burst_multiplier
arrivals = [
burst_rate if 10 <= t <= 27 else baseline
for t in range(60)
]
hpa = _simulate_autoscaler_trace(arrivals, mode="cpu_hpa")
keda = _simulate_autoscaler_trace(arrivals, mode="keda_queue")
wait_speedup_x = round(
hpa["p95_queue_wait_sec"] / max(0.01, keda["p95_queue_wait_sec"]), 2
)
backlog_reduction_x = round(hpa["peak_backlog"] / max(1, keda["peak_backlog"]), 2)
return {
"burst_multiplier_x": burst_multiplier,
"baseline_jobs_per_tick": baseline,
"burst_jobs_per_tick": burst_rate,
"cpu_hpa": hpa,
"keda_queue": keda,
"p95_wait_reduction_x": wait_speedup_x,
"peak_backlog_reduction_x": backlog_reduction_x,
}
# ---------------------------------------------------------------------------
# 3. Canary / Blue-Green Rollout Safety Gate & Vault Dynamic Lease Rotation
# ---------------------------------------------------------------------------
def evaluate_rollout_safety_and_vault_leases(
error_threshold_pct: float = 1.0,
p95_slo_ms: float = 80.0,
lease_ttl_sec: int = 300,
horizon_sec: int = 900,
) -> dict[str, Any]:
"""Evaluate RollingUpdate vs Blue-Green vs Canary SLO gates and Vault dynamic lease rotation."""
degraded_release = {
"version": "v2.1-bad-threshold",
"health_endpoint_ok": True,
"error_rate_pct": 8.5,
"p95_latency_ms": 148.0,
}
healthy_release = {
"version": "v2.2-calibrated",
"health_endpoint_ok": True,
"error_rate_pct": 0.25,
"p95_latency_ms": 42.0,
}
def _slo_passes(rel: dict[str, Any]) -> bool:
return (
float(rel["error_rate_pct"]) <= error_threshold_pct
and float(rel["p95_latency_ms"]) <= p95_slo_ms
)
rolling_degraded = {
"strategy": "RollingUpdate (Health-Probe Only)",
"candidate": degraded_release["version"],
"final_traffic_pct": 100 if degraded_release["health_endpoint_ok"] else 0,
"blast_radius_pct": 100.0,
"decision": "PROMOTED_UNSAFE_100PCT",
}
blue_green_degraded = {
"strategy": "Blue-Green (Pre-Cutover Smoke Gate)",
"candidate": degraded_release["version"],
"final_traffic_pct": 0 if not _slo_passes(degraded_release) else 100,
"blast_radius_pct": 0.0,
"decision": "ABORTED_AT_SMOKE_ZERO_BLAST",
}
canary_steps = [10, 30, 100]
canary_degraded_exposure = 0
for step_pct in canary_steps:
canary_degraded_exposure = step_pct
if not _slo_passes(degraded_release):
break
canary_degraded = {
"strategy": "KServe Canary SLO-Gated (10->30->100%)",
"candidate": degraded_release["version"],
"final_traffic_pct": 0,
"blast_radius_pct": float(canary_degraded_exposure),
"decision": "AUTO_ROLLED_BACK_AT_10PCT",
}
canary_healthy = {
"strategy": "KServe Canary SLO-Gated (10->30->100%)",
"candidate": healthy_release["version"],
"final_traffic_pct": 100 if _slo_passes(healthy_release) else 0,
"blast_radius_pct": 0.0,
"decision": "PROMOTED_100PCT" if _slo_passes(healthy_release) else "ROLLED_BACK",
}
# HashiCorp Vault Dynamic Secret Lease Rotation via ESO
refresh_interval_sec = 60
renew_threshold_sec = int(lease_ttl_sec * 0.30) # Rotate when <= 30% TTL remains
lease_seq = 1
issued_at = 0
rotations: list[dict[str, Any]] = [
{"t_sec": 0, "lease_id": f"vault-lease-{lease_seq:03d}", "event": "INITIAL_ISSUE"}
]
auth_failures = 0
pod_restarts = 0
for t in range(refresh_interval_sec, horizon_sec + 1, refresh_interval_sec):
remaining = lease_ttl_sec - (t - issued_at)
if remaining <= 0:
auth_failures += 1
elif remaining <= renew_threshold_sec:
lease_seq += 1
issued_at = t
rotations.append(
{
"t_sec": t,
"lease_id": f"vault-lease-{lease_seq:03d}",
"event": "ESO_ZERO_DOWNTIME_ROTATE",
}
)
return {
"rollout_comparisons": [
rolling_degraded,
blue_green_degraded,
canary_degraded,
canary_healthy,
],
"vault_lease_rotation": {
"lease_ttl_sec": lease_ttl_sec,
"refresh_interval_sec": refresh_interval_sec,
"horizon_sec": horizon_sec,
"leases_issued": lease_seq,
"auth_failures": auth_failures,
"pod_restarts_required": pod_restarts,
"active_lease_id": f"vault-lease-{lease_seq:03d}",
"rotations": rotations,
},
}
# ---------------------------------------------------------------------------
# 4. Offline FastAPI Async Job Queue Service + Bounded OpenTelemetry
# ---------------------------------------------------------------------------
class AsyncJobCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
task_type: Literal["ocr_extract", "embed_batch", "llm_rerank"]
priority: int = Field(default=5, ge=1, le=10)
idempotency_key: str = Field(min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
payload: dict[str, Any] = Field(default_factory=dict)
simulate_transient_failures: int = Field(default=0, ge=0, le=3)
poison_payload: bool = False
class AsyncJobRecord(BaseModel):
model_config = ConfigDict(extra="forbid")
job_id: str
task_type: Literal["ocr_extract", "embed_batch", "llm_rerank"]
priority: int
idempotency_key: str
status: Literal["QUEUED", "COMPLETED", "DEAD_LETTERED"]
attempts: int
deduplicated: bool = False
result_summary: str | None = None
error_reason: str | None = None
class AsyncJobDrainRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
max_jobs: int = Field(default=10, ge=1, le=100)
max_retries: int = Field(default=2, ge=0, le=5)
class AsyncJobDrainResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
drained_count: int
completed_count: int
dead_lettered_count: int
remaining_queue_depth: int
dlq_depth: int
processed_jobs: list[AsyncJobRecord]
@dataclass
class AsyncPlatformState:
"""In-memory async job broker, idempotency registry, DLQ, and OTel telemetry."""
vault_active_lease_id: str = "vault-lease-001"
qos_class: str = "Guaranteed"
jobs_by_id: dict[str, AsyncJobRecord] = field(default_factory=dict)
idempotency_index: dict[str, str] = field(default_factory=dict)
internal_flags: dict[str, tuple[int, bool]] = field(default_factory=dict)
pending_queue: deque[str] = field(default_factory=deque)
dead_letter_queue: list[str] = field(default_factory=list)
counter: int = 0
tracer: trace.Tracer = field(init=False)
exporter: BoundedInMemorySpanExporter = field(init=False)
def __post_init__(self) -> None:
_provider, exporter, tracer = create_in_memory_telemetry()
self.exporter = exporter
self.tracer = tracer
def create_async_platform_app(state: AsyncPlatformState | None = None) -> FastAPI:
"""Create FastAPI Async Job Queue App (/health, /v1/jobs, /v1/jobs/drain, /v1/jobs/{job_id})."""
bundle = state or AsyncPlatformState()
app = FastAPI(title="FSDS Lab 13 K8s Async Job Platform", version="0.1.0")
app.state.bundle = bundle
@app.get("/health")
def health() -> dict[str, Any]:
return {
"status": "ok",
"qos_class": bundle.qos_class,
"vault_lease_id": bundle.vault_active_lease_id,
"queue_depth": len(bundle.pending_queue),
"dlq_depth": len(bundle.dead_letter_queue),
"total_jobs": len(bundle.jobs_by_id),
}
@app.post("/v1/jobs", response_model=AsyncJobRecord, status_code=status.HTTP_202_ACCEPTED)
def enqueue_job(req: AsyncJobCreateRequest) -> AsyncJobRecord:
with bundle.tracer.start_as_current_span("lab13.api.enqueue_job") as span:
span.set_attribute("job.task_type", req.task_type)
span.set_attribute("job.priority", req.priority)
# Idempotency deduplication check
existing_id = bundle.idempotency_index.get(req.idempotency_key)
if existing_id is not None:
existing = bundle.jobs_by_id[existing_id].model_copy(update={"deduplicated": True})
span.set_attribute("job.id", existing.job_id)
span.set_attribute("job.deduplicated", True)
return existing
bundle.counter += 1
job_id = f"job-{bundle.counter:04d}"
rec = AsyncJobRecord(
job_id=job_id,
task_type=req.task_type,
priority=req.priority,
idempotency_key=req.idempotency_key,
status="QUEUED",
attempts=0,
deduplicated=False,
)
bundle.jobs_by_id[job_id] = rec
bundle.idempotency_index[req.idempotency_key] = job_id
bundle.internal_flags[job_id] = (
req.simulate_transient_failures,
req.poison_payload,
)
bundle.pending_queue.append(job_id)
span.set_attribute("job.id", job_id)
span.set_attribute("job.deduplicated", False)
span.set_attribute("queue.depth", len(bundle.pending_queue))
return rec
@app.post("/v1/jobs/drain", response_model=AsyncJobDrainResponse)
def drain_jobs(req: AsyncJobDrainRequest) -> AsyncJobDrainResponse:
processed: list[AsyncJobRecord] = []
completed_cnt = 0
dlq_cnt = 0
with bundle.tracer.start_as_current_span("lab13.worker.drain_batch") as batch_span:
for _ in range(min(req.max_jobs, len(bundle.pending_queue))):
job_id = bundle.pending_queue.popleft()
rec = bundle.jobs_by_id[job_id]
transient_fails, is_poison = bundle.internal_flags.get(job_id, (0, False))
with bundle.tracer.start_as_current_span("lab13.worker.process_job") as job_span:
job_span.set_attribute("job.id", job_id)
job_span.set_attribute("job.task_type", rec.task_type)
attempts = 0
succeeded = False
err_reason: str | None = None
for attempt in range(1, req.max_retries + 2):
attempts = attempt
if is_poison or attempt <= transient_fails:
err_reason = (
"POISON_PAYLOAD_SCHEMA_FATAL"
if is_poison
else "TRANSIENT_WORKER_GPU_TIMEOUT"
)
continue
succeeded = True
err_reason = None
break
if succeeded:
updated = rec.model_copy(
update={
"status": "COMPLETED",
"attempts": attempts,
"result_summary": f"{rec.task_type}_ok_in_{attempts}_attempt(s)",
"error_reason": None,
}
)
completed_cnt += 1
else:
updated = rec.model_copy(
update={
"status": "DEAD_LETTERED",
"attempts": attempts,
"error_reason": err_reason,
}
)
bundle.dead_letter_queue.append(job_id)
dlq_cnt += 1
bundle.jobs_by_id[job_id] = updated
job_span.set_attribute("job.status", updated.status)
job_span.set_attribute("job.attempts", attempts)
processed.append(updated)
batch_span.set_attribute("drain.processed", len(processed))
batch_span.set_attribute("drain.completed", completed_cnt)
batch_span.set_attribute("drain.dlq", dlq_cnt)
return AsyncJobDrainResponse(
drained_count=len(processed),
completed_count=completed_cnt,
dead_lettered_count=dlq_cnt,
remaining_queue_depth=len(bundle.pending_queue),
dlq_depth=len(bundle.dead_letter_queue),
processed_jobs=processed,
)
@app.get("/v1/jobs/{job_id}", response_model=AsyncJobRecord)
def get_job(job_id: str) -> AsyncJobRecord:
rec = bundle.jobs_by_id.get(job_id)
if rec is None:
raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found")
return rec
return app
def main() -> None:
"""CLI entrypoint reporting readiness of Lab 13 Async Job Platform."""
state = AsyncPlatformState()
print(
f"Lab 13 K8s Async Job Platform Ready | qos={state.qos_class} | "
f"vault_lease={state.vault_active_lease_id}"
)
if __name__ == "__main__":
main()
"""Deterministic CLI runner generating artifacts/t2_ch15_lab13_results.json."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Any
from fastapi.testclient import TestClient
from k8s_ai_platform_lab.manifest_and_vault_audit import run_tier1_manifest_audit
from k8s_ai_platform_lab.scheduler_keda_and_async_app import (
AsyncPlatformState,
ClusterNode,
PodScheduleRequest,
create_async_platform_app,
evaluate_gpu_scheduling_strategies,
evaluate_rollout_safety_and_vault_leases,
run_keda_vs_hpa_autoscaling_benchmark,
schedule_pods_two_phase,
simulate_qos_and_oomkill_eviction,
summarize_finished_spans,
)
def run_full_benchmark_suite(seed: int = 42) -> dict[str, Any]:
"""Execute the end-to-end Lab 13 benchmark suite and return structured results."""
state = AsyncPlatformState()
tracer = state.tracer
exporter = state.exporter
with tracer.start_as_current_span("lab13.benchmark.suite") as root_span:
root_span.set_attribute("lab.seed", seed)
with tracer.start_as_current_span("lab13.tier1_manifest_and_vault_audit") as sp:
manifest_audit = run_tier1_manifest_audit()
sp.set_attribute("audit.all_passed", manifest_audit["all_passed"])
sp.set_attribute(
"audit.secret_files_scanned",
manifest_audit["secret_hygiene"]["scanned_files_count"],
)
with tracer.start_as_current_span("lab13.scheduler_and_qos_oom") as sp:
nodes = [
ClusterNode(
node_id="worker-zone-a",
zone="zone-a",
allocatable_cpu_m=8000,
allocatable_mem_mib=32768,
total_gpus=2,
taints=["gpu=nvidia:NoSchedule"],
cached_images=["ghcr.io/fsds-sota/ml-async-api:2026.1.0"],
),
ClusterNode(
node_id="worker-zone-b",
zone="zone-b",
allocatable_cpu_m=8000,
allocatable_mem_mib=32768,
total_gpus=2,
taints=["gpu=nvidia:NoSchedule"],
cached_images=[],
),
ClusterNode(
node_id="worker-zone-c",
zone="zone-c",
allocatable_cpu_m=8000,
allocatable_mem_mib=32768,
total_gpus=0,
taints=[],
cached_images=["ghcr.io/fsds-sota/ml-async-api:2026.1.0"],
),
]
pods = [
PodScheduleRequest(
pod_name="ml-async-api-0",
cpu_request_m=1000,
cpu_limit_m=1000,
mem_request_mib=1024,
mem_limit_mib=1024,
tolerations=["gpu=nvidia:NoSchedule"],
),
PodScheduleRequest(
pod_name="ml-async-api-1",
cpu_request_m=1000,
cpu_limit_m=1000,
mem_request_mib=1024,
mem_limit_mib=1024,
tolerations=["gpu=nvidia:NoSchedule"],
),
PodScheduleRequest(
pod_name="ml-async-api-2",
cpu_request_m=1000,
cpu_limit_m=1000,
mem_request_mib=1024,
mem_limit_mib=1024,
tolerations=["gpu=nvidia:NoSchedule"],
),
PodScheduleRequest(
pod_name="ml-async-worker-gpu-0",
cpu_request_m=2000,
cpu_limit_m=2000,
mem_request_mib=8192,
mem_limit_mib=8192,
gpu_request=1,
tolerations=["gpu=nvidia:NoSchedule"],
),
]
scheduler_res = schedule_pods_two_phase(nodes, pods)
qos_oom = simulate_qos_and_oomkill_eviction(node_mem_mib=32_768)
sp.set_attribute("qos.guaranteed_survival_pct", qos_oom["guaranteed_survival_pct"])
sp.set_attribute("qos.best_effort_evicted_pct", qos_oom["best_effort_evicted_pct"])
with tracer.start_as_current_span("lab13.gpu_mig_vs_dra_vs_timeslice") as sp:
gpu_eval = evaluate_gpu_scheduling_strategies(
n_gpus=4,
gpu_vram_gb=80,
n_workloads=12,
workload_vram_gb=16.0,
spike_vram_gb=52.0,
)
sp.set_attribute("gpu.mig_density_gain_x", gpu_eval["mig_density_gain_x"])
sp.set_attribute("gpu.dra_peak_capacity_gain_x", gpu_eval["dra_peak_capacity_gain_x"])
with tracer.start_as_current_span("lab13.keda_vs_cpu_hpa") as sp:
autoscaling_eval = run_keda_vs_hpa_autoscaling_benchmark(burst_multiplier=8)
sp.set_attribute(
"autoscaling.hpa_p95_wait_sec",
autoscaling_eval["cpu_hpa"]["p95_queue_wait_sec"],
)
sp.set_attribute(
"autoscaling.keda_p95_wait_sec",
autoscaling_eval["keda_queue"]["p95_queue_wait_sec"],
)
sp.set_attribute(
"autoscaling.wait_reduction_x",
autoscaling_eval["p95_wait_reduction_x"],
)
with tracer.start_as_current_span("lab13.canary_and_vault_leases") as sp:
rollout_vault = evaluate_rollout_safety_and_vault_leases()
sp.set_attribute(
"vault.leases_issued",
rollout_vault["vault_lease_rotation"]["leases_issued"],
)
sp.set_attribute(
"vault.auth_failures",
rollout_vault["vault_lease_rotation"]["auth_failures"],
)
# FastAPI TestClient smoke verification
client = TestClient(create_async_platform_app(state=state))
r_health = client.get("/health").json()
r_job1 = client.post(
"/v1/jobs",
json={
"task_type": "ocr_extract",
"priority": 9,
"idempotency_key": "idem-receipt-1001",
"payload": {"doc_id": "INV-1001"},
},
).json()
r_job1_dup = client.post(
"/v1/jobs",
json={
"task_type": "ocr_extract",
"priority": 9,
"idempotency_key": "idem-receipt-1001",
"payload": {"doc_id": "INV-1001"},
},
).json()
client.post(
"/v1/jobs",
json={
"task_type": "embed_batch",
"priority": 5,
"idempotency_key": "idem-retry-1002",
"payload": {"batch": 16},
"simulate_transient_failures": 1,
},
)
client.post(
"/v1/jobs",
json={
"task_type": "llm_rerank",
"priority": 3,
"idempotency_key": "idem-poison-1003",
"payload": {"corrupt": True},
"poison_payload": True,
},
)
r_drain = client.post("/v1/jobs/drain", json={"max_jobs": 10, "max_retries": 2}).json()
r_get1 = client.get(f"/v1/jobs/{r_job1['job_id']}").json()
otel_summary = summarize_finished_spans(exporter)
whole_p, ts_p, mig_p, dra_p = gpu_eval["profiles"]
hpa_res = autoscaling_eval["cpu_hpa"]
keda_res = autoscaling_eval["keda_queue"]
rolling_cmp, bg_cmp, canary_bad, _canary_ok = rollout_vault["rollout_comparisons"]
vault_res = rollout_vault["vault_lease_rotation"]
qos_surv_val = (
f"{qos_oom['guaranteed_survival_pct']}% vs "
f"{100.0 - qos_oom['best_effort_evicted_pct']}%"
)
gpu_gain_val = (
f"{mig_p['packing_density_vs_whole_x']}x MIG / "
f"{dra_p['packing_density_vs_whole_x']}x DRA"
)
burstable_alive = qos_oom["by_qos"]["Burstable"]["alive"]
burstable_total = qos_oom["by_qos"]["Burstable"]["total"]
burstable_pct = round((burstable_alive / burstable_total) * 100.0, 2)
wait_red_x = autoscaling_eval["p95_wait_reduction_x"]
workbench_panels = {
"kpis": [
{
"id": "kpi_tier1_helm_vault_audit",
"label": "Helmfile, Vault ESO & PSS Restricted Audit",
"value": "PASS (0 Secrets)",
"unit": f"({manifest_audit['secret_hygiene']['scanned_files_count']} YAMLs)",
"status": "ok",
"detail": (
"Verifies acyclic Helmfile DAG, Vault KV v2 Kubernetes auth, "
"Guaranteed QoS, non-root PSS Restricted, NetworkPolicy & PDB."
),
},
{
"id": "kpi_qos_oom_survival",
"label": "QoS Guaranteed Survival Under Node OOM",
"value": qos_surv_val,
"unit": "(Guaranteed vs BestEffort)",
"status": "ok",
"detail": (
"Under 39.1 GiB pressure on 32 GiB node, all BestEffort/Burstable excess "
"pods are evicted while Guaranteed API pods (-997) stay 100% online."
),
},
{
"id": "kpi_gpu_mig_dra_packing",
"label": "NVIDIA MIG & K8s DRA GPU Packing Gain",
"value": gpu_gain_val,
"unit": f"({ts_p['spillover_neighbor_kills']} vs 0 neighbor kills)",
"status": "ok",
"detail": (
"Packs 12-20 isolated 16 GB AI workloads on 4x80 GB GPUs vs 4 on Whole GPU, "
"eliminating Time-Slicing CUDA OOM spillover kills."
),
},
{
"id": "kpi_keda_vs_hpa_p95",
"label": "KEDA Queue-Depth vs CPU HPA p95 Wait",
"value": f"{keda_res['p95_queue_wait_sec']}s vs {hpa_res['p95_queue_wait_sec']}s",
"unit": f"({wait_red_x}x faster SLA)",
"status": "ok",
"detail": (
f"Under 8x bursty GPU/I/O traffic, KEDA cuts p95 queue wait "
f"{wait_red_x}x and reaches {keda_res['sla_compliance_pct']}% SLA compliance."
),
},
{
"id": "kpi_canary_and_vault_leases",
"label": "Canary SLO Gate & Vault Dynamic Leases",
"value": f"{canary_bad['blast_radius_pct']}% vs {rolling_cmp['blast_radius_pct']}%",
"unit": f"({vault_res['leases_issued']} leases, {vault_res['auth_failures']} err)",
"status": "ok",
"detail": (
"Canary catches 8.5% error spike at 10% weight and rolls back vs 100% "
"RollingUpdate blast; ESO rotates dynamic Vault leases with 0 restarts."
),
},
{
"id": "kpi_fastapi_async_otel",
"label": "FastAPI Async Queue, Idempotency & OTel",
"value": f"{otel_summary['span_count']} OTel Spans",
"unit": f"({r_drain['completed_count']} OK / {r_drain['dlq_depth']} DLQ)",
"status": "ok",
"detail": (
"POST /v1/jobs (202 Accepted + idempotency dedup), retry + DLQ drain, "
"and BoundedInMemorySpanExporter telemetry verified offline."
),
},
],
"bars": [
{
"id": "bar_keda_vs_hpa_p95_wait",
"title": "8x Bursty Async AI Queue p95 Wait Time (sec): CPU-Only HPA vs KEDA",
"metric_label": "p95 Queue Wait (sec)",
"items": [
{
"label": "cpu_only_hpa_lagging",
"value": hpa_res["p95_queue_wait_sec"],
"display": (
f"{hpa_res['p95_queue_wait_sec']}s (peak {hpa_res['peak_backlog']} "
f"queued, {hpa_res['sla_compliance_pct']}% SLA)"
),
"css_class": "is-slow",
},
{
"label": "keda_queue_depth_scaledobject",
"value": keda_res["p95_queue_wait_sec"],
"display": (
f"{keda_res['p95_queue_wait_sec']}s ({wait_red_x}x faster, "
f"{keda_res['sla_compliance_pct']}% SLA)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_gpu_packing_capacity",
"title": "4x 80 GB Cluster GPU Workload Capacity: Whole vs Time-Slice vs MIG vs DRA",
"metric_label": "Max Isolated Workloads (16 GB)",
"items": [
{
"label": "whole_gpu_1_per_card",
"value": whole_p["max_workload_capacity"],
"display": (
f"{whole_p['max_workload_capacity']} workloads "
f"({whole_p['vram_utilization_pct']}% VRAM, isolated)"
),
"css_class": "is-slow",
},
{
"label": "time_slicing_unisolated",
"value": ts_p["max_workload_capacity"],
"display": (
f"{ts_p['max_workload_capacity']} slots "
f"({ts_p['spillover_neighbor_kills']} neighbor OOM kills!)"
),
"css_class": "is-mid",
},
{
"label": "nvidia_mig_2g_20gb",
"value": mig_p["max_workload_capacity"],
"display": (
f"{mig_p['max_workload_capacity']} slices "
f"({mig_p['packing_density_vs_whole_x']}x, 0 spillover kills)"
),
"css_class": "is-fast",
},
{
"label": "k8s_dra_resource_claim",
"value": dra_p["max_workload_capacity"],
"display": (
f"{dra_p['max_workload_capacity']} claims "
f"({dra_p['packing_density_vs_whole_x']}x, "
f"{dra_p['peak_packable_vram_util_pct']}% VRAM, 0 kills)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_qos_oom_survival_pct",
"title": "Node Memory Pressure (39.1 / 32 GiB) Pod Survival Rate (%) by QoS Class",
"metric_label": "Survival Rate (%)",
"items": [
{
"label": "best_effort_oom_1000",
"value": round(100.0 - qos_oom["best_effort_evicted_pct"], 2),
"display": (
f"{round(100.0 - qos_oom['best_effort_evicted_pct'], 1)}% "
"alive (evicted first)"
),
"css_class": "is-slow",
},
{
"label": "burstable_over_request",
"value": burstable_pct,
"display": f"{burstable_alive}/{burstable_total} alive (evicted second)",
"css_class": "is-mid",
},
{
"label": "guaranteed_api_oom_minus_997",
"value": qos_oom["guaranteed_survival_pct"],
"display": f"{qos_oom['guaranteed_survival_pct']}% alive (protected -997)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_rollout_blast_radius",
"title": "Faulty Release (8.5% Error Rate, /health 200 OK) Production Blast Radius (%)",
"metric_label": "Bad Traffic Exposed (%)",
"items": [
{
"label": "rolling_update_health_only",
"value": rolling_cmp["blast_radius_pct"],
"display": (
f"{rolling_cmp['blast_radius_pct']}% exposed "
f"({rolling_cmp['decision']})"
),
"css_class": "is-slow",
},
{
"label": "canary_slo_gated_10pct",
"value": canary_bad["blast_radius_pct"],
"display": (
f"{canary_bad['blast_radius_pct']}% exposed ({canary_bad['decision']})"
),
"css_class": "is-mid",
},
{
"label": "blue_green_smoke_gated",
"value": bg_cmp["blast_radius_pct"],
"display": (
f"{bg_cmp['blast_radius_pct']}% exposed ({bg_cmp['decision']})"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_tier1_manifest_audit",
"title": "Tier-1 Helmfile, Vault ESO, QoS, NetworkPolicy & GPU Manifest Audit",
"columns": ["audit_target", "checks_verified", "gpu_or_auth_mode", "status"],
"rows": [
[
"helmfile.yaml.gotmpl (4 releases, 2 envs)",
" -> ".join(manifest_audit["helmfile"]["topological_order"]),
", ".join(manifest_audit["helmfile"]["environments"]),
"PASS" if manifest_audit["helmfile"]["passed"] else "FAIL",
],
[
"Secret Hygiene Scan (YAML + Templates)",
f"{manifest_audit['secret_hygiene']['scanned_files_count']} files scanned",
"Vault KV v2 + K8s SA JWT (0 inline)",
"PASS" if manifest_audit["secret_hygiene"]["passed"] else "FAIL",
],
[
"Helm Chart Render (prod MIG profile)",
f"{manifest_audit['prod_mig_render']['rendered_resource_count']} K8s objects",
"Guaranteed QoS + nvidia.com/mig-2g.20gb",
"PASS" if manifest_audit["prod_mig_render"]["passed"] else "FAIL",
],
[
"Helm Chart Render (dev DRA profile)",
f"{manifest_audit['dev_dra_render']['rendered_resource_count']} K8s objects",
"K8s 1.34+ DRA ResourceClaimTemplate",
"PASS" if manifest_audit["dev_dra_render"]["passed"] else "FAIL",
],
],
},
{
"id": "table_gpu_scheduling_comparison",
"title": "4x 80 GB GPU Scheduling Comparison: Whole vs Time-Slicing vs MIG vs DRA",
"columns": ["strategy", "admitted_cap", "vram_isolation", "spillover_risk"],
"rows": [
[
p["label"],
f"{p['admitted_workloads']}/12 (cap {p['max_workload_capacity']})",
f"{p['vram_utilization_pct']}% VRAM | HW={p['hardware_vram_isolation']}",
f"{p['spillover_neighbor_kills']} kills ({p['packing_density_vs_whole_x']}x)",
]
for p in gpu_eval["profiles"]
],
},
{
"id": "table_keda_vs_hpa_burst",
"title": "8x Bursty Async AI Traffic Benchmark: CPU-Only HPA vs KEDA Queue-Depth",
"columns": ["autoscaler", "peak_queue_pods", "p95_max_wait", "sla_compliance"],
"rows": [
[
"CPU-Only HPA (70% CPU Target)",
f"Peak {hpa_res['peak_backlog']} jobs | max {hpa_res['peak_replicas']} pods",
f"p95 {hpa_res['p95_queue_wait_sec']}s (max {hpa_res['max_queue_wait_sec']}s)",
f"{hpa_res['sla_compliance_pct']}% (<=30s SLA)",
],
[
"KEDA ScaledObject (Queue Lag=4/pod)",
f"Peak {keda_res['peak_backlog']} jobs | max {keda_res['peak_replicas']} pods",
f"p95 {keda_res['p95_queue_wait_sec']}s (max {keda_res['max_queue_wait_sec']}s)",
f"{keda_res['sla_compliance_pct']}% ({wait_red_x}x faster)",
],
],
},
{
"id": "table_rollout_and_vault_leases",
"title": "Canary / Blue-Green Rollout Gate & HashiCorp Vault Lease Rotation (900s)",
"columns": ["mechanism", "candidate_or_ttl", "exposure_or_leases", "verdict"],
"rows": [
*[
[
r["strategy"],
r["candidate"],
f"Final {r['final_traffic_pct']}% | Blast {r['blast_radius_pct']}%",
r["decision"],
]
for r in rollout_vault["rollout_comparisons"]
],
[
"HashiCorp Vault + ESO Dynamic Lease",
f"TTL {vault_res['lease_ttl_sec']}s / {vault_res['refresh_interval_sec']}s",
f"{vault_res['leases_issued']} leases ({vault_res['active_lease_id']})",
f"{vault_res['auth_failures']} err | {vault_res['pod_restarts_required']} rst",
],
],
},
],
}
return {
"unit_id": "T2-P3-U03",
"lab_id": "lab-13-k8s-helm-vault-async-job-platform",
"seed": seed,
"manifest_audit": manifest_audit,
"scheduler_placement": scheduler_res,
"qos_oom_eval": qos_oom,
"gpu_scheduling_eval": gpu_eval,
"keda_vs_hpa_eval": autoscaling_eval,
"canary_and_vault_eval": rollout_vault,
"fastapi_async_smoke": {
"health": r_health,
"first_job": r_job1,
"dedup_job": r_job1_dup,
"drain_summary": r_drain,
"polled_job_1": r_get1,
},
"otel_telemetry": otel_summary,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 13 K8s Cloud-Native AI Platform Benchmark")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path(__file__).resolve().parents[1] / "artifacts" / "t2_ch15_lab13_results.json",
)
args = parser.parse_args()
results = run_full_benchmark_suite(seed=args.seed)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")
print(f"Wrote Lab 13 benchmark results to {args.output}")
if __name__ == "__main__":
main()
"""Automated verification suite (21 tests, 0 skips) for Lab 13 K8s Async Job Platform."""
from __future__ import annotations
import ast
import io
import re
import tokenize
from pathlib import Path
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 k8s_ai_platform_lab.manifest_and_vault_audit import (
audit_helmfile,
audit_rendered_manifests,
load_and_render_helm_chart,
run_tier1_manifest_audit,
scan_directory_secret_hygiene,
)
from k8s_ai_platform_lab.scheduler_keda_and_async_app import (
AsyncPlatformState,
ClusterNode,
PodScheduleRequest,
classify_pod_qos,
create_async_platform_app,
evaluate_gpu_scheduling_strategies,
evaluate_rollout_safety_and_vault_leases,
run_keda_vs_hpa_autoscaling_benchmark,
schedule_pods_two_phase,
simulate_qos_and_oomkill_eviction,
summarize_finished_spans,
)
from scripts.run_lab_demo import run_full_benchmark_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
CHART_DIR = LAB_ROOT / "charts" / "ml-async-platform"
def test_01_ast_safety_no_pickle_eval_exec_or_type_ignore() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec"}
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 4
forbidden_comment = "type:" + " ignore"
for py_file in py_files:
source = py_file.read_text(encoding="utf-8")
with io.StringIO(source) as buf:
for tok in tokenize.generate_tokens(buf.readline):
if tok.type == tokenize.COMMENT and forbidden_comment in tok.string:
raise AssertionError(f"Forbidden type-ignore comment found in {py_file}")
tree = ast.parse(source, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in forbidden_modules
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".")[0]
assert root_mod not in forbidden_modules
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
for ext in ("*.png", "*.parquet", "*.duckdb*"):
assert not list(LAB_ROOT.rglob(ext))
def test_02_helmfile_release_dag_and_environments() -> None:
assert (LAB_ROOT / "helmfile.yaml.gotmpl").is_file()
assert not (LAB_ROOT / "helmfile.yaml").exists()
res = audit_helmfile(LAB_ROOT / "helmfile.yaml.gotmpl")
assert res["passed"] is True
assert set(res["environments"]) == {"dev", "prod"}
topo = res["topological_order"]
assert topo.index("security-system/vault-eso") < topo.index("kserve-system/kserve")
assert topo.index("keda-system/keda") < len(topo) - 1
assert topo[-1].endswith("/ml-async-platform")
def test_03_vault_eso_zero_hardcoded_secrets_audit() -> None:
hygiene = scan_directory_secret_hygiene(LAB_ROOT)
assert hygiene["passed"] is True
assert hygiene["scanned_files_count"] >= 11
assert hygiene["findings"] == []
docs = load_and_render_helm_chart(CHART_DIR)
ss = next(d for d in docs if d["kind"] == "SecretStore")
es = next(d for d in docs if d["kind"] == "ExternalSecret")
assert ss["spec"]["provider"]["vault"]["version"] == "v2"
assert ss["spec"]["provider"]["vault"]["auth"]["kubernetes"]["serviceAccountRef"]["name"]
assert es["spec"]["target"]["name"] == "ml-async-vault-runtime-secret"
def test_04_api_deployment_guaranteed_qos_and_pss_restricted() -> None:
docs = load_and_render_helm_chart(CHART_DIR)
api_dep = next(
d for d in docs if d["kind"] == "Deployment" and d["metadata"]["name"] == "ml-async-api"
)
pod_spec = api_dep["spec"]["template"]["spec"]
c = pod_spec["containers"][0]
assert c["resources"]["requests"] == c["resources"]["limits"]
assert pod_spec["securityContext"]["runAsNonRoot"] is True
assert pod_spec["securityContext"]["seccompProfile"]["type"] == "RuntimeDefault"
assert c["securityContext"]["allowPrivilegeEscalation"] is False
assert c["securityContext"]["readOnlyRootFilesystem"] is True
assert "ALL" in c["securityContext"]["capabilities"]["drop"]
assert {"startupProbe", "readinessProbe", "livenessProbe"} <= set(c.keys())
assert len(pod_spec["topologySpreadConstraints"]) >= 1
def test_05_worker_deployment_init_mig_dra_and_graceful_drain() -> None:
mig_docs = load_and_render_helm_chart(CHART_DIR, overrides={"worker": {"gpuMode": "mig"}})
mig_wrk = next(
d for d in mig_docs if d["kind"] == "Deployment" and d["metadata"]["name"] == "ml-async-worker"
)
mig_spec = mig_wrk["spec"]["template"]["spec"]
assert mig_spec["initContainers"][0]["name"] == "model-weights-precheck"
assert mig_spec["terminationGracePeriodSeconds"] >= 60
assert "nvidia.com/mig-2g.20gb" in mig_spec["containers"][0]["resources"]["limits"]
dra_docs = load_and_render_helm_chart(CHART_DIR, overrides={"worker": {"gpuMode": "dra"}})
dra_rct = next(d for d in dra_docs if d["kind"] == "ResourceClaimTemplate")
dra_wrk = next(
d for d in dra_docs if d["kind"] == "Deployment" and d["metadata"]["name"] == "ml-async-worker"
)
assert dra_rct["apiVersion"] == "resource.k8s.io/v1"
assert dra_wrk["spec"]["template"]["spec"]["resourceClaims"][0]["name"] == "gpu-dra-claim"
def test_06_keda_kserve_networkpolicy_and_pdb_manifests() -> None:
audit = run_tier1_manifest_audit(LAB_ROOT)
assert audit["all_passed"] is True
assert audit["prod_mig_render"]["passed"] is True
assert audit["dev_dra_render"]["passed"] is True
docs = load_and_render_helm_chart(CHART_DIR)
keda = next(d for d in docs if d["kind"] == "ScaledObject")
trig_auth = next(d for d in docs if d["kind"] == "TriggerAuthentication")
sa = next(d for d in docs if d["kind"] == "ServiceAccount")
isvc = next(d for d in docs if d["kind"] == "InferenceService")
netpols = [d for d in docs if d["kind"] == "NetworkPolicy"]
pdbs = [d for d in docs if d["kind"] == "PodDisruptionBudget"]
assert keda["spec"]["triggers"][0]["type"] == "redis"
assert keda["spec"]["triggers"][0]["authenticationRef"]["name"] == "ml-async-keda-vault-auth"
assert trig_auth["metadata"]["name"] == "ml-async-keda-vault-auth"
assert sa["automountServiceAccountToken"] is False
assert isvc["spec"]["predictor"]["canaryTrafficPercent"] == 10
assert isvc["spec"]["predictor"]["automountServiceAccountToken"] is False
assert "nvidia.com/gpu" in isvc["spec"]["predictor"]["model"]["resources"]["requests"]
assert isvc["spec"]["predictor"]["model"]["securityContext"]["runAsNonRoot"] is True
assert len(netpols) == 4
assert any(np["metadata"]["name"] == "doc-ocr-reranker-least-privilege" for np in netpols)
assert len(pdbs) == 2
def test_07_kube_scheduler_filter_score_topology_placement() -> None:
nodes = [
ClusterNode(
node_id="n1",
zone="zone-a",
allocatable_cpu_m=4000,
allocatable_mem_mib=16384,
total_gpus=1,
taints=["gpu=nvidia:NoSchedule"],
cached_images=["api:v1"],
),
ClusterNode(
node_id="n2",
zone="zone-b",
allocatable_cpu_m=4000,
allocatable_mem_mib=16384,
total_gpus=0,
taints=[],
cached_images=["api:v1"],
),
]
pods = [
PodScheduleRequest(
pod_name="api-0",
cpu_request_m=1000,
cpu_limit_m=1000,
mem_request_mib=1024,
mem_limit_mib=1024,
image="api:v1",
),
PodScheduleRequest(
pod_name="gpu-blocked-no-toleration",
cpu_request_m=1000,
cpu_limit_m=1000,
mem_request_mib=1024,
mem_limit_mib=1024,
gpu_request=1,
image="api:v1",
),
]
out = schedule_pods_two_phase(nodes, pods)
assert out["placements"][0]["status"] == "Scheduled"
assert out["placements"][0]["node_id"] == "n2"
assert out["placements"][1]["status"] == "Pending"
def test_08_qos_classification_and_oomkill_eviction_order() -> None:
res = simulate_qos_and_oomkill_eviction(node_mem_mib=32_768)
assert res["guaranteed_survival_pct"] == 100.0
assert res["best_effort_evicted_pct"] == 100.0
assert res["final_used_mib"] <= int(32_768 * 0.85)
# First 3 evictions must all be BestEffort pods
best_effort_names = {"debug-shell-0", "adhoc-nb-1", "adhoc-nb-2"}
assert set(res["eviction_order"][:3]) == best_effort_names
@given(
cpu_m=st.integers(min_value=100, max_value=8000),
mem_mib=st.integers(min_value=128, max_value=16384),
extra_mem=st.integers(min_value=1, max_value=8192),
)
@settings(max_examples=40, deadline=None)
def test_09_hypothesis_qos_and_oom_score_invariants(
cpu_m: int, mem_mib: int, extra_mem: int
) -> None:
g = classify_pod_qos(cpu_m, cpu_m, mem_mib, mem_mib, node_mem_mib=32_768)
b = classify_pod_qos(cpu_m, cpu_m * 2, mem_mib, mem_mib + extra_mem, node_mem_mib=32_768)
be = classify_pod_qos(0, 0, 0, 0, node_mem_mib=32_768)
assert g["qos_class"] == "Guaranteed" and g["oom_score_adj"] == -997
assert b["qos_class"] == "Burstable" and 2 <= b["oom_score_adj"] <= 999
assert be["qos_class"] == "BestEffort" and be["oom_score_adj"] == 1000
assert g["oom_score_adj"] < b["oom_score_adj"] < be["oom_score_adj"]
def test_10_gpu_sharing_whole_vs_timeslice_vs_mig_vs_dra() -> None:
res = evaluate_gpu_scheduling_strategies(
n_gpus=4, gpu_vram_gb=80, n_workloads=12, workload_vram_gb=16.0, spike_vram_gb=52.0
)
whole, ts, mig, dra = res["profiles"]
assert whole["admitted_workloads"] == 4
assert ts["admitted_workloads"] == 12
assert ts["spillover_neighbor_kills"] >= 2
assert mig["admitted_workloads"] == 12
assert mig["spillover_neighbor_kills"] == 0
assert mig["packing_density_vs_whole_x"] == 3.0
assert dra["max_workload_capacity"] == 20
assert dra["packing_density_vs_whole_x"] == 5.0
assert dra["spillover_neighbor_kills"] == 0
@given(
n_gpus=st.integers(min_value=1, max_value=8),
vram_gb=st.sampled_from([40, 80]),
req_gb=st.sampled_from([8.0, 10.0, 16.0, 20.0]),
)
@settings(max_examples=30, deadline=None)
def test_11_hypothesis_gpu_packing_capacity_invariants(
n_gpus: int, vram_gb: int, req_gb: float
) -> None:
out = evaluate_gpu_scheduling_strategies(
n_gpus=n_gpus, gpu_vram_gb=vram_gb, n_workloads=n_gpus * 5, workload_vram_gb=req_gb
)
whole, _ts, mig, dra = out["profiles"]
assert whole["max_workload_capacity"] == n_gpus
assert dra["max_workload_capacity"] >= mig["max_workload_capacity"] >= whole["max_workload_capacity"]
assert mig["spillover_neighbor_kills"] == 0
assert dra["spillover_neighbor_kills"] == 0
def test_12_keda_queue_depth_vs_cpu_hpa_burst_sla() -> None:
bench = run_keda_vs_hpa_autoscaling_benchmark(burst_multiplier=8)
hpa = bench["cpu_hpa"]
keda = bench["keda_queue"]
assert hpa["p95_queue_wait_sec"] >= 100.0
assert keda["p95_queue_wait_sec"] <= 30.0
assert bench["p95_wait_reduction_x"] >= 5.0
assert keda["sla_compliance_pct"] > hpa["sla_compliance_pct"]
assert keda["sla_compliance_pct"] >= 95.0
def test_13_canary_slo_gate_rollback_vs_blind_rolling() -> None:
res = evaluate_rollout_safety_and_vault_leases()
rolling, _bg, canary_bad, canary_ok = res["rollout_comparisons"]
assert rolling["blast_radius_pct"] == 100.0
assert canary_bad["blast_radius_pct"] == 10.0
assert canary_bad["final_traffic_pct"] == 0
assert canary_ok["final_traffic_pct"] == 100
def test_14_blue_green_zero_blast_radius_and_vault_lease_rotation() -> None:
res = evaluate_rollout_safety_and_vault_leases()
_rolling, bg, _cb, _co = res["rollout_comparisons"]
assert bg["blast_radius_pct"] == 0.0
assert bg["decision"] == "ABORTED_AT_SMOKE_ZERO_BLAST"
vault = res["vault_lease_rotation"]
assert vault["leases_issued"] >= 4
assert vault["auth_failures"] == 0
assert vault["pod_restarts_required"] == 0
def test_15_fastapi_health_and_202_job_enqueue_idempotency() -> None:
client = TestClient(create_async_platform_app())
h = client.get("/health")
assert h.status_code == 200
assert h.json()["qos_class"] == "Guaranteed"
r1 = client.post(
"/v1/jobs",
json={
"task_type": "ocr_extract",
"priority": 8,
"idempotency_key": "req-abc-001",
"payload": {"page": 1},
},
)
assert r1.status_code == 202
assert r1.json()["deduplicated"] is False
r2 = client.post(
"/v1/jobs",
json={
"task_type": "ocr_extract",
"priority": 8,
"idempotency_key": "req-abc-001",
"payload": {"page": 1},
},
)
assert r2.status_code == 202
assert r2.json()["job_id"] == r1.json()["job_id"]
assert r2.json()["deduplicated"] is True
assert client.get("/health").json()["queue_depth"] == 1
def test_16_fastapi_strict_pydantic_422_and_404_validation() -> None:
client = TestClient(create_async_platform_app())
bad_extra = client.post(
"/v1/jobs",
json={
"task_type": "ocr_extract",
"idempotency_key": "req-bad-01",
"unexpected_admin_flag": True,
},
)
assert bad_extra.status_code == 422
bad_task = client.post(
"/v1/jobs",
json={"task_type": "shell_exec", "idempotency_key": "req-bad-02"},
)
assert bad_task.status_code == 422
missing = client.get("/v1/jobs/job-9999")
assert missing.status_code == 404
def test_17_fastapi_worker_drain_retry_and_dead_letter_queue() -> None:
client = TestClient(create_async_platform_app())
client.post(
"/v1/jobs",
json={
"task_type": "embed_batch",
"idempotency_key": "retry-ok-01",
"simulate_transient_failures": 2,
},
)
client.post(
"/v1/jobs",
json={
"task_type": "llm_rerank",
"idempotency_key": "poison-dlq-01",
"poison_payload": True,
},
)
drain = client.post("/v1/jobs/drain", json={"max_jobs": 10, "max_retries": 2})
assert drain.status_code == 200
body = drain.json()
assert body["drained_count"] == 2
assert body["completed_count"] == 1
assert body["dead_lettered_count"] == 1
assert body["remaining_queue_depth"] == 0
assert body["dlq_depth"] == 1
assert body["processed_jobs"][0]["attempts"] == 3
assert body["processed_jobs"][1]["status"] == "DEAD_LETTERED"
def test_18_bounded_otel_spans_zero_raw_secrets() -> None:
state = AsyncPlatformState()
client = TestClient(create_async_platform_app(state=state))
client.post(
"/v1/jobs",
json={"task_type": "ocr_extract", "idempotency_key": "otel-check-01"},
)
client.post("/v1/jobs/drain", json={"max_jobs": 5, "max_retries": 1})
summary = summarize_finished_spans(state.exporter)
assert summary["span_count"] >= 3
assert "lab13.api.enqueue_job" in summary["span_names"]
assert "lab13.worker.drain_batch" in summary["span_names"]
raw_dump = str(summary)
assert "hvs." not in raw_dump
assert "password" not in raw_dump.lower()
def test_19_cli_demo_benchmark_schema_and_panels() -> None:
res = run_full_benchmark_suite(seed=42)
assert res["unit_id"] == "T2-P3-U03"
assert res["lab_id"] == "lab-13-k8s-helm-vault-async-job-platform"
panels = res["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_20_manifest_tamper_detection_fails_audit(tmp_path: Path) -> None:
docs = load_and_render_helm_chart(CHART_DIR)
# Tamper API Deployment to drop Guaranteed QoS and enable root
tampered_docs = []
for d in docs:
if d.get("kind") == "Deployment" and d["metadata"]["name"] == "ml-async-api":
bad = yaml.safe_load(yaml.safe_dump(d))
bad["spec"]["template"]["spec"]["containers"][0]["resources"]["requests"]["memory"] = "512Mi"
bad["spec"]["template"]["spec"]["containers"][0]["securityContext"]["runAsNonRoot"] = False
tampered_docs.append(bad)
else:
tampered_docs.append(d)
audit_res = audit_rendered_manifests(tampered_docs, expected_gpu_mode="mig")
assert audit_res["passed"] is False
assert any("Guaranteed QoS" in v for v in audit_res["violations"])
assert any("runAsNonRoot" in v for v in audit_res["violations"])
# Also prove secret hygiene scanner flags inline token
bad_yaml = tmp_path / "leak.yaml"
bad_yaml.write_text("vault_token: hvs.FakeSecretLeak123456789\n", encoding="utf-8")
sec_res = scan_directory_secret_hygiene(tmp_path)
assert sec_res["passed"] is False
# Confirm Pydantic extra=forbid rejects unknown fields on ClusterNode
with pytest.raises(ValidationError):
ClusterNode.model_validate(
{
"node_id": "x",
"zone": "z",
"allocatable_cpu_m": 1000,
"allocatable_mem_mib": 1024,
"total_gpus": 0,
"extra_field": True,
}
)
def test_21_c3_h6_network_policy_trigger_auth_and_helmfile_invariants(tmp_path: Path) -> None:
docs = load_and_render_helm_chart(CHART_DIR)
# 1. Tampering away TriggerAuthentication must fail manifest audit (C3)
without_ta = [d for d in docs if d.get("kind") != "TriggerAuthentication"]
res_ta = audit_rendered_manifests(without_ta, expected_gpu_mode="mig")
assert res_ta["passed"] is False
assert any("TriggerAuthentication" in v for v in res_ta["violations"])
# 2. Tampering away worker 443 egress or KServe NetworkPolicy must fail (C3)
without_kserve_np = [
d
for d in docs
if not (
d.get("kind") == "NetworkPolicy"
and d["metadata"]["name"] == "doc-ocr-reranker-least-privilege"
)
]
res_np = audit_rendered_manifests(without_kserve_np, expected_gpu_mode="mig")
assert res_np["passed"] is False
assert any("NetworkPolicy" in v for v in res_np["violations"])
# 3. Verify Helmfile environments match dev=dra / prod=mig & PDB headroom > 0 (H6)
hf_raw = (LAB_ROOT / "helmfile.yaml.gotmpl").read_text(encoding="utf-8")
hf = yaml.safe_load(
re.sub(
r'(?<!")(\{\{[-]?.*?[-]?\}\})(?!")',
r'"\1"',
hf_raw,
)
)
assert hf["environments"]["dev"]["values"][0]["gpuMode"] == "dra"
assert hf["environments"]["prod"]["values"][0]["gpuMode"] == "mig"
assert hf["environments"]["dev"]["values"][0]["apiReplicas"] > 2
assert hf["environments"]["dev"]["values"][0]["workerMinReplicas"] > 1
# 4. Tampering Helmfile to quote an integer field must be caught by audit_helmfile (H6)
bad_hf = tmp_path / "helmfile.yaml.gotmpl"
bad_hf.write_text(
hf_raw.replace(
"replicas: {{ .Values.apiReplicas }}",
'replicas: "{{ .Values.apiReplicas }}"',
),
encoding="utf-8",
)
bad_hf_res = audit_helmfile(bad_hf)
assert bad_hf_res["passed"] is False
assert any("unquoted integer" in v for v in bad_hf_res["violations"])
# 5. Placing raw Go templates inside plain helmfile.yaml (without .gotmpl) must fail
wrong_ext_hf = tmp_path / "helmfile.yaml"
wrong_ext_hf.write_text(hf_raw, encoding="utf-8")
wrong_ext_res = audit_helmfile(wrong_ext_hf)
assert wrong_ext_res["passed"] is False
assert any(".gotmpl" in v for v in wrong_ext_res["violations"])
Test 07) kết hợp Gateway API + Inference Extension (GAIE), vai trò của etcd MVCC Watch-List, hai pha Filter -> Score của kube-scheduler và định tuyến EPP là gì?Test 07 và §1.1: Mọi đối tượng đi qua kube-apiserver (AuthN/RBAC/Admission) vào etcd (Raft + SharedInformer MVCC List/Watch); kube-scheduler lọc cứng ở pha Filter (chặn Pod GPU thiếu toleration ở Pending) rồi xếp hạng ở Score; Gateway API (HTTPRoute) + GAIE (InferencePool, EPP tối ưu KV-cache prefix & queue lag) thay thế kubernetes/ingress-nginx (chấm dứt hỗ trợ 03/2026).
32,768 MiB (39,130 MiB yêu cầu thực tế) của Lab 13 (Tests 08–09), lớp QoS và điểm oom_score_adj quyết định thứ tự thu hồi Pod như thế nào?Tests 08–09: CPU nén được (vượt limits.cpu gây CFS throttling), còn Memory không nén được (vượt gây OOMKill). Khi Node thiếu RAM, kubelet giết BestEffort (oom_score_adj = 1000, 3/3 đầu tiên), kế đến Burstable vượt request (2..999, 75.0% sống), bảo toàn 100.0% (3/3) Pod API/KServe Guaranteed (-997).
4 × 80 GB (320.0 GB VRAM) phục vụ các tác vụ AI 16 GB trong Lab 13 (Tests 10–11), điều gì xảy ra khi so sánh Whole GPU, Time-Slicing, NVIDIA MIG (2g.20gb) và Kubernetes DRA v1 (cùng LWS đa nút)?Tests 10–11: Whole GPU lãng phí (4/12, 20.0% VRAM); Time-Slicing chia thời gian không cách ly VRAM nên sự cố 52 GB đánh sập 2 hàng xóm; MIG 2g.20gb cách ly phần cứng (12 slice = 3.0x, 0 kill); DRA v1 (GA 1.34, CEL + firstAvailable B200->H200->H100) cấp 20 ResourceClaim (5.0x, 100.0% VRAM, 0 kill), kết hợp LeaderWorkerSet (LWS) cho phục vụ đa nút/P-D.
600s (744 job đến với pha burst 8x từ 4 -> 32 job/tick) tại Lab 13 (Test 12), tại sao CPU-Only HPA lại sụp đổ ở 18.33% SLA và KEDA ScaledObject khắc phục ra sao?Test 12: Tác vụ GPU/I/O-bound không bão hòa CPU (61.8% < 70% target), khiến CPU-Only HPA kẹt ở 2 Pod, ùn 432 job và p95 = 525.25s (18.33% SLA <= 30s). KEDA ScaledObject (+ TriggerAuthentication) đọc trực tiếp độ sâu hàng đợi, co giãn lên 8 Pod giữ đỉnh tồn 32 job và giảm p95 xuống 10.0s (52.52x nhanh hơn, 100.0% SLA).
v2.1-bad-threshold vẫn qua lọt /health 200 OK nhưng phát sinh 8.5% lỗi thực tế và p95 = 148 ms (Test 13), ba chiến lược triển khai phản ứng thế nào?Tests 13–14: RollingUpdate chỉ kiểm tra probe sống nên đẩy bản lỗi v2.1 lên 100.0% lưu lượng. KServe Canary (canaryTrafficPercent) cắt và rollback ngay ở bước 10.0% khi vi phạm SLO (err <= 1%, p95 <= 80ms), còn Blue-Green chặn trước lúc đổi selector Service với 0.0% blast radius.
Lab 13 (Tests 02–04, 14, 20) kết hợp Helmfile, Vault + ESO, TriggerAuthentication, PSS Restricted, NetworkPolicy và PDB như thế nào?Tests 02–04, 14, 20: helmfile.yaml.gotmpl sắp DAG vault-eso & keda -> kserve -> ml-async-platform cho hai môi trường dev (gpuMode=dra) và prod (gpuMode=mig); ESO (SecretStore SA JWT + ExternalSecret) và keda-triggerauthentication.yaml xoay 4 lease trong 900s (0 restart, 12/12 YAML sạch); gắn kèm PSS Restricted, NetworkPolicy default-deny (KServe doc-ocr-reranker, S3 443, Prometheus 8080/9090) và PDB bảo đảm DisruptionsAllowed >= 1 (replicas > minAvailable).
Init Container, Native Sidecar (K8s 1.29+), Operator/CRD, và quy tắc RWO vs RWX PVC?Init Container chạy tuần tự và phải thoát mã 0 trước container chính (vd. kiểm tra checksum mô hình); Native Sidecar (khai báo trong initContainers với restartPolicy: Always) khởi động trước và tắt sau cùng; Operator đối chiếu CRD liên tục; đĩa RWO chỉ gắn 1 Node nên đòi hỏi chiến lược Recreate khi cập nhật (hoặc chuyển RWX).
FastAPI xử lý job bất đồng bộ của Lab 13 (Tests 15–18), các chốt bảo vệ nào ngăn chặn trùng lặp giao dịch, treo kết nối HTTP và rò rỉ dữ liệu nhạy cảm?Tests 15–18: POST /v1/jobs trả ngay 202 Accepted và chống đẩy trùng qua idempotency_key (deduplicated=True), từ chối payload sai/extra field bằng HTTP 422; /v1/jobs/drain thử lại lỗi tạm thời tối đa max_retries=2 và cô lập poison_payload sang DEAD_LETTERED (DLQ), phát hành 14 span OTel sạch bí mật.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Kiểm toán DAG Helmfile, Vault ESO, TriggerAuthentication, NetworkPolicy và PDB 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lần theo needs: giữa dev (dra) vs prod (mig) trong helmfile.yaml.gotmpl, SecretStore/ExternalSecret trong external-secret-vault.yaml, keda-triggerauthentication.yaml, networkpolicy.yaml (KServe/S3/Prometheus), pdb.yaml (replicas > minAvailable) và 5 cờ PSS Restricted.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_02 or test_03 or test_04 or test_06 or test_20 or test_21" -v và kiểm tra audit_rendered_manifests cùng scan_directory_secret_hygiene trong src/k8s_ai_platform_lab/manifest_and_vault_audit.py.
Tiêu chí Đáp án & Số đối chứng
Kiểm toán Tầng 1 quét sạch 12/12 tệp YAML/Template (0 bí mật tĩnh), xác nhận DAG keda & vault-eso -> kserve -> ml-async-platform và render thành công cả prod MIG (16 đối tượng) lẫn dev DRA (17 đối tượng có ResourceClaimTemplate), gồm TriggerAuthentication, NetworkPolicy và PDB an toàn (DisruptionsAllowed >= 1), đồng thời chặn giả mạo hạ quyền runAsNonRoot hay token hvs.*.
Bài tập 2 — Bộ lập lịch K8s 2 Pha và Thứ tự Thu hồi QoS OOMKill 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân biệt pha Filter (Fit, Taints) vs Score (ImageLocality, TopologySpread, LeastAllocated) cùng Gateway API + GAIE (EPP) thay ingress-nginx, và công thức oom_score_adj: Guaranteed = -997, Burstable = 2..999, BestEffort = 1000.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_07 or test_08 or test_09" -v và kiểm tra mục qos_oom_eval trong artifacts/t2_ch15_lab13_results.json.
Tiêu chí Đáp án & Số đối chứng
Pod GPU thiếu toleration bị Filter chặn ở Pending. Dưới áp lực 39,130 MiB / 32,768 MiB, kubelet tiêu diệt trước 100.0% (3/3) Pod BestEffort, kế đến 1/4 Pod Burstable vượt request (75.0% sống), còn 100.0% (3/3) Pod API/KServe Guaranteed sống sót trọn vẹn.
Bài tập 3 — Lập lịch GPU Whole vs Time-Slicing vs NVIDIA MIG vs Kubernetes DRA v1 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính toán số slot, % VRAM, và cơ chế cách ly bộ nhớ trên cụm 4 × 80 GB (320.0 GB VRAM) cho 12 tác vụ 16 GB kèm sự cố 52 GB, cộng cấu hình DRA v1 (CEL + firstAvailable) và LWS đa nút.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11" -v và xem bảng table_gpu_scheduling_comparison trong artifacts/t2_ch15_lab13_results.json.
Tiêu chí Đáp án & Số đối chứng
Whole GPU chỉ nhận 4/12 (20.0% VRAM); Time-Slicing nhận 12/12 nhưng mất cách ly VRAM nên gây chết chéo 2 workload hàng xóm; NVIDIA MIG 2g.20gb nhận 12/12 (3.0x mật độ, 0 kill); và K8s DRA v1 mở rộng công suất tối đa lên 20 claim (5.0x, 100.0% peak VRAM, 0 lỗi lan truyền).
Bài tập 4 — KEDA Queue-Depth vs CPU-Only HPA Dưới Tải Burst 8x 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích nghịch lý CPU thấp khi worker chờ GPU/I/O (đỉnh CPU 61.8% < 70% target) và cơ chế scale-up + TriggerAuthentication của KEDA ScaledObject.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_12" -v và đọc đối chiếu keda_vs_hpa_eval trong artifacts/t2_ch15_lab13_results.json.
Tiêu chí Đáp án & Số đối chứng
Trong 600s (744 job, burst 8x), CPU-Only HPA kẹt ở 2 Pod khiến tồn đỉnh vọt 432 job, p95 chờ 525.25s (18.33% SLA). KEDA ScaledObject mở worker lên 8 Pod, giữ đỉnh tồn 32 job và kéo p95 về 10.0s (nhanh hơn 52.52x, đạt 100.0% SLA).
Bài tập 5 — Cổng An toàn Canary Blue-Green và Xoay Lease Vault Không Gián đoạn 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đối chiếu điều kiện SLO (error_rate <= 1.0%, p95 <= 80.0 ms) trước ứng viên v2.1 (8.5% err, /health 200 OK) và logic gia hạn ESO (SecretStore + ExternalSecret) tại <= 30% TTL còn lại (90s / 300s).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_13 or test_14" -v và kiểm tra hàm evaluate_rollout_safety_and_vault_leases.
Tiêu chí Đáp án & Số đối chứng
RollingUpdate làm lộ 100.0% lưu lượng trước bản lỗi v2.1; KServe Canary tự động rollback ngay tại bước 10.0%; Blue-Green chặn từ smoke test (0.0% blast radius). Cùng lúc, Vault + ESO xoay vòng 4 lease động (vault-lease-004) trong 900s với 0 lỗi auth và 0 Pod restart.
Bài tập 6 — Dịch vụ FastAPI Async Job Queue Idempotency DLQ và Bounded OTel 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm chứng qua TestClient: POST /v1/jobs (202 + deduplicated), từ chối trường thừa HTTP 422, /v1/jobs/drain thử lại 2 lần vs DEAD_LETTERED vào DLQ, và kiểm tra BoundedInMemorySpanExporter.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ run_lab_demo.py, ruff check src tests scripts, mypy src tests, pytest -p no:cacheprovider -v, và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
TestClient xác nhận /health, 202 + chống trùng idempotency_key, 422/404 chuẩn Pydantic, drain hoàn tất job retry (3 attempts) & cô lập poison_payload sang DLQ, thu 14 span OTel sạch bí mật, 0 # type: ignore và 21/21 pytest pass (0 skip).