Chương 25 — Quan sát Toàn phần (OTel, Prometheus, ELK, Jaeger, Langfuse, Evidently), Giám sát Khi Nhãn Đến Trễ (#17) & SRE
Chuyên đề #17: Khử báo động giả KS mẫu lớn (PSI 0.612 / W1 0.876), bóc trần ảo ảnh +25.31 đpt do nhãn trễ bằng Kaplan-Meier IPCW (61.61%, err 1.15 pp) & Active Audit (MAE 3.87 pp), OTel GenAI v1.37+, 2-tầng loadbalancing -> tail_sampling, Prometheus 3.0 Native Histograms & SRE error budget 43.2 phút (11 OTel spans).
Unit ID:
T2-P5-U02
Track & Part: Track 2 (EDAI) — Part 5: MLOps, LLMOps, CI/CD & Full-Stack Observability (part-05-mlops-cicd-and-observability)
Cầu nối Từ Chương 24 (Part 5): Sau khi thiết lập quản lý phiên bản đồng bộGit/DVC/MLflowvà cổng triển khaiCanary/Rollbackở Chương 24 (ch-24-versioning-cicd-and-safe-model-rollout.md), Chương 25 trả lời câu hỏi sống còn hậu phát hành: làm thế nào quan sát toàn diện hệ thốngML&LLM/Agenttừ biên HTTP tới từng token và phát hiện mô hình suy giảm chất lượng trước khi nhãn thật về tới kho dữ liệu (1–90ngày sau)?
Truy xuất Giáo trình Gốc (R50,AIDE 1 & 3 SRE Delta, Chuyên đề#17): Block 12: Observable Systems (Three pillars of observability: logs, metrics, traces; Observable system architecture; Drift detection; LLM and Agent specific telemetry; Test Telemetry Output); SRE / Error budgets / SLI-SLA-SLO; Article#17: Monitoring Model Quality When Labels Arrive Late 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 20): labs/lab-20-otel-prom-elk-jaeger-langfuse-evidently/README.md (observability_late_labels_sre_lab)
Tình huống Mở đầu: Bốn Điểm Mù Đánh Sập Mô Hình Sản Xuất Dù Bảng Giám Sát Vẫn Xanh#
Một nền tảng chấm điểm gian lận tài chính kết hợp trợ lý Agent/LLM xử lý khiếu nại có thể hiển thị HTTP 200 OK và CPU 35% suốt cả tháng trong khi thiệt hại kinh doanh đã tích tụ hàng trăm nghìn USD do bốn điểm mù kinh điển:
- Bão Báo động Giả Từ Kiểm định
KSTrên Mẫu Lớn (50,000Giao dịch): Đội ngũ dữ liệu cài ngưỡngp < 0.05trên kiểm định hai mẫuKolmogorov–Smirnov(KS) cho luồng50,000điểm/giờ. Chỉ một biến thiên sinh hoạt ngày–đêm vô hại (+0.035 sigma) trongLab 20(Exp 1) đã đẩyp_KS = 0.00800434 < 0.05(naive_ks_alarm = True), dùPSI = 0.000687và khoảng cáchWasserstein-1chuẩn hóa chỉ là0.026534. Kỹ sư trực đêm bị quá tải cảnh báo giả rồi tắt tiếng kênh cảnh báo đúng lúc trôi thật (PSI = 0.611997,W1/std = 0.876281,MMD^2 = 0.088917) ập tới! - Ảo ảnh Nhãn Đến Trễ Khiến Mô Hình Mù Suốt
39Ngày (Chuyên đề #17): Trong bài toán gian lận thanh toán (Lab 20,Exp 2), nhãn giao dịch hợp lệ (Y=0) xác nhận sớm với trung vị4.16ngày, nhưng khiếu nại gian lận (Y=1, chargeback) mất trung vị28.25ngày (đuôi tới90ngày). Khi một đợt tấn công ẩn (Silent Concept Drift) bắt đầu từDay 15, tạiDay 21(cohort day_15_to_21, mới có24.11%nhãn về), độ chính xác thật đã sụp từ82.62%xuống60.46%, nhưng Naive Observed Accuracy vẫn ảo giác ở mức85.78%(+25.31 pp) và không bao giờ nổ cảnh báo trên cửa sổ tuần! Chỉ khi kết hợp bù kiểm duyệtIPCWước lượng qua đường cong sống sót thực nghiệmKaplan–Meier(Cohort Day 28:61.61%, giảm sai số xuống+1.15 ppso với+21.53 ppcủa Naive), tín hiệu thay thế (Prediction PSI = 0.232916,Entropy +0.0491 nats), và kiểm toán chủ động phân tầngHorvitz–Thompson(160mẫu/tuần =5.71%, đo được63.09%ngayDay 21,MAE = 3.87 pp), hệ thống mới phát hiện sự cố sớm hơn39ngày! - Vòng lặp Công cụ
AgentĐốt Tiền Token & Rò rỉPIIVào Nhật ký: Phiên bản promptv2.4.1vẫn trảHTTP 200 OKdưới200 ms, nhưng gọi lặp công cụ làmgen_ai.cost_usdtăng vọt mà không có cảnh báo; đồng thời log gỡ lỗi ghi thẳng email (an.nguyen@example.com), thẻ thanh toán và khóa APIsk-...xuốngElasticsearchvì thiếuAutomated Telemetry Output TestingtrongCI/CD. - Nổ
TSDB OOMVì Nhãn Lực lượng Cao & Cảnh báo Hạ tầng Nhạy Nhiễu: Gắnuser_idhoặctrace_idlàm nhãnPrometheusgây tràn bộ nhớ chuỗi thời gian; còn cảnh báo lỗi tức thời5phút khiến nhóm vận hành thức trắng đêm dù ngân sách lỗi30ngày (43.2phút tạiSLO 99.9%) hầu như chưa suy suyển (transient 5m spike:5m = 18.0x,1h = 1.2x\(\to\) bị triệt tiêu đúng chuẩn bởiMulti-Window Multi-Burn-Rate 14.4x 1h/5m).
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 25 và Lab 20 (observability_late_labels_sre_lab), kỹ sư Dữ liệu & AI làm chủ năm năng lực cốt lõi:
- Thiết kế Kiến trúc Ba Trụ cột Quan sát Toàn phần (
R50): Phân tách đúng dữ liệu vàoLogs(Elasticsearch/Filebeat/Kibana),Metrics(Prometheus/Grafana), vàTraces(OpenTelemetry Collector/Jaeger), tuân thủ nguyên tắc lực lượng nhãn thấp trênPrometheusvà liên kết chéo mọi bản ghi quatrace_id/span_id. - Làm chủ Toán học Phát hiện Trôi Dữ liệu (
Evidently): Dẫn xuất và lựa chọn chính xácPSI,Kolmogorov–Smirnov(KS),Wasserstein-1(\(W_1\)) và Embedding Drift (Cosine,RBF MMD^2), đồng thời hóa giải bẫy báo động giả củaKSở cỡ mẫu lớn \(N \ge 50{,}000\). - Giải quyết Tận gốc Bài toán Giám sát Khi Nhãn Đến Trễ (
#17): Phân tích thiên lệch kiểm duyệt phải bất đối xứng (Differential Right-Censoring), cài đặt bộ ước lượng bù kiểm duyệtIPCW, theo dõi tín hiệu thay thế không nhãn (Prediction PSI,Entropy,CBPE), và triển khai kiểm toán con người chủ động phân tầng (Horvitz–Thompson). - Xây dựng Quan sát Đặc thù
LLM/Agent(Langfuse+OTel GenAI) & Kiểm thử Tự động Telemetry (R50): Chuẩn hóa cây spanlangfuse.trace\(\to\)gen_ai.agent_step\(\to\)gen_ai.tool_call\(\to\)gen_ai.generation, che chắnPIIhai tầng, và viết bộ testFastAPI TestClient+InMemorySpanExporterchặn mọi PR làm ròPIIhoặc sai hợp đồng telemetry. - Thực hành
SREChuẩn Công nghiệp (AIDE 1 & 3): Định nghĩaSLI,SLO,SLA, tính ngân sách lỗi30ngày, lập cấu hình cảnh báo đa cửa sổ đa tỷ lệ đốt (14.4x 1h/5m,6.0x 6h/30m), và tự động kích hoạt đóng băng triển khai (Deployment Freeze) khi ngân sách lỗi cạn kiệt.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P5-U02)#
Nội dung Gốc (R50, AIDE 1/3) & Chuyên đề #17 |
Nâng cấp Chuẩn SOTA 2026 (Ch 25) |
Mục trong Chương 25 | Tạo tác & Kiểm thử (observability_late_labels_sre_lab) |
|---|---|---|---|
1. Three pillars: Logs, Metrics, Traces & Observable Architecture |
OTel 2 tầng (loadbalancing traceID \(\to\) tail_sampling, 0.0.0.0:4317/4318) + Prometheus 3.0+ Native Histograms (schema=3, tránh cụt +Inf = 1.0s) + ELK; chặn nhãn lực lượng cao |
Trụ cột 1 (§1.1) + Trụ cột 2 (Mermaid 2) | docker-compose.yml, prometheus.yml, otel_collector_*.yaml, Tests 16, 20–23, 31 |
2. Drift detection (Evidently: PSI, KS, Wasserstein, Embedding) |
Đối chiếu 4 kịch bản: Covariate (PSI=0.612, W1=0.876, MMD2=0.089) vs Bẫy KS n=50k (p=0.0080 giả) vs Silent Concept Drift |
Trụ cột 1 (§1.2) + Widget 1 | drift_and_late_labels.py, Tests 03–07 |
3. #17 Monitoring Model Quality When Labels Arrive Late |
Mô phỏng 1–90d (Y=1 28.25d vs Y=0 4.16d): +25.31 pp ảo giác Naive (Day 21), IPCW qua Kaplan–Meier (61.61% Day 28), Entropy/Pred PSI & Audit HT (3.87 pp MAE, sớm 39d) |
Trụ cột 1 (§1.3) + Mermaid 1 + Widget 2 | simulate_delayed_label_monitoring, compute_kaplan_meier_curve, Tests 08–11, 29 |
4. LLM & Agent telemetry (Langfuse + OTel GenAI v1.37+ + RAGAS) |
Cây span chuẩn OTel v1.37+ (gen_ai.operation.name="chat", gen_ai.provider.name, finish_reasons=["stop"]) + đánh giá RAGAS (faithfulness, relevancy, context_precision) + cảnh báo đốt tiền \$25/h |
Trụ cột 1 (§1.4) + Trụ cột 2 + Widget 3 | create_observed_app (/v1/llm/chat, /v1/llm/ragas_eval), Tests 17–18, 30 |
5. Test Telemetry Output (Kiểm thử Tự động Telemetry) |
Bộ kiểm thử TestClient + InMemorySpanExporter: 7+4 OTel spans, 100% trace_id log-span, /metrics (kèm drift gauges), Luhn-checked PII & ghp_ |
Trụ cột 2 (§2.3) + Trụ cột 3 | run_automated_telemetry_tests, redact_pii, Tests 15, 18–19, 25, 30 |
6. SRE Practice: SLI, SLO, SLA, Error Budgets, Burn-Rate |
Ngân sách 43.2 phút/30d (99.9%); 14.4x 1h/5m (guard > 0 không mù khi < 1 RPS, bỏ clamp_min) & đóng băng rollout |
Trụ cột 1 (§1.4) + Mermaid 3 + Widget 3 | SREEngine, prometheus_sre_alerts.yaml, Tests 12–14, 24, 31 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 25 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 25 & observability_late_labels_sre_lab |
Giá trị Thực nghiệm Lab 20 (seed=42) |
|---|---|---|---|
| \(\text{PSI}(P, Q)\) | \([0, \infty)\) | Chỉ số ổn định quần thể đối xứng trên \(B=10\) giỏ phân vị tham chiếu (>=0.25 trôi nặng) |
Covariate: 0.611997; Trap 50k: 0.000687; Day 21 X0: 0.002636, Pred: 0.232916 |
| \(D_{n,m}, p_{\text{KS}}\) | \([0, 1]\) | Thống kê Kolmogorov–Smirnov cực đại hai ECDF và \(p\)-value tiệm cận |
Trap 50k (+0.035 sigma): \(D=0.0105\), p = 0.00800434 (bẫy báo động giả!) |
| \(W_1, W_{1,\text{norm}}\) | Đơn vị gốc / \(\sigma\) | Khoảng cách Wasserstein-1 (\(W_1(X, X+\Delta) = \|\Delta\|\)) và chuẩn hóa theo \(\sigma_{\text{ref}}\) |
Covariate: 0.876281; Trap 50k: 0.026534 (< 0.25) |
| \(d_{\cos}, \widehat{\text{MMD}}^2_u\) | \([0, 2]\), \([0, \infty)\) | Khoảng cách cosine trung tâm và RBF-MMD không thiên lệch trên không gian vector nhúng | Baseline MMD^2 = 0.000086 vs Topic Shift 0.088917 (cos = 0.485556) |
| \(m_c(a), w_i(t)\) | \((0, 1]\), \([1, 12.5]\) | Đường cong trưởng thành Kaplan–Meier theo lớp \(c \in \{0, 1\}\) ở tuổi \(a\); trọng số IPCW (\(m_{\min}=0.08\)) |
Trung vị trễ \(Y=0\): 4.16d vs \(Y=1\): 28.25d; Cohort Day 28: KM-IPCW 61.61% (+1.15 pp) |
| \(\hat{\theta}_{\text{HT}}, H(\hat{p})\) | \([0, 1]\), nats | Ước lượng Horvitz–Thompson qua kiểm toán phân tầng; entropy nhị phân dự đoán \(\hat{p}\) |
Audit HT (160/wk): Day 21 63.09% (MAE = 3.87 pp vs Naive 25.03 pp); \(\Delta H = +0.0491\) |
| \(\text{EB}, r_{\text{burn}}\) | Phút / Hệ số (\(\times\)) | Ngân sách lỗi 30 ngày \((1 - \text{SLO}) \cdot 43{,}200\); tỷ lệ đốt lỗi chia ngân sách lỗi |
99.9% SLO \(\implies\) 43.2 phút; 14.4x 1h/5m & 6.0x 6h/30m |
Trụ cột 1 — Nguyên lý Gốc & Frontier: Ba Trụ cột Quan sát, Toán học Trôi Dữ liệu, Nhãn Trễ (#17) & SRE#
1.1 Ba Trụ cột Quan sát (Logs, Metrics, Traces) & Quy tắc Lực lượng Nhãn#
Trong một hệ thống phân tán phục vụ ML/LLM, monitoring chỉ kiểm tra các ngưỡng thất bại đã biết trước, còn observability bảo đảm kỹ sư có thể truy nguyên nguyên nhân gốc của những sự cố chưa từng lường trước chỉ từ dữ liệu telemetry phát ra:
- Logs (
Elasticsearch+Filebeat+Kibana): Ghi lại từng sự kiện rời rạc dạngJSONcó cấu trúc (ECS schema). Mỗi dòng log bắt buộc mang cặp định danhtrace_id(32hex) vàspan_id(16hex) theo chuẩnW3C TraceContextđể nhảy thẳng từ một biểu đồ chậm sang đúng chuỗi sự kiện gây lỗi, đồng thời bắt buộc che chắn PII trước khi rời ứng dụng. - Metrics (
Prometheus 3.0++Grafana): Nén các đại lượng số theo thời gian bằngCounter,Gauge, vàHistogram. Để tính đúng độ trễ đuôip99trên toàn cụm nhiều bản sao, tuyệt đối không lấy trung bình các giá trịp99từng máy mà phải tổng hợp bằnghistogram_quantile(...):- Bẫy Cắt cụt Đuôi Cố định (
le = 1.0s\(\to\)+Inf) &Prometheus 3.0+ Native Histograms: Trên API suy luậnLLM(/v1/llm/chat), hỗn hợp trả lời ngắn (~0.18s) và sinh chuỗiRAG/CoTdài (1.2s–4.8s) khiến13.9%yêu cầu vượt ngưỡng1.0s(Lab 20, truep99 = 3.3018s). Với histogram giỏ cố định cũ (le = [0.01, ..., 1.0]),histogram_quantile(0.99, ...)nổ thành+Inf(hoặc sai số nội suy20–50%trên giỏ thưa). Ngược lại, Prometheus3.0+ Native Histograms(--enable-feature=native-histograms,schema = 3) dùng giỏ lũy thừa \(b_k = (2^{2^{-3}})^k\) nén gọn trong1chuỗi thời gian duy nhất và ước lượng đượcp99 = 3.3636s(sai số tương đối chỉ1.87%qua54giỏ tự động). - Cấm kỵ Lực lượng Cao (High-Cardinality Ban): Mỗi tổ hợp nhãn duy nhất tạo ra một chuỗi thời gian riêng trong RAM của
Prometheus TSDB. Đưauser_id,request_id,trace_id, hayemailvào nhãn Prometheus sẽ nhân số chuỗi lên hàng triệu và gây sậpOOMKilled! Các định danh lực lượng cao chỉ được nằm trong Traces và Logs; Prometheus chỉ giữ các nhãn tập hữu hạn nhưroute,status_class,model_version,prompt_version. - Tránh điểm mù
clamp_min(..., 1)trên lưu lượng thấp (< 1 RPS): Không bao giờ kẹp mẫu số tỷ lệ lỗi bằngclamp_min(sum(rate(...)), 1)vì tại lưu lượng0.2 RPS, lỗi2%(20xburn rate!) bị chia cho1.0thành0.004 < 0.0144và mù hoàn toàn. Thay bằng bộ lọc mẫu số tường minh(sum(rate(fsds_ml_http_requests_total[1h])) > 0).
- Bẫy Cắt cụt Đuôi Cố định (
- Traces (
OpenTelemetry SDK/Collector+Jaeger+Langfuse): Biểu diễn toàn bộ hành trình một yêu cầu dưới dạng câySpanphân cấp từ cổngFastAPI\(\to\) suy luậnML/LLM\(\to\) gọi công cụ. Tại tầngOTel Collector, kỹ sư bậtTail-Based Samplingđể giữ lại100%trace có lỗi (ERROR) hoặc độ trễ vượt SLO (>= 500 ms) trong khi chỉ lấy mẫu10%trace bình thường — cắt giảm chi phí lưu trữ mà không mất dấu vết sự cố hiếm.- Tại sao
tail_sampling1tầng sau Load Balancer tròn làm vỡ trace & Kiến trúc2tầngloadbalancing(traceID): Khi chạy \(\ge 2\) bản saoOTel Collectorsau Load Balancer quay vòng (round-robin), các span mang cùng mộttraceIDbị đẩy ngẫu nhiên sang các Pod Collector khác nhau; không Pod nào gom đủ toàn bộ cây span nên chính sácherrors-alwayshoặcslow-slo-tracesđưa ra quyết định sai và làm đứt gãy trace! Giải pháp chuẩn sản xuất là kiến trúc 2 tầng: Tầng 1 (otel_collector_lb_gateway.yaml) chạy bộ xuấtloadbalancingbăm nhất quán theorouting_key: traceIDqua Kubernetes Headless Service (clusterIP: None) để dồn mọi span cùngtraceIDvề đúng một Pod Tầng 2 (otel_collector_config.yaml, bind0.0.0.0:4317/4318) chạytail_samplingvàattributes/pii_redact.
- Tại sao
1.2 Toán học Phát hiện Trôi Dữ liệu (Evidently): PSI, KS, Wasserstein-1 & Embedding MMD^2#
Cho phân phối tham chiếu \(P\) (mẫu huấn luyện/tuần chuẩn cỡ \(n\)) và phân phối hiện tại \(Q\) (cửa sổ sản xuất cỡ \(m\)):
1. PSI (Population Stability Index — Phân kỳ Jeffreys Rời rạc)#
Chia miền \(P\) thành \(B=10\) giỏ theo các phân vị thập phân trên tập tham chiếu (hai đầu mở \((-\infty, \infty)\)), tính tỷ trọng làm mượt \(\tilde{p}_b, \tilde{q}_b \ge \varepsilon = 10^{-6}\):
- Ngưỡng quy ước:
< 0.10(ổn định),0.10–0.25(cảnh báo theo dõi),>= 0.25(trôi nghiêm trọng). - Ưu & nhược: Tính nhanh \(O((n+m)\log B)\), không phụ thuộc đơn vị, nhưng phụ thuộc lựa chọn giỏ và kém nhạy nếu khối lượng dịch chuyển dồn hết vào cùng một giỏ biên.
2. Kiểm định Hai mẫu Kolmogorov–Smirnov (KS) & Bẫy Kích thước Mẫu Lớn#
Thống kê KS đo khoảng cách cực đại giữa hai hàm phân phối tích lũy thực nghiệm (ECDF):
Tại sao KS p < 0.05 hỏng nặng trong sản xuất dữ liệu lớn? Khi \(n = m = 50{,}000\), hệ số \(N_{\text{eff}} \approx 158.11\). Một nhiễu sinh hoạt ngày–đêm nhỏ xíu \(\Delta\mu = 0.035\sigma\) chỉ tạo \(D_{n,m} = 0.0105\), nhưng tích \(N_{\text{eff}} D_{n,m} \approx 1.66\) đẩy p_KS = 0.00800434 < 0.05 (Lab 20 Exp 1), phát báo động giả liên miên dù phân phối thực tế gần như không đổi!
3. Khoảng cách Wasserstein-1 (Earth Mover's Distance) — Thước đo Vàng Theo Kích thước Ảnh hưởng#
- Bất biến & Tuyến tính: Với mọi phép tịnh tiến \(Y = X + \Delta\), ta có \(W_1(X, X+\Delta) = |\Delta|\) chính xác (độ phức tạp \(O((n+m)\log(n+m))\) bằng sắp xếp hợp hai mảng). Khác với
KS(bão hòa tại \(1.0\)) vàKL/PSI(nổ khi hai giá đỡ rời nhau), \(W_{1,\text{norm}}\) đo đúng biên độ dịch chuyển thực tế độc lập với \(N\): ở kịch bản50knhiễu+0.035 sigma, \(W_{1,\text{norm}} = \mathbf{0.026534} \ll 0.25\), triệt tiêu hoàn toàn báo động giả củaKS!
4. Trôi Không gian Nhúng Vector (Embedding Drift: Cosine & RBF MMD^2)#
Trên vector nhúng LLM/RAG đa chiều (\(d \gg 1\)), dùng hai thước đo tổng hợp không dính bùng nổ kiểm định bội:
- Khoảng cách Cosine Trung tâm: \(d_{\cos}(\bar{e}_P, \bar{e}_Q) = 1 - \frac{\langle \bar{e}_P, \bar{e}_Q \rangle}{\|\bar{e}_P\|_2 \|\bar{e}_Q\|_2}\).
RBF MMD^2không thiên lệch (nhân \(k(u,v) = \exp(-\gamma \|u-v\|_2^2)\), \(\gamma = 1/d\), chi phí \(O((n+m)^2 d)\) trên cửa sổ mẫu đại diện):
1.3 Chuyên đề #17: Giám sát Chất lượng Mô hình Khi Nhãn Đến Trễ (Monitoring Model Quality When Labels Arrive Late)#
1. Tình huống Thất bại Thực tế (Concrete Failure Case: Ảo ảnh Kiểm duyệt Phải Bất đối xứng)#
Trong thương mại điện tử, chống gian lận thẻ, vỡ nợ tín dụng hay dự báo rời bỏ (churn), dự đoán \(\hat{y}_i\) phát ra tức thời tại \(t_i\), nhưng nhãn thật \(y_i \in \{0, 1\}\) đến sau độ trễ \(D_i \in [1, 90]\text{ ngày}\). Đặc biệt, độ trễ phụ thuộc mạnh vào bản thân nhãn thật (Differential Right-Censoring):
- Giao dịch hợp lệ (\(Y=0\)) xác nhận qua đối soát/OTP nhanh với trung vị
4.16ngày. - Giao dịch gian lận (\(Y=1\)) phải chờ khách hàng khiếu nại sao kê ngân hàng (chargeback), mất trung vị
28.25ngày (đuôi tới90ngày).
Khi Trôi Khái niệm Thầm lặng (Silent Concept Drift) bùng phát từ Day 15 (phân phối biên từng đặc trưng \(P(X_j)\) gần như đứng yên với feature_x0_psi = 0.002636, nhưng cấu trúc tương tác \(X_0, X_1\) đổi chiều và kẻ tấn công nhắm vào nhóm rủi ro thấp \(\hat{y}=0\) khiến độ chính xác thật sụp từ 82.62% xuống 60.46%):
- Tại
Day 21, mới chỉ có24.11%giao dịch của tuầnday_15_to_21kịp có nhãn — phần lớn là các ca \(Y=0\) đến sớm, còn các ca gian lận bỏ sót (\(\hat{y}=0, Y=1\)) hầu như chưa về! - Phép tính Naive Observed Accuracy trên
675nhãn đã về báo cáo85.78%(ảo giác lạc quan+25.31 ppso với sự thật60.46%!), và không hề nổ bất kỳ cảnh báo nào trên toàn chuỗi cửa sổ trượt hàng tuần (naive_first_alert_day = None)!
2. Mô hình Định lượng Ba Lớp (IPCW + Tín hiệu Thay thế + Kiểm toán Chủ động Phân tầng)#
Đặt tuổi đoàn hệ tại thời điểm quan sát \(t\) là \(a_i = t - t_i\), biến quan sát nhãn \(R_i(t) = \mathbf{1}\{D_i \le a_i\}\), và đường cong trưởng thành lịch sử ước lượng thực nghiệm từ dấu thời gian đến & kiểm duyệt phải bằng ước lượng tích–giới hạn Kaplan–Meier (Product-Limit Estimator):
trong đó \(d_{c,k}\) là số nhãn lớp \(c\) kịp về tại mốc tuổi \(u_k\) và \(n_{c,k}\) là số mẫu còn đang chờ (at-risk) ngay trước \(u_k\) (tuyệt đối không dùng hàm oracle tham số có sẵn ngoài thực tế).
-
Bộ ước lượng Bù Kiểm duyệt
IPCW(Inverse Probability of Censoring Weighting): Gán trọng số nghịch đảo xác suất trưởng thànhKaplan–Meierkèm sàn ổn định phương sai \(m_{\min} = 0.08\):\[w_i(t) = \frac{1}{\max\!\left(m_{\min},\, \hat{m}_{y_i}(t - t_i)\right)}, \qquad \widehat{\text{Acc}}_{\text{IPCW}}(t) = \frac{\sum_{i: R_i(t)=1} w_i(t)\, \mathbf{1}\{\hat{y}_i = y_i\}}{\sum_{i: R_i(t)=1} w_i(t)}\]Các ca gian lận \(Y=1\) về sớm được nhân trọng số cao hơn nhiều so với \(Y=0\), triệt tiêu dần thiên lệch lạc quan: trên đoàn hệ cố định
Days 15–21, tạiDay 28(57.54%nhãn về),Naivevẫn mắc ảo giác+21.53 pp(82.0%), cònIPCW(Kaplan–Meier) đã hội tụ sát về61.61%(+1.15 ppsai số, chính xác hơn18x)!- Ràng buộc: Ở tuổi cực non (\(a < 7\) ngày, khi \(\hat{m}_1(a) < m_{\min}\)), ngay cả
IPCWvẫn còn dư sai số (+14.43 pptạiDay 21) do số ca \(Y=1\) về quá ít.
- Ràng buộc: Ở tuổi cực non (\(a < 7\) ngày, khi \(\hat{m}_1(a) < m_{\min}\)), ngay cả
-
Tín hiệu Thay thế Không Nhãn (
Label-Free Proxy Signals:Prediction PSI&Entropy): Không cần chờ dù chỉ1nhãn \(Y\), ta giám sát ngay phân phối xác suất đầu ra \(\hat{p}_i\) và entropy dự đoán:\[H(\hat{p}_i) = -\hat{p}_i \ln \hat{p}_i - (1 - \hat{p}_i) \ln(1 - \hat{p}_i) \in [0, \ln 2]\]Khi mẫu trượt vào vùng mơ hồ \(\hat{p}_i \in [0.35, 0.65]\), tại
Day 21prediction_psinhảy vọt từ0.004729lên0.232916vàentropy_delta_nats = +0.0491, kích hoạt báo động sớm ngay tuần đầu (proxy_first_alert_day = 21) dùfeature_x0_psichỉ là0.002636!- Ràng buộc:
CBPE(\(\frac{1}{N}\sum \max(\hat{p}_i, 1-\hat{p}_i) = 80.20\%\)) giả định mô hình giữ nguyên hiệu chuẩn \(P(Y \mid \hat{p})\), nên khi \(P(Y \mid X)\) đổi chiều (Concept Drift), chỉCBPEđơn lẻ sẽ không đo được cú rơi thực60.46%.
- Ràng buộc:
-
Kiểm toán Con người Chủ động Phân tầng (
Active Human-Audit+Horvitz–Thompson): Phân tầng lưu lượng hàng tuần theo điểm rủi ro (<0.35,[0.35, 0.65],>0.65với tỷ lệ phân bổ(0.45, 0.35, 0.20)), lấy ngẫu nhiên \(n_h\) giao dịch trong \(N_h\) mẫu mỗi tầng (tổng ngân sách chỉ160ca/tuần =5.71%lưu lượng trongLab 20) để chuyên gia gán nhãn nhanh trong24–48h, rồi dùng bộ ước lượng không chệch Horvitz–Thompson (\(\pi_h = n_h / N_h\)):\[\widehat{\text{Acc}}_{\text{HT}} = \frac{1}{N} \sum_{h=1}^{3} \sum_{i \in S_h} \frac{\mathbf{1}\{\hat{y}_i = y_i\}}{\pi_h}\]
3. Thí nghiệm Kiểm chứng Có Kiểm soát (Lab 20 Exp 2, seed=42)#
- Trên đoàn hệ trượt hàng tuần hậu trôi (
Days 21–56),Naive Observedchịu sai sốMAE = 25.03 ppvà không bao giờ báo động;IPCW(Kaplan–Meier) hạMAExuống12.32 pp(alert Day 21);Active Audit HT(5.71%chi phí gán nhãn) đạt63.09%ngayDay 21vớiMAE = 3.87 pp, rút ngắn thời gian phát hiện sớm hơn39ngày!
4. Cẩm nang Quyết định Giám sát Nhãn Trễ (#17 Production Playbook)#
| Chế độ Trôi & Độ trễ Nhãn | Biện pháp Khuyến nghị | Lý do & Ngưỡng Kích hoạt Thực chiến |
|---|---|---|
| Tuần đầu sau thay đổi (\(a < 7\text{ ngày}\), \(m_1(a) < 0.08\)) | Active Human-Audit (HT) + Entropy/Prediction PSI Proxy |
Naive mù hoàn toàn (+25.31 pp); IPCW còn phương sai cao; kiểm toán phân tầng ~5% bắt trọn suy giảm ngay tuần 1 (3.87 pp MAE). |
Đoàn hệ trung hạn (14–45 ngày, \(m_1(a) \in [0.25, 0.85]\)) |
Class-Conditional Kaplan–Meier IPCW |
Khử thiên lệch Y=1 về chậm (Day 28: sai số +1.15 pp so với +21.53 pp của Naive), giúp tính lại PR-AUC & hiệu chuẩn cho tái huấn luyện. |
Chế độ Tương phản (Nhãn có tức thời < 5 phút) |
Giám sát Trực tiếp SLI/Chất lượng + Evidently PSI/W1 |
Không cần IPCW hay chi phí gán nhãn HT vì tỷ lệ kiểm duyệt phải \(R_i(t) \approx 100\%\). |
1.4 Quan sát Đặc thù LLM/Agent (Langfuse + OTel GenAI v1.37+ + RAGAS) & Toán học SRE (SLI/SLO/SLA)#
1. Chuẩn Span OTel GenAI v1.37+, Langfuse & Đánh giá RAGAS Cho Hệ thống Tác nhân#
Mỗi lượt gọi /v1/llm/chat và /v1/llm/ragas_eval phát sinh một cây quan sát tuân thủ OpenTelemetry GenAI Semantic Conventions v1.37+ gắn liền nhau bằng trace_id (đã loại bỏ các khóa cũ gen_ai.system và số ít gen_ai.response.finish_reason):
langfuse.trace(langfuse.observation.type="trace",gen_ai.prompt.version,gen_ai.prompt.redacted)- \(\to\)
gen_ai.agent_step(agent.step_index)- \(\to\)
gen_ai.tool_call(gen_ai.tool.name,langfuse.observation.type="span") - \(\to\)
gen_ai.generation(gen_ai.operation.name="chat",gen_ai.provider.name="vllm",gen_ai.request.model,gen_ai.usage.input_tokens,gen_ai.usage.output_tokens,gen_ai.cost_usd,gen_ai.tool.calls,gen_ai.response.finish_reasons=["stop"]dạng mảng chuỗi,ragas.faithfulness,ragas.answer_relevancy,ragas.context_precision,langfuse.observation.type="generation")
- \(\to\)
- \(\to\)
gen_ai.evaluation.ragas(langfuse.observation.type="evaluator",gen_ai.provider.name="vllm", chấm tự động độ trung thực với ngữ cảnhragas.faithfulness, độ liên quanragas.answer_relevancy, và độ chính xác truy xuấtragas.context_precision).
- \(\to\)
Nhờ gắn gen_ai.prompt.version, gen_ai.cost_usd, và bộ ba chỉ số RAGAS trực tiếp lên Span cùng bộ đếm/gauge Prometheus (fsds_ml_gen_ai_cost_usd_total, fsds_ml_prediction_psi, fsds_ml_audit_early_accuracy_drop), kỹ sư bắt được ngay hiện tượng vòng lặp công cụ đốt ngân sách vượt \$25/giờ, tụt độ trung thực RAG, hoặc sụp chất lượng theo phiên bản prompt.
2. Phương trình SRE: SLI, SLO, SLA & Cảnh báo Đa Cửa sổ Đa Tỷ lệ Đốt#
SLI(Service Level Indicator): \(\text{SLI} = \frac{\text{Good Requests (HTTP 2xx \& Latency } \le 500\text{ ms)}}{\text{Valid Requests}} \times 100\%\).SLOvs.SLA:SLO(ví dụ99.9%trên cửa sổ trượt \(W = 30\text{ ngày} = 43{,}200\text{ phút}\)) là mục tiêu vận hành nội bộ nghiêm ngặt hơnSLA(99.5%) ghi trong hợp đồng thương mại, tạo vùng đệm phản ứng kỹ thuật trước khi bị phạt tiền.- Ngân sách Lỗi (
Error Budget):\[\text{EB} = (1 - \text{SLO}) \times W = 0.001 \times 43{,}200\text{ phút} = \mathbf{43.2\text{ phút/tháng}}\] -
Tỷ lệ Đốt Ngân sách (
Burn Rate) & Cảnh báo Đa Cửa sổ (Google SRE Workbook):\[r_{\text{burn}}(w) = \frac{\text{Error Rate}(w)}{1 - \text{SLO}}\]Critical Page(14.4x,1hAND5m): Tiêu thụ2%ngân sách tháng trong1giờ (43,200 / 14.4 = 3,000 phút = 50 giờlà cháy sạch!). Điều kiệnANDtrên cả cửa sổ dài (1h) lẫn ngắn (5m) vừa báo sự cố thật trong5phút vừa triệt tiêu nhiễu gai thoáng qua (ví dụ5m = 18.0xnhưng1h = 1.2xtrongLab 20\(\to\) không báo trang và không đóng băng).High Warning(6.0x,6hAND30m): Tiêu thụ5%ngân sách trong6giờ.Deployment Freeze: Tự động khóa các bản phát hành tính năng/mô hình mới khi cảnh báo14.4xđang cháy HOẶCbudget_remaining_pct <= 0.0%— buộc toàn đội tập trung sửa độ tin cậy hoặc hoàn tác phiên bản.
Trụ cột 2 — Kiến trúc Hệ thống Toàn phần, Cổng SRE & Kiểm thử Tự động Telemetry#
2.1 Kiến trúc Hợp nhất OTel Collector + ELK + Prometheus/Grafana + Jaeger + Langfuse + Evidently#
2.2 Luồng Quyết định Đa Cửa sổ SRE & Tự động Đóng băng Triển khai (Deployment Freeze)#
2.3 Kiểm thử Tự động Đầu ra Telemetry (Automated Telemetry Output Testing — R50)#
Trong quy trình CI/CD SOTA 2026, telemetry không được phép kiểm tra bằng mắt thủ công trên Kibana/Jaeger sau khi đã lên production mà phải có hợp đồng kiểm thử tự động ngay trong pytest:
Lớp Kiểm thử Telemetry (Lab 20) |
Cơ chế Xác minh Không Phụ thuộc Hạ tầng Ngoài | Tiêu chí Đạt (CI Gate Pass) |
|---|---|---|
1. Hợp đồng Span OTel v1.37+, Langfuse & RAGAS |
Dùng InMemorySpanExporter gắn vào TracerProvider của FastAPI TestClient |
Đủ 7 span sống (ml.predict, langfuse.trace, gen_ai.agent_step, gen_ai.tool_call, gen_ai.generation), có gen_ai.operation.name, gen_ai.provider.name, finish_reasons=["stop"], ragas.*, 0 khóa cũ |
2. Kiểm toán /metrics & Native Histogram |
Gọi GET /metrics kiểm tra exposition format + validate_labels + NativeHistogram |
Đếm 2xx/5xx, llm_tokens_total, cost_usd, fsds_ml_prediction_psi, fsds_ml_audit_early_accuracy_drop, Native Histogram schema=3; chặn nhãn lực lượng cao |
3. Tương quan Trace-Log & 0 Rò rỉ PII (Luhn + ghp_) |
Quét toàn bộ dòng ELK JSON và span.attributes sau khi bơm email, thẻ Luhn, SĐT, sk-/ghp_, timestamp ns |
100% log khớp trace_id; 0 rò rỉ PII; giữ nguyên Unix timestamp 19 số không khớp Luhn |
4. Kiểm toán YAML 2-Tầng OTel & Prometheus |
Quét PyYAML trên docker-compose.yml, otel_collector_*.yaml, prometheus.yml, prometheus_sre_alerts.yaml |
0 :latest, bind 0.0.0.0:4317/4318 OTLP nội bộ, http://langfuse:3000/api/public/otel khớp dịch vụ langfuse, scrape_native_histograms: true, routing_key: traceID, không dùng clamp_min(..., 1) |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#
Đoạn mã độc lập dưới đây chạy trực tiếp trong .venv (sử dụng numpy, fastapi, opentelemetry-sdk và TestClient), tái hiện trọn vẹn bốn bất biến cốt lõi của Chương 25: (1) Bẫy báo động giả KS trên 50,000 mẫu so với Wasserstein-1; (2) Ảo giác nhãn trễ vs bù kiểm duyệt IPCW bằng đường cong Kaplan–Meier thực nghiệm & kiểm toán phân tầng Horvitz–Thompson; (3) So sánh Prometheus 3.0+ Native Histograms vs bẫy cắt cụt +Inf = 1.0s; và (4) Span OTel GenAI v1.37+ + RAGAS + che PII Luhn & ghp_.
from __future__ import annotations
import json
import math
import re
from collections.abc import Sequence
import numpy as np
from fastapi import FastAPI
from fastapi.testclient import TestClient
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
class LocalSpanCollector(SpanExporter):
def __init__(self) -> None:
self.spans: list[ReadableSpan] = []
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
self.spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
return None
def wasserstein_and_ks(ref: np.ndarray, cur: np.ndarray) -> tuple[float, float, float]:
u, v = np.sort(ref), np.sort(cur)
all_v = np.sort(np.concatenate((u, v)))
deltas = np.diff(all_v)
cdf_u = np.searchsorted(u, all_v[:-1], side="right") / float(u.size)
cdf_v = np.searchsorted(v, all_v[:-1], side="right") / float(v.size)
w1 = float(np.sum(np.abs(cdf_u - cdf_v) * deltas))
pooled = np.concatenate((u, v))
d_stat = float(
np.max(
np.abs(
np.searchsorted(u, pooled, side="right") / float(u.size)
- np.searchsorted(v, pooled, side="right") / float(v.size)
)
)
)
en = math.sqrt((u.size * v.size) / float(u.size + v.size))
lam = (en + 0.12 + 0.11 / en) * d_stat
p_val = min(1.0, max(0.0, 2.0 * sum(((-1) ** (k - 1)) * math.exp(-2 * k * k * lam * lam) for k in range(1, 50))))
return round(w1 / float(np.std(ref)), 5), round(d_stat, 5), round(p_val, 6)
def fit_km_cdf(obs_t: np.ndarray, events: np.ndarray, query_ages: np.ndarray) -> np.ndarray:
t_unique = np.unique(obs_t[events])
t_grid, cdf_grid = [0.0], [0.0]
surv = 1.0
for tk in t_unique:
n_risk = int(np.sum(obs_t >= tk))
d_k = int(np.sum((obs_t == tk) & events))
if n_risk > 0:
surv *= 1.0 - float(d_k) / float(n_risk)
t_grid.append(float(tk))
cdf_grid.append(1.0 - surv)
tg, cg = np.array(t_grid), np.array(cdf_grid)
pos = np.clip(np.searchsorted(tg, query_ages, side="right") - 1, 0, cg.size - 1)
return cg[pos]
def redact_pii_luhn(text: str) -> str:
def _card_sub(m: re.Match[str]) -> str:
digits = re.sub(r"[^0-9]", "", m.group(0))
tot = sum(
(int(c) * 2 - 9 if int(c) * 2 > 9 else int(c) * 2) if i % 2 == 1 else int(c)
for i, c in enumerate(reversed(digits))
)
return "[REDACTED_CARD]" if 13 <= len(digits) <= 19 and tot % 10 == 0 else m.group(0)
cleaned = re.sub(r"\b(?:sk-[A-Za-z0-9_-]{8,}|ghp_[A-Za-z0-9]{20,})\b", "[REDACTED_SECRET]", text)
cleaned = re.sub(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "[REDACTED_EMAIL]", cleaned)
return re.sub(r"\b(?:\d[ -]*?){13,19}\b", _card_sub, cleaned)
def demo_pillar3_observability(seed: int = 42) -> None:
rng = np.random.default_rng(seed)
# 1. Large-N KS False-Alarm Trap (n=50,000, harmless +0.035 sigma shift)
ref_50k = rng.normal(0.0, 1.0, size=50_000)
cur_50k = rng.normal(0.035, 1.0, size=50_000)
w1_norm, _ks_d, ks_p = wasserstein_and_ks(ref_50k, cur_50k)
assert ks_p < 0.05 and w1_norm < 0.10
print(f"[1. Drift Trap] n=50k (+0.035 sigma): KS p={ks_p} (false alarm) vs W1_norm={w1_norm} (<0.25 OK)")
# 2. #17 Delayed-Label Illusion vs Empirical Kaplan-Meier IPCW & Active Audit HT
n_hist = 6000
h_y = (rng.random(n_hist) < 0.35).astype(np.int64)
h_u = np.clip(rng.uniform(0.0, 1.0, size=n_hist), 1e-6, 0.999)
h_delay = np.where(h_y == 1, 36.0 * np.power(-np.log(1.0 - h_u), 1.0 / 1.55), 5.5 * np.power(-np.log(1.0 - h_u), 1.0 / 1.35))
h_cens = rng.uniform(1.0, 60.0, size=n_hist)
h_obs_t = np.round(np.minimum(h_delay, h_cens), 2)
h_ev = h_delay <= h_cens
n_cohort = 2800
p_hat = np.clip(rng.beta(1.6, 4.2, size=n_cohort), 0.02, 0.98)
y_hat = (p_hat >= 0.5).astype(np.int64)
y_true = np.where(y_hat == 0, (rng.random(n_cohort) < 0.34).astype(np.int64), (rng.random(n_cohort) < 0.72).astype(np.int64))
ages = rng.uniform(7.5, 19.5, size=n_cohort)
c_u = np.clip(rng.uniform(0.0, 1.0, size=n_cohort), 1e-6, 0.999)
c_delay = np.where(y_true == 1, 36.0 * np.power(-np.log(1.0 - c_u), 1.0 / 1.55), 5.5 * np.power(-np.log(1.0 - c_u), 1.0 / 1.35))
arrived = c_delay <= ages
correct = (y_hat == y_true).astype(np.float64)
true_acc = float(np.mean(correct))
naive_acc = float(np.mean(correct[arrived]))
km_y0 = fit_km_cdf(h_obs_t[h_y == 0], h_ev[h_y == 0], ages[arrived])
km_y1 = fit_km_cdf(h_obs_t[h_y == 1], h_ev[h_y == 1], ages[arrived])
w_ipcw = 1.0 / np.maximum(0.08, np.where(y_true[arrived] == 1, km_y1, km_y0))
ipcw_acc = float(np.sum(w_ipcw * correct[arrived]) / np.sum(w_ipcw))
strata = np.where(p_hat < 0.35, 0, np.where(p_hat <= 0.65, 1, 2))
ht_sum = 0.0
for sid, k in ((0, 100), (1, 80), (2, 45)):
idx_s = np.flatnonzero(strata == sid)
chosen = rng.choice(idx_s, size=min(idx_s.size, k), replace=False)
ht_sum += float(np.sum(correct[chosen])) / (float(chosen.size) / float(idx_s.size))
audit_acc = ht_sum / float(n_cohort)
assert naive_acc - true_acc > 0.12 and abs(ipcw_acc - true_acc) < 0.04 and abs(audit_acc - true_acc) < 0.08
print(f"[2. #17 KM-IPCW] True={true_acc:.2%} | Naive={naive_acc:.2%} | KM-IPCW={ipcw_acc:.2%} | AuditHT={audit_acc:.2%}")
# 3. Prometheus 3.0+ Native Histogram vs Fixed le=1.0s Tail Trap
lat_llm = np.where(rng.random(1500) < 0.85, rng.lognormal(-1.8, 0.35, 1500), rng.lognormal(0.55, 0.45, 1500))
base = math.pow(2.0, math.pow(2.0, -3))
b_idx = np.ceil(np.log(np.maximum(1e-4, lat_llm)) / math.log(base)).astype(int)
vals, cnts = np.unique(b_idx, return_counts=True)
cum, nat_p99 = 0, float("inf")
for idx_b, cnt in zip(vals, cnts, strict=True):
cum += int(cnt)
if cum >= 0.99 * lat_llm.size:
nat_p99 = math.pow(base, int(idx_b))
break
assert float(np.mean(lat_llm > 1.0)) > 0.01 and abs(nat_p99 - float(np.percentile(lat_llm, 99.0))) / nat_p99 < 0.10
print(f"[3. Native Histogram] True p99={np.percentile(lat_llm, 99):.3f}s | Classic le=1.0s=+Inf | Native={nat_p99:.3f}s")
# 4. OTel GenAI v1.37+ + RAGAS Span + Luhn-Checked PII Redaction Test
collector = LocalSpanCollector()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(collector))
tracer = provider.get_tracer("pillar3_demo")
app = FastAPI()
@app.post("/llm")
def llm_endpoint(payload: dict[str, str]) -> dict[str, str]:
safe = redact_pii_luhn(payload["prompt"])
with tracer.start_as_current_span("gen_ai.generation") as sp:
sp.set_attribute("gen_ai.operation.name", "chat")
sp.set_attribute("gen_ai.provider.name", "vllm")
sp.set_attribute("gen_ai.prompt.version", "v2.4.1")
sp.set_attribute("gen_ai.usage.output_tokens", 180)
sp.set_attribute("gen_ai.cost_usd", 0.000121)
sp.set_attribute("gen_ai.response.finish_reasons", ["stop"])
sp.set_attribute("ragas.faithfulness", 0.94)
sp.set_attribute("ragas.answer_relevancy", 0.91)
sp.set_attribute("ragas.context_precision", 0.89)
sp.set_attribute("gen_ai.prompt.redacted", safe)
return {"prompt": safe}
with TestClient(app) as client:
res = client.post(
"/llm",
json={"prompt": "Refund an.nguyen@example.com card 4532-1111-2222-3336 pat ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234 ts=1732459384123456789"},
)
assert res.status_code == 200
dumped = json.dumps([dict(s.attributes or {}) for s in collector.spans])
assert "an.nguyen@example.com" not in dumped and "ghp_" not in dumped and "1732459384123456789" in dumped
assert "gen_ai.operation.name" in dumped and "gen_ai.provider.name" in dumped and "ragas.faithfulness" in dumped
print(f"[4. OTel v1.37+ & RAGAS & Luhn PII] Spans={len(collector.spans)} | Timestamp preserved | Zero PII leaks!")
if __name__ == "__main__":
demo_pillar3_observability(seed=42)
print("Pillar 3 Full-Stack Observability & Late-Label Verification PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (Lab 20: observability_late_labels_sre_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Lab 20 (labs/lab-20-otel-prom-elk-jaeger-langfuse-evidently/)#
- Tầng 1 — Cấu hình Hạ tầng Quan sát Sạch (
docker-compose.yml&configs/):docker-compose.yml: Khai báo8dịch vụ (otel-collector,jaeger,prometheus:v3.0.1bật--enable-feature=native-histograms,grafana,elasticsearch,filebeat,kibana,langfuse:3.25.0), gắn tag phiên bản rõ ràng (0:latest), khóa toàn bộ cổng về127.0.0.1:,cap_drop: [ALL],no-new-privileges:true, và0bí mật văn bản thuần.configs/otel_collector_lb_gateway.yaml&configs/otel_collector_config.yaml: Kiến trúc 2 tầng (loadbalancingrouting_key: traceID\(\to\)tail_sampling+attributes/pii_redact), lắng nghe OTLP trên0.0.0.0:4317/4318cho container Compose và xuấtotlphttp/langfusetới đúng dịch vụhttp://langfuse:3000/api/public/otel.configs/prometheus.yml&configs/prometheus_sre_alerts.yaml:prometheus.ymlbậtscrape_native_histograms: truevà được mount trực tiếp vào container Prometheus để scrapefsds-ml-llm-api&otel-collector;prometheus_sre_alerts.yamlloại bỏclamp_min(..., 1)bằng bộ lọc mẫu số tường minh> 0, và truy vấn trực tiếp các gaugefsds_ml_prediction_psi&fsds_ml_audit_early_accuracy_dropdo Python phát ra.
- Tầng 2 — Gói Python
observability_late_labels_sre_lab(src/observability_late_labels_sre_lab/):drift_and_late_labels.py: Thuật toánPSI,KS,Wasserstein-1,Embedding Cosine & RBF MMD^2; cùng mô phỏng#17dùngcompute_kaplan_meier_curvethực nghiệm (không dùng hàm oracle Weibull) đối chiếuNaive,KM-IPCW,Prediction PSI/Entropy, vàHorvitz–Thompson.otel_genai_sre_and_tests.py:SREEngine, ứng dụngFastAPIsống (create_observed_app) phát spanOTel GenAI v1.37+(gen_ai.operation.name="chat",gen_ai.provider.name,gen_ai.response.finish_reasons=["stop"]) +RAGAS(/v1/llm/ragas_eval),PrometheusMetricsRegistry(drift gauges +Native Histogramschema=3),ELK JSONlogs,redact_pii(Luhn check +ghp_), vàaudit_observability_configs.
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch25_lab20_results.json, seed=42)#
Thực nghiệm (observability_late_labels_sre_lab) |
Thông số Đo được (Xác định seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Exp 1 (Evidently Drift Suite — 4 Kịch bản) |
Baseline: PSI=0.01114, W1=0.071266; Covariate: PSI=0.611997, W1=0.876281, MMD2=0.088917; Trap 50k: KS p=0.00800434 vs W1=0.026534 (PSI=0.000687); Silent Concept (18% flip): PSI=0.007779 |
W1/std + PSI loại bỏ bão báo động giả KS cỡ lớn; trôi khái niệm qua mặt kiểm định đầu vào đơn thuần |
Exp 2 (#17 Delayed Labels, KM-IPCW & HT) |
Day 21 (24.11% nhãn): True 60.46% vs Naive 85.78% (+25.31 pp), Audit HT 63.09% (Pred PSI=0.232916, dH=+0.0491); Cohort 15–21 Day 28: KM-IPCW 61.61% (+1.15 pp) vs Naive 82.0% (+21.53 pp); MAE: Audit 3.87 pp vs KM-IPCW 12.32 pp vs Naive 25.03 pp |
Kiểm toán phân tầng 5.71% + Proxy sớm 39 ngày; Kaplan–Meier IPCW không oracle sửa thiên lệch từ tuần 2 |
Exp 3A (SRE Burn-Rate & Native Histograms) |
Budget 30d: 43.2 phút; Transient 5m bị triệt; 14.4x & Exhausted: freeze=True; LLM Chat p99 (13.9% > 1s, true 3.3018s): Fixed le=1.0s \(\to\) +Inf vs Native schema=3 3.3636s (1.87% sai số) |
Cảnh báo > 0 không mù ở < 1 RPS; Native Histogram giữ chính xác đuôi p99 đa thang đo |
Exp 3B (FastAPI + OTel v1.37+ + RAGAS + YAML) |
7 live + 4 suite = 11 OTel spans (gen_ai.operation.name="chat", gen_ai.provider.name, finish_reasons=["stop"], ragas.*, 0 khóa cũ); 3/3 ELK logs khớp trace_id; /metrics đủ drift gauges; 0 PII leaks; 8 Compose imgs, 0 :latest |
Tự động hóa kiểm thử hợp đồng telemetry v1.37+, RAGAS, và hạ tầng 2 tầng trong CI |
4.3 Quy trình Kiểm định Tự động (31/31 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-05-mlops-cicd-and-observability/labs/lab-20-otel-prom-elk-jaeger-langfuse-evidently
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch25_lab20_results.json
ruff check src scripts tests
mypy src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (6 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2022–2026#
- Beyer, Jones, Petoff & Murphy (O'Reilly / Google SRE Workbook). Alerting on SLOs: Multiwindow, Multi-Burn-Rate Alerts & Error Budgets. — Chuẩn toán học cho cảnh báo
14.4x(1h/5m),6.0x(6h/30m) và chính sách đóng băng triển khai khi cạn ngân sách lỗi. - Garg et al. (ICLR 2022) & NannyML / Evidently AI (2024–2026). Leveraging Unlabeled Data to Predict Out-of-Distribution Performance (
ATC/CBPE&Evidently Drift Benchmarks). — Phương pháp ước lượng suy giảm chất lượng từ độ tự tin/entropy và chuẩn mực chọnWasserstein-1/PSI/MMDtránh bẫyKScỡ lớn. - Huyen, Chip (2022–2025). Designing Machine Learning Systems & AI Engineering (O'Reilly) — Monitoring Model Quality When Labels Arrive Late (
#17). — Hệ thống hóa độ trễ nhãn phản hồi trong gian lận/tín dụng, bẫy kiểm duyệt phải và tín hiệu proxy. - Robins, Rotnitzky & Zhao (JASA) / Chapelle (WWW / Criteo Delayed Feedback). Modeling Delayed Feedback in Conversion & Fraud Systems with
IPCW. — Cơ sở thống kê cho trọng số nghịch đảo xác suất trưởng thành \(w_i = 1 / m_c(a_i)\) và cân bằng phương sai. - OpenTelemetry Specification (
v1.37+GenAI Semantic Conventions, 2024–2026) &RAGAS. Semantic Conventions for Generative AI Systems (gen_ai.provider.name,gen_ai.response.finish_reasons). — Quy chuẩn thuộc tính span mới cho LLM/RAG, tích hợpLangfuseOTLP và bộ chỉ số đánh giáRAGAS(faithfulness,answer_relevancy,context_precision). - Majors, Fong-Jones & Miranda (O'Reilly) & Prometheus
3.0+Native Histograms. Observability Engineering: Achieving Production Excellence. — Nguyên lý ba trụ cột liên kết bằngtrace_id, kiến trúc 2 tầngloadbalancing -> tail_sampling, Native Histograms và kiểm thử tự động telemetry.
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%) — Giải mã BẫyKSCỡ Lớn & Chọn Bộ Đo TrôiEvidently: Dùng kết quảExp 1(Tests 03–07), giải thích vì sao ởn = 50,000với độ dịch vô hại+0.035 sigma,KSlại báop = 0.00800434 < 0.05trong khiPSI = 0.000687vàW1/std = 0.026534; đồng thời chỉ ra lý do cảPSI,KS,W1, lẫnRBF MMD^2đều bỏ sót kịch bảnsilent_concept_drift(18%flip).Thang điểm: Chứng minh vai trò hệ số \(\sqrt{nm/(n+m)}\) làm nổ độ nhạy
KS(5%), giải thích tính bất biến tỷ lệ củaW1vàMMD^2(5%), passTests 03–07(5%). -
Bài tập 2 (
ex2, 20%) — Phân tích Thiên lệch Kiểm duyệt Phải & BùKM-IPCW(#17): TrongExp 2(Tests 08–09, 29), đối chiếu phân bố trễ \(Y=0\) (4.16d) với \(Y=1\) (28.25d), giải thích tại sao tạiDay 21(24.11%nhãn về),Naive Observedvọt lên85.78%(+25.31 ppảo giác) so vớiTrue = 60.46%, và vì saoKaplan–Meier IPCWước lượng từ dấu thời gian đến thực nghiệm đưa đoàn hệ15–21về61.61%(+1.15 ppsai số) ởDay 28nhưng vẫn chịu sai số14.43 pptạiDay 21.Thang điểm: Chứng minh cơ chế kiểm duyệt bất đối xứng làm
FN(\(Y=1\)) mất hút ở tuổi nhỏ (7%), giải thích ước lượngKaplan–Meier+ ngưỡng sàn \(m_{\min}=0.08\) (7%), passTests 08–09, 29(6%). -
Bài tập 3 (
ex3, 15%) — Thiết kế Proxy Không Nhãn & Kiểm toán Phân tầngHorvitz–Thompson(#17): Chứng minh vì sao tạiDay 21,Feature X0 PSI = 0.002636vẫn đứng yên nhưngPrediction PSIđạt0.232916vàEntropy Delta = +0.0491 nats; đồng thời viết lại công thứcHorvitz–Thompsontrên160ca kiểm toán/tuần (5.71%lưu lượng) giúp đạt63.09%ngayDay 21(MAE = 3.87 pp, sớm39ngày,Tests 10–11).Thang điểm: Giải thích cơ chế trôi tương quan làm tăng entropy dự đoán (
5%), chứng minh tính không chệch của \(\hat{\theta}_{\text{HT}}\) (5%), passTests 10–11(5%). -
Bài tập 4 (
ex4, 15%) — Tính toán Ngân sách LỗiSRE, Cảnh báo< 1 RPS& Native Histograms: Tính toán ngân sách lỗi30ngày cho99.9%SLO (43.2phút) và99.95%SLO (21.6phút); chứng minh vì saotransient_5m_spike_suppressedkhông đóng băng rollout, vì saoclamp_min(..., 1)gây mù dưới1 RPS, và vì sao Prometheus3.0+Native Histogram khắc phục bẫy cắt cụtle=1.0s(Tests 12–14, 30).Thang điểm: Tính đúng Error Budget & guard
> 0(5%), giải thích cơ chếAND& Native Histograms (5%), passTests 12–14, 30(5%). -
Bài tập 5 (
ex5, 20%) — Triển khaiFastAPI+OTel GenAI v1.37+/Langfuse/RAGAS+Prometheus+ELK: Phân tíchcreate_observed_appvàrun_automated_telemetry_tests(Tests 15–19, 30): chứng minh khóa chuẩngen_ai.operation.name="chat",gen_ai.provider.name,gen_ai.response.finish_reasons=["stop"],ragas.*, bộ lọc Luhn chống bắt nhầm timestampns+ghp_, vàfsds_ml_prediction_psitrên/metrics.Thang điểm: Trình bày đúng chuẩn span
v1.37+&RAGAS(7%), chứng minh kiểm thử tự động Luhn PII &/metrics(7%), passTests 15–19, 30(6%). -
Bài tập 6 (
ex6, 15%) — Kiểm toán Hạ tầngYAML2-Tầng OTel,prometheus.yml& Tính Xác định: Kiểm tra chuỗi cấu hìnhdocker-compose.yml(8dịch vụ cólangfuse:3.25.0),configs/otel_collector_config.yaml(0.0.0.0:4317/4318,http://langfuse:3000/api/public/otel),configs/otel_collector_lb_gateway.yaml(loadbalancingtraceID),configs/prometheus.yml(scrape_native_histograms: true),configs/prometheus_sre_alerts.yaml(Tests 20–28, 31), chạy sạchruff,mypy strict,31pytestvàuv lock --check.Thang điểm: Phân tích đúng kiến trúc 2 tầng
traceID& bảo mật YAML (5%), kiểm chứng đầy đủ bộ lệnh CI (5%), passTests 20–31(5%).
5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#
- (
q1— BẫyKSCỡ Lớn vs.Wasserstein-1&PSI): TrongLab 20 Exp 1, vì sao kiểm địnhKSởn = 50,000lại phát báo động giả cho mức dịch+0.035 sigmavà cặp chỉ số nào khắc phục dứt điểm hiện tượng này? - (
q2— Cấm kỵ Nhãn Lực lượng Cao & Tương quanLogs–Metrics–Traces): Điều gì xảy ra nếu đưauser_idhoặctrace_idvào nhãn metric củaPrometheus, và kiến trúc chuẩn đặt chúng ở đâu? - (
q3— Ảo ảnh Kiểm duyệt Phải Khi Nhãn Đến Trễ,#17): TạiDay 21trongLab 20 Exp 2, vì saoNaive Observed Accuracyvẫn báo tới85.78%trong khi độ chính xác thật đã sụp xuống60.46%? - (
q4— Bù Kiểm duyệtIPCWTrên Đoàn hệ Trễ Nhãn,#17): Cơ chế trọng sốIPCW(Kaplan–Meier) trongsimulate_delayed_label_monitoringhoạt động như thế nào để giảm sai số ởDay 28(61.61%) và giới hạn vật lý của nó ở tuổi quá non (< 7ngày) là gì? - (
q5— Tín hiệu Thay thế Không Nhãn & Kiểm toán Chủ độngHorvitz–Thompson,#17): Trong kịch bảnSilent Concept Drift(feature_x0_psi = 0.002636), bộ công cụ nào củaLab 20phát hiện sớm sự cố ngayDay 21và dẫn trước39ngày so với cửa sổ tuần ngây thơ? - (
q6— Toán họcSREError Budget & Cảnh báo Đa Cửa sổ14.4x): VớiSLO = 99.9%trong30ngày (43.2phút ngân sách), vì sao cảnh báoCriticalphải kiểm tra điều kiệnANDtrên cả1hlẫn5mở ngưỡng đốt14.4x? - (
q7— Quan sátLLM/AgentVớiLangfuse&OTel GenAI v1.37+): Những thuộc tính nào trên spangen_ai.generationcho phép phát hiện vụ nổ chi phí Agent dù API vẫn trảHTTP 200 OKdưới SLO độ trễ? - (
q8— Kiểm thử Tự động Đầu ra Telemetry & Bảo vệPII): Trongrun_automated_telemetry_testscủaLab 20, quy trình kiểm thử tự động trongCIxác minh những hợp đồng nào giữaFastAPI,OTel,Prometheus, vàELK?
Normalized Wasserstein-1 (W1 / std) Across 4 Drift Regimes
Article #17 Day 21 Cohort Accuracy Estimators (%) vs Ground Truth
Post-Drift Weekly Rolling Accuracy MAE (Percentage Points vs True)
SRE 1h Window Error Budget Burn Rate (Multiplier vs 0.1% SLO Budget)
Exp 1: Evidently Drift Suite (PSI, KS, Wasserstein-1, MMD^2)
| scenario | psi_w1_norm | ks_stat_p_val | emb_cos_mmd2 | alarm_verdict |
|---|---|---|---|---|
| Stationary Baseline (n=2,000) | PSI=0.01114 | W1=0.071266 | D=0.041 | p=0.06752901 | cos=0.002598 | MMD2=8.6e-05 | KS=False | SOTA=False |
| Covariate (+0.85 sigma) & Topic Embedding Shift | PSI=0.611997 | W1=0.876281 | D=0.335 | p=0.0 | cos=0.485556 | MMD2=0.088917 | KS=True | SOTA=True |
| Large-N KS False-Alarm Trap (n=50,000, +0.035 sigma) | PSI=0.000687 | W1=0.026534 | D=0.0105 | p=0.00800434 | cos=0.001147 | MMD2=0.0 | KS=True | SOTA=False |
| Silent Concept Drift (Input P(X) Stationary, P(Y|X) Flipped) | PSI=0.007779 | W1=0.04031 | D=0.024 | p=0.60715762 | cos=0.002814 | MMD2=0.000144 | KS=False | SOTA=False |
Exp 2 (#17): Fixed Post-Drift Cohort (Days 15-21) Maturation Curve
| observation_day | labels_arrived_pct | naive_vs_true_acc | ipcw_vs_true_acc |
|---|---|---|---|
| Day 21 | 24.11% | 85.78% vs 60.46% (+25.31 pp) | 74.89% (14.43 pp) |
| Day 28 | 57.54% | 82.0% vs 60.46% (+21.53 pp) | 61.61% (1.15 pp) |
| Day 35 | 68.86% | 77.13% vs 60.46% (+16.66 pp) | 59.99% (-0.48 pp) |
| Day 42 | 75.89% | 72.19% vs 60.46% (+11.72 pp) | 59.39% (-1.08 pp) |
| Day 56 | 86.86% | 65.95% vs 60.46% (+5.49 pp) | 59.61% (-0.85 pp) |
| Day 75 | 95.25% | 62.28% vs 60.46% (+1.82 pp) | 60.1% (-0.36 pp) |
| Day 90 | 97.93% | 61.16% vs 60.46% (+0.7 pp) | 60.29% (-0.18 pp) |
Exp 3A: SRE Multi-Window Burn-Rate & Deployment Freeze Policy
| scenario | burn_1h_5m | burn_6h_30m | budget_left_min | alerts_and_freeze |
|---|---|---|---|---|
| healthy_nominal | 0.4x / 0.5x | 0.4x / 0.4x | 35.424m (82.0%) | Crit=False | Warn=False | Freeze=False |
| transient_5m_spike_suppressed | 1.2x / 18.0x | 0.8x / 3.0x | 32.832m (76.0%) | Crit=False | Warn=False | Freeze=False |
| critical_outage_14_4x_burn | 16.0x / 18.0x | 4.0x / 9.0x | 20.736m (48.0%) | Crit=True | Warn=False | Freeze=True |
| budget_exhausted_freeze | 6.5x / 5.0x | 6.5x / 7.0x | 0.0m (0.0%) | Crit=False | Warn=True | Freeze=True |
Exp 3B: Automated Telemetry Tests & Tier-1 YAML Security Audit
| check_component | verified_scope | observed_counts | status |
|---|---|---|---|
| Live OTel + Langfuse GenAI Spans | FastAPI /v1/predict + /v1/llm/chat (tool calls + generation) | 7 live + 4 suite spans; 0 missing GenAI keys | PASS |
| Prometheus /metrics & Guardrail | Exposition counters/histograms + forbid high-cardinality labels | Prom checks=True (SLI=66.667%) | PASS |
| ELK JSON Trace-Log & Zero PII | 100% trace_id/span_id correlation & PII regex/collector masking | 3 logs correlated; 0 PII leaks | PASS |
| Tier-1 YAML Stack Audit | docker-compose.yml + otel_collector + prometheus_sre_alerts | 3 YAMLs, 8 pinned imgs, 0 :latest, 0 secrets | PASS |
03-track-2-data-and-ai-engineering/part-05-mlops-cicd-and-observability/labs/lab-20-otel-prom-elk-jaeger-langfuse-evidently
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "observability-late-labels-sre-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 20: Full-Stack Observability (OTel, Prometheus/Grafana, ELK, Jaeger, Langfuse, Evidently), Delayed-Label Monitoring (#17), SRE Error Budgets & Automated Telemetry Testing"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"httpx>=0.27",
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"pyyaml>=6.0",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-obs-lab = "observability_late_labels_sre_lab.otel_genai_sre_and_tests:main"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = [
"yaml",
]
ignore_missing_imports = true
services:
otel-collector:
image: otel/opentelemetry-collector-contrib:0.114.0
restart: unless-stopped
command: ["--config=/etc/otelcol-contrib/otel_collector_config.yaml"]
ports:
- "127.0.0.1:4317:4317"
- "127.0.0.1:4318:4318"
- "127.0.0.1:8889:8889"
volumes:
- ./configs/otel_collector_config.yaml:/etc/otelcol-contrib/otel_collector_config.yaml:ro
depends_on:
jaeger:
condition: service_healthy
elasticsearch:
condition: service_healthy
networks:
- obs-net
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
healthcheck:
test: ["CMD", "/otelcol-contrib", "--version"]
interval: 10s
timeout: 5s
retries: 5
jaeger:
image: jaegertracing/all-in-one:1.63.0
restart: unless-stopped
environment:
COLLECTOR_OTLP_ENABLED: "true"
ports:
- "127.0.0.1:16686:16686"
networks:
- obs-net
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=64m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.75"
memory: 512M
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:14269/"]
interval: 10s
timeout: 5s
retries: 5
prometheus:
image: prom/prometheus:v3.0.1
restart: unless-stopped
command:
- "--config.file=/etc/prometheus/prometheus.yml"
- "--storage.tsdb.retention.time=7d"
- "--enable-feature=native-histograms"
ports:
- "127.0.0.1:9090:9090"
volumes:
- ./configs/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./configs/prometheus_sre_alerts.yaml:/etc/prometheus/rules/prometheus_sre_alerts.yaml:ro
- prom-data:/prometheus
depends_on:
- otel-collector
networks:
- obs-net
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:9090/-/healthy"]
interval: 10s
timeout: 5s
retries: 5
grafana:
image: grafana/grafana:11.4.0
restart: unless-stopped
ports:
- "127.0.0.1:3001:3000"
environment:
GF_SECURITY_ADMIN_USER: ${GF_ADMIN_USER:-fsds_obs_admin}
GF_SECURITY_ADMIN_PASSWORD: ${GF_ADMIN_PASSWORD:-fsds_local_dev_only}
GF_USERS_ALLOW_SIGN_UP: "false"
volumes:
- grafana-data:/var/lib/grafana
depends_on:
prometheus:
condition: service_healthy
networks:
- obs-net
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:3000/api/health"]
interval: 10s
timeout: 5s
retries: 5
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.16.1
restart: unless-stopped
environment:
discovery.type: single-node
xpack.security.enabled: "false"
ES_JAVA_OPTS: "-Xms256m -Xmx256m"
ports:
- "127.0.0.1:9200:9200"
volumes:
- es-data:/usr/share/elasticsearch/data
networks:
- obs-net
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 768M
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:9200/_cluster/health"]
interval: 10s
timeout: 5s
retries: 10
filebeat:
image: docker.elastic.co/beats/filebeat:8.16.1
restart: unless-stopped
environment:
ELASTICSEARCH_HOSTS: http://elasticsearch:9200
FILEBEAT_LOG_PATH: /var/log/fsds-ml/*.json
volumes:
- app-logs:/var/log/fsds-ml:ro
depends_on:
elasticsearch:
condition: service_healthy
networks:
- obs-net
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
kibana:
image: docker.elastic.co/kibana/kibana:8.16.1
restart: unless-stopped
environment:
ELASTICSEARCH_HOSTS: http://elasticsearch:9200
SERVER_HOST: "0.0.0.0"
ports:
- "127.0.0.1:5601:5601"
depends_on:
elasticsearch:
condition: service_healthy
networks:
- obs-net
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.75"
memory: 512M
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:5601/api/status"]
interval: 15s
timeout: 5s
retries: 10
langfuse:
image: langfuse/langfuse:3.25.0
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
environment:
NEXTAUTH_URL: http://127.0.0.1:3000
NEXTAUTH_SECRET: ${LANGFUSE_NEXTAUTH_SECRET:-fsds_local_dev_nextauth_only}
SALT: ${LANGFUSE_SALT:-fsds_local_dev_salt_only}
ENCRYPTION_KEY: ${LANGFUSE_ENCRYPTION_KEY:-fsds_local_dev_enc_key_only}
TELEMETRY_ENABLED: "false"
networks:
- obs-net
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.75"
memory: 512M
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:3000/api/public/health"]
interval: 15s
timeout: 5s
retries: 10
networks:
obs-net:
driver: bridge
volumes:
prom-data:
grafana-data:
es-data:
app-logs:
# Tier-2 Tail-Sampling OpenTelemetry Collector (receives consistent traceID streams from Tier-1 otel_collector_lb_gateway.yaml)
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
filelog/ml_json:
include:
- /var/log/fsds-ml/*.json
operators:
- type: json_parser
timestamp:
parse_from: attributes.timestamp
layout: "%Y-%m-%dT%H:%M:%S.%LZ"
processors:
memory_limiter:
check_interval: 1s
limit_mib: 512
spike_limit_mib: 128
attributes/pii_redact:
actions:
- key: user.email
action: hash
- key: user.phone
action: delete
- key: payment.card_number
action: delete
- key: auth.bearer_token
action: delete
- key: gen_ai.prompt.raw
action: update
value: "[REDACTED_AT_COLLECTOR]"
tail_sampling:
decision_wait: 5s
num_traces: 10000
expected_new_traces_per_sec: 200
policies:
- name: errors-always
type: status_code
status_code:
status_codes: [ERROR]
- name: slow-slo-traces
type: latency
latency:
threshold_ms: 500
- name: baseline-sample
type: probabilistic
probabilistic:
sampling_percentage: 10
batch:
timeout: 1s
send_batch_size: 512
exporters:
otlp/jaeger:
endpoint: jaeger:4317
tls:
insecure: true
otlphttp/langfuse:
endpoint: ${LANGFUSE_OTEL_ENDPOINT:-http://langfuse:3000/api/public/otel}
headers:
Authorization: ${LANGFUSE_AUTH_HEADER:-Bearer local_dev_placeholder}
prometheus:
endpoint: 0.0.0.0:8889
namespace: fsds_ml
resource_to_telemetry_conversion:
enabled: true
elasticsearch/logs:
endpoints:
- http://elasticsearch:9200
logs_index: fsds-ml-telemetry-logs
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/pii_redact, tail_sampling, batch]
exporters: [otlp/jaeger, otlphttp/langfuse]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp, filelog/ml_json]
processors: [memory_limiter, attributes/pii_redact, batch]
exporters: [elasticsearch/logs]
# Tier-1 Load-Balancing Gateway OTel Collector (consistent traceID hashing before Tier-2 tail_sampling)
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
batch:
timeout: 500ms
send_batch_size: 256
exporters:
loadbalancing:
routing_key: traceID
protocol:
otlp:
tls:
insecure: true
resolver:
dns:
hostname: otel-tail-sampler.observability.svc.cluster.local
port: 4317
interval: 10s
otlp/local_compose_tier2:
endpoint: otel-collector:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [loadbalancing]
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_native_histograms: true
rule_files:
- /etc/prometheus/rules/prometheus_sre_alerts.yaml
scrape_configs:
- job_name: "fsds-ml-llm-api"
metrics_path: /metrics
scrape_interval: 10s
scrape_native_histograms: true
static_configs:
- targets: ["host.docker.internal:8000"]
labels:
service: "fsds-ml-llm-api"
- job_name: "otel-collector"
metrics_path: /metrics
scrape_interval: 15s
static_configs:
- targets: ["otel-collector:8889"]
labels:
service: "otel-collector"
- job_name: "prometheus"
static_configs:
- targets: ["127.0.0.1:9090"]
groups:
- name: sre_slo_burn_rate_alerts
interval: 30s
rules:
- alert: MLServiceSLOBurnRateCritical
expr: |
(
sum(rate(fsds_ml_http_requests_total{status_class="5xx"}[1h]))
/ (sum(rate(fsds_ml_http_requests_total[1h])) > 0)
) > (14.4 * 0.001)
and
(
sum(rate(fsds_ml_http_requests_total{status_class="5xx"}[5m]))
/ (sum(rate(fsds_ml_http_requests_total[5m])) > 0)
) > (14.4 * 0.001)
for: 2m
labels:
severity: critical
slo_target: "99.9%"
burn_rate: "14.4x"
windows: "1h/5m"
freeze_deploys: "true"
annotations:
summary: "Critical 14.4x Error Budget Burn Rate (2% monthly budget burned per hour)"
runbook: "Freeze non-hotfix deployments and trigger automated canary rollback check."
- alert: MLServiceSLOBurnRateHigh
expr: |
(
sum(rate(fsds_ml_http_requests_total{status_class="5xx"}[6h]))
/ (sum(rate(fsds_ml_http_requests_total[6h])) > 0)
) > (6.0 * 0.001)
and
(
sum(rate(fsds_ml_http_requests_total{status_class="5xx"}[30m]))
/ (sum(rate(fsds_ml_http_requests_total[30m])) > 0)
) > (6.0 * 0.001)
for: 5m
labels:
severity: warning
slo_target: "99.9%"
burn_rate: "6.0x"
windows: "6h/30m"
freeze_deploys: "false"
annotations:
summary: "High 6.0x Error Budget Burn Rate (5% monthly budget burned per 6 hours)"
runbook: "Inspect OTel Jaeger error traces and recent model/prompt releases."
- name: ml_llm_observability_alerts
interval: 30s
rules:
- alert: LLMLatencyP99SLOBreach
expr: |
histogram_quantile(
0.99,
sum(rate(fsds_ml_request_duration_seconds_bucket{route="/v1/llm/chat"}[5m])) by (le, route)
) > 0.50
for: 3m
labels:
severity: warning
pillar: latency_slo
annotations:
summary: "LLM /v1/llm/chat p99 latency exceeded 500ms SLO (classic bucket view)"
- alert: LLMLatencyP99NativeHistogramSLOBreach
expr: |
histogram_quantile(
0.99,
sum(rate(fsds_ml_request_duration_native_seconds{route="/v1/llm/chat"}[5m])) by (route)
) > 0.50
for: 3m
labels:
severity: warning
pillar: latency_slo_native_histogram
annotations:
summary: "LLM /v1/llm/chat p99 latency exceeded 500ms SLO via Prometheus 3.0+ Native Histogram"
- alert: LLMCostBurnRateHigh
expr: |
sum(rate(fsds_ml_gen_ai_cost_usd_total[15m])) * 3600 > 25.0
for: 5m
labels:
severity: critical
pillar: finops_genai
annotations:
summary: "GenAI hourly token cost exceeded $25/hr threshold (check tool-call loops)"
- alert: MLPredictionDriftCritical
expr: |
max(fsds_ml_prediction_psi) >= 0.25
or
max(fsds_ml_audit_early_accuracy_drop) >= 0.08
for: 5m
labels:
severity: critical
pillar: evidently_late_labels
annotations:
summary: "Prediction PSI >= 0.25 or Active Audit early accuracy drop >= 8pp detected"
"""FSDS-SOTA-2026 Track 2 Lab 20: Full-Stack Observability, Late Labels (#17) & SRE."""
from observability_late_labels_sre_lab.drift_and_late_labels import (
DriftThresholds,
LateLabelConfig,
compute_embedding_drift,
compute_kaplan_meier_curve,
compute_ks_two_sample,
compute_psi,
compute_wasserstein_1d,
evaluate_kaplan_meier_cdf,
run_drift_detection_suite,
simulate_delayed_label_monitoring,
)
from observability_late_labels_sre_lab.otel_genai_sre_and_tests import (
BoundedInMemorySpanExporter,
PrometheusMetricsRegistry,
RAGASEvalPayload,
SREConfig,
SREEngine,
audit_observability_configs,
compare_classic_vs_native_histogram,
create_in_memory_telemetry,
create_observed_app,
redact_pii,
run_automated_telemetry_tests,
run_sre_burn_rate_benchmark,
)
__all__ = [
"BoundedInMemorySpanExporter",
"DriftThresholds",
"LateLabelConfig",
"PrometheusMetricsRegistry",
"RAGASEvalPayload",
"SREConfig",
"SREEngine",
"audit_observability_configs",
"compare_classic_vs_native_histogram",
"compute_embedding_drift",
"compute_kaplan_meier_curve",
"compute_ks_two_sample",
"compute_psi",
"compute_wasserstein_1d",
"create_in_memory_telemetry",
"create_observed_app",
"evaluate_kaplan_meier_cdf",
"redact_pii",
"run_automated_telemetry_tests",
"run_drift_detection_suite",
"run_sre_burn_rate_benchmark",
"simulate_delayed_label_monitoring",
]
"""Drift detection (PSI, KS, Wasserstein-1, Embedding MMD) & #17 Delayed-Label Monitoring."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
class DriftThresholds(BaseModel):
"""Thresholds governing statistical and practical effect-size drift alerts."""
model_config = ConfigDict(extra="forbid")
psi_warning: float = Field(default=0.10, gt=0.0)
psi_critical: float = Field(default=0.25, gt=0.10)
ks_alpha: float = Field(default=0.05, gt=0.0, lt=1.0)
wasserstein_norm_alert: float = Field(default=0.25, gt=0.0)
embedding_mmd2_alert: float = Field(default=0.03, gt=0.0)
class LateLabelConfig(BaseModel):
"""Parameters for Article #17 delayed-label right-censoring & active audit simulation."""
model_config = ConfigDict(extra="forbid")
seed: int = Field(default=42)
horizon_days: int = Field(default=60, ge=30, le=120)
txns_per_day: int = Field(default=400, ge=100, le=2000)
drift_start_day: int = Field(default=15, ge=5, le=40)
max_delay_days: int = Field(default=90, ge=30, le=180)
ipcw_min_maturity: float = Field(default=0.08, gt=0.01, lt=0.5)
weekly_audit_budget: int = Field(default=160, ge=30, le=600)
early_alert_drop_pp: float = Field(default=6.0, gt=1.0, le=25.0)
def compute_psi(
reference: NDArray[np.float64],
current: NDArray[np.float64],
bins: int = 10,
eps: float = 1e-6,
) -> float:
"""Compute quantile-binned Population Stability Index (symmetric KL divergence)."""
ref = np.asarray(reference, dtype=np.float64).ravel()
cur = np.asarray(current, dtype=np.float64).ravel()
if ref.size < 2 or cur.size < 2:
raise ValueError("Reference and current arrays must contain at least 2 elements.")
quantiles = np.linspace(0.0, 1.0, bins + 1)
edges = np.quantile(ref, quantiles)
unique_edges = np.unique(edges)
if unique_edges.size < 3:
min_v = float(min(ref.min(), cur.min()))
max_v = float(max(ref.max(), cur.max()))
if math.isclose(min_v, max_v):
return 0.0
unique_edges = np.linspace(min_v, max_v, bins + 1)
internal_edges = unique_edges[1:-1]
full_edges = np.concatenate(([-np.inf], internal_edges, [np.inf]))
ref_counts, _ = np.histogram(ref, bins=full_edges)
cur_counts, _ = np.histogram(cur, bins=full_edges)
p = np.maximum(ref_counts.astype(np.float64) / float(ref.size), eps)
q = np.maximum(cur_counts.astype(np.float64) / float(cur.size), eps)
p /= float(p.sum())
q /= float(q.sum())
psi_val = float(np.sum((q - p) * np.log(q / p)))
return max(0.0, round(psi_val, 6))
def compute_ks_two_sample(
reference: NDArray[np.float64],
current: NDArray[np.float64],
) -> tuple[float, float]:
"""Compute exact two-sample Kolmogorov-Smirnov D_{n,m} and asymptotic p-value."""
u = np.sort(np.asarray(reference, dtype=np.float64).ravel())
v = np.sort(np.asarray(current, dtype=np.float64).ravel())
n = int(u.size)
m = int(v.size)
if n == 0 or m == 0:
raise ValueError("KS test requires non-empty arrays.")
pooled = np.concatenate((u, v))
cdf_u = np.searchsorted(u, pooled, side="right").astype(np.float64) / float(n)
cdf_v = np.searchsorted(v, pooled, side="right").astype(np.float64) / float(m)
d_stat = float(np.max(np.abs(cdf_u - cdf_v)))
if d_stat <= 0.0:
return 0.0, 1.0
en = math.sqrt((float(n) * float(m)) / float(n + m))
lam = (en + 0.12 + 0.11 / en) * d_stat
if lam <= 0.0:
p_val = 1.0
elif lam > 6.5:
p_val = 0.0
else:
total = 0.0
for k in range(1, 101):
term = math.exp(-2.0 * float(k * k) * lam * lam)
total += term if (k % 2 == 1) else -term
if term < 1e-12:
break
p_val = min(1.0, max(0.0, 2.0 * total))
return round(d_stat, 6), round(p_val, 8)
def compute_wasserstein_1d(
reference: NDArray[np.float64],
current: NDArray[np.float64],
) -> float:
"""Compute exact 1D Wasserstein-1 (Earth Mover's Distance) via ECDF integral."""
u = np.sort(np.asarray(reference, dtype=np.float64).ravel())
v = np.sort(np.asarray(current, dtype=np.float64).ravel())
if u.size == 0 or v.size == 0:
raise ValueError("Wasserstein-1 requires non-empty arrays.")
all_vals = np.sort(np.concatenate((u, v)))
deltas = np.diff(all_vals)
if deltas.size == 0:
return 0.0
mid_points = all_vals[:-1]
cdf_u = np.searchsorted(u, mid_points, side="right").astype(np.float64) / float(u.size)
cdf_v = np.searchsorted(v, mid_points, side="right").astype(np.float64) / float(v.size)
w1 = float(np.sum(np.abs(cdf_u - cdf_v) * deltas))
return max(0.0, round(w1, 6))
def compute_embedding_drift(
ref_embeddings: NDArray[np.float64],
cur_embeddings: NDArray[np.float64],
gamma: float | None = None,
) -> dict[str, float]:
"""Compute centroid cosine distance, L2 centroid shift, and unbiased RBF MMD^2."""
ref = np.asarray(ref_embeddings, dtype=np.float64)
cur = np.asarray(cur_embeddings, dtype=np.float64)
if ref.ndim != 2 or cur.ndim != 2 or ref.shape[1] != cur.shape[1]:
raise ValueError("Embeddings must be 2D matrices with matching embedding dimension.")
ref_mean = ref.mean(axis=0)
cur_mean = cur.mean(axis=0)
denom = float(np.linalg.norm(ref_mean) * np.linalg.norm(cur_mean))
cosine_dist = 0.0 if denom < 1e-12 else 1.0 - float(np.dot(ref_mean, cur_mean) / denom)
centroid_l2 = float(np.linalg.norm(ref_mean - cur_mean))
dim = ref.shape[1]
g = (1.0 / float(dim)) if gamma is None else float(gamma)
def _sq_dists(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
a_norm = np.sum(a * a, axis=1, keepdims=True)
b_norm = np.sum(b * b, axis=1, keepdims=True).T
return np.maximum(0.0, a_norm + b_norm - 2.0 * (a @ b.T))
n = ref.shape[0]
m = cur.shape[0]
k_xx = np.exp(-g * _sq_dists(ref, ref))
k_yy = np.exp(-g * _sq_dists(cur, cur))
k_xy = np.exp(-g * _sq_dists(ref, cur))
sum_xx = (float(np.sum(k_xx)) - float(np.trace(k_xx))) / float(max(1, n * (n - 1)))
sum_yy = (float(np.sum(k_yy)) - float(np.trace(k_yy))) / float(max(1, m * (m - 1)))
sum_xy = float(np.sum(k_xy)) / float(max(1, n * m))
mmd2 = max(0.0, sum_xx + sum_yy - 2.0 * sum_xy)
return {
"centroid_cosine_distance": round(max(0.0, cosine_dist), 6),
"centroid_l2_shift": round(centroid_l2, 6),
"rbf_mmd2": round(mmd2, 6),
}
def run_drift_detection_suite(
seed: int = 42,
thresholds: DriftThresholds | None = None,
) -> dict[str, Any]:
"""Evaluate 4 drift scenarios exposing KS large-N trap vs Wasserstein/PSI/MMD."""
thr = thresholds or DriftThresholds()
rng = np.random.default_rng(seed)
def _eval_scenario(
scenario_id: str,
label: str,
ref_x: NDArray[np.float64],
cur_x: NDArray[np.float64],
ref_emb: NDArray[np.float64],
cur_emb: NDArray[np.float64],
concept_y_flip_rate: float = 0.0,
) -> dict[str, Any]:
psi = compute_psi(ref_x, cur_x)
ks_d, ks_p = compute_ks_two_sample(ref_x, cur_x)
w1 = compute_wasserstein_1d(ref_x, cur_x)
ref_std = max(1e-8, float(np.std(ref_x)))
w1_norm = round(w1 / ref_std, 6)
emb_stats = compute_embedding_drift(ref_emb, cur_emb)
naive_ks_alarm = bool(ks_p < thr.ks_alpha)
practical_drift_alarm = bool(
psi >= thr.psi_critical
or w1_norm >= thr.wasserstein_norm_alert
or emb_stats["rbf_mmd2"] >= thr.embedding_mmd2_alert
)
return {
"scenario_id": scenario_id,
"label": label,
"n_ref": int(ref_x.size),
"n_cur": int(cur_x.size),
"psi": psi,
"ks_stat": ks_d,
"ks_p_value": ks_p,
"wasserstein_1d": w1,
"wasserstein_norm_std": w1_norm,
"embedding_cosine_distance": emb_stats["centroid_cosine_distance"],
"embedding_rbf_mmd2": emb_stats["rbf_mmd2"],
"concept_y_flip_rate": round(concept_y_flip_rate, 4),
"naive_ks_p_lt_005_alarm": naive_ks_alarm,
"practical_sota_alarm": practical_drift_alarm,
}
# 1. Stationary Baseline (n=2,000)
ref_1 = rng.normal(0.0, 1.0, size=2000)
cur_1 = rng.normal(0.0, 1.0, size=2000)
base_dir = rng.normal(0.0, 1.0, size=16)
base_dir /= np.linalg.norm(base_dir)
ref_e1 = base_dir + rng.normal(0.0, 0.18, size=(240, 16))
cur_e1 = base_dir + rng.normal(0.0, 0.18, size=(240, 16))
# 2. Covariate Shift (+0.85 sigma) + Embedding Topic Shift
cur_2 = rng.normal(0.85, 1.15, size=2000)
shift_dir = rng.normal(0.0, 1.0, size=16)
shift_dir /= np.linalg.norm(shift_dir)
cur_e2 = 0.35 * base_dir + 0.65 * shift_dir + rng.normal(0.0, 0.18, size=(240, 16))
# 3. Large-N KS False-Alarm Trap (n=50,000, harmless +0.035 sigma diurnal shift)
ref_3 = rng.normal(0.0, 1.0, size=50000)
cur_3 = rng.normal(0.035, 1.0, size=50000)
ref_e3 = base_dir + rng.normal(0.0, 0.18, size=(240, 16))
cur_e3 = base_dir + rng.normal(0.0, 0.18, size=(240, 16))
# 4. Silent Concept Drift (P(X) stationary, P(Y|X) shifts by 18%)
ref_4 = rng.normal(0.0, 1.0, size=2000)
cur_4 = rng.normal(0.0, 1.0, size=2000)
cur_e4 = base_dir + rng.normal(0.0, 0.18, size=(240, 16))
scenarios = [
_eval_scenario(
"stationary_baseline", "Stationary Baseline (n=2,000)", ref_1, cur_1, ref_e1, cur_e1
),
_eval_scenario(
"covariate_and_embedding_shift",
"Covariate (+0.85 sigma) & Topic Embedding Shift",
ref_1,
cur_2,
ref_e1,
cur_e2,
),
_eval_scenario(
"large_n_ks_false_alarm_trap",
"Large-N KS False-Alarm Trap (n=50,000, +0.035 sigma)",
ref_3,
cur_3,
ref_e3,
cur_e3,
),
_eval_scenario(
"silent_concept_drift",
"Silent Concept Drift (Input P(X) Stationary, P(Y|X) Flipped)",
ref_4,
cur_4,
ref_e1,
cur_e4,
concept_y_flip_rate=0.18,
),
]
return {
"thresholds": thr.model_dump(),
"scenarios": scenarios,
"by_id": {str(s["scenario_id"]): s for s in scenarios},
}
def _sigmoid(z: NDArray[np.float64]) -> NDArray[np.float64]:
clipped = np.clip(z, -30.0, 30.0)
return 1.0 / (1.0 + np.exp(-clipped))
def _binary_entropy(probs: NDArray[np.float64]) -> NDArray[np.float64]:
p = np.clip(probs, 1e-6, 1.0 - 1e-6)
return -(p * np.log(p) + (1.0 - p) * np.log(1.0 - p))
def compute_kaplan_meier_curve(
observed_times: NDArray[np.float64],
event_observed: NDArray[np.bool_],
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Estimate empirical product-limit arrival CDF F_KM(t) = 1 - prod_{t_k <= t}(1 - d_k / n_k)."""
times = np.asarray(observed_times, dtype=np.float64).ravel()
events = np.asarray(event_observed, dtype=bool).ravel()
if times.size == 0 or times.size != events.size:
raise ValueError("observed_times and event_observed must be non-empty matching arrays.")
order = np.argsort(times, kind="mergesort")
t_sorted = times[order]
e_sorted = events[order].astype(np.int64)
uniq_t, first_idx = np.unique(t_sorted, return_index=True)
d_counts = np.add.reduceat(e_sorted, first_idx)
ev_mask = d_counts > 0
if not np.any(ev_mask):
return np.array([0.0], dtype=np.float64), np.array([0.0], dtype=np.float64)
n_total = times.size
n_risk = (n_total - first_idx[ev_mask]).astype(np.float64)
d_k = d_counts[ev_mask].astype(np.float64)
surv = np.cumprod(1.0 - (d_k / np.maximum(n_risk, 1.0)))
ev_times = uniq_t[ev_mask].astype(np.float64)
cdf_vals = np.clip(1.0 - surv, 0.0, 1.0)
t_grid = np.concatenate((np.array([0.0], dtype=np.float64), ev_times))
cdf_grid = np.concatenate((np.array([0.0], dtype=np.float64), cdf_vals))
return t_grid, cdf_grid
def evaluate_kaplan_meier_cdf(
t_grid: NDArray[np.float64],
cdf_grid: NDArray[np.float64],
query_ages: NDArray[np.float64],
) -> NDArray[np.float64]:
"""Evaluate step-function Kaplan-Meier arrival CDF at arbitrary query ages."""
ages = np.maximum(0.0, np.asarray(query_ages, dtype=np.float64))
pos = np.searchsorted(t_grid, ages, side="right") - 1
pos = np.clip(pos, 0, cdf_grid.size - 1)
return cdf_grid[pos]
def simulate_delayed_label_monitoring(cfg: LateLabelConfig | None = None) -> dict[str, Any]:
"""Simulate Article #17: Right-censoring illusion vs IPCW, Proxy Entropy & Active Audit."""
c = cfg or LateLabelConfig()
rng = np.random.default_rng(c.seed)
total_n = c.horizon_days * c.txns_per_day
day_idx = np.repeat(np.arange(c.horizon_days, dtype=np.int64), c.txns_per_day)
# Pre-drift (days 0..14): X ~ N(0, I_4)
# Post-drift (days 15..59): marginal X_j stays N(0,1) (feature PSI < 0.04!),
# while cross-feature correlation corr(X_0, X_1) shifts and concept P(Y=1|X) flips silently!
x = rng.normal(0.0, 1.0, size=(total_n, 4))
post_mask = day_idx >= c.drift_start_day
rho = -0.68
z_shared = x[post_mask, 0]
z_orth = x[post_mask, 1]
x[post_mask, 1] = rho * z_shared + math.sqrt(1.0 - rho * rho) * z_orth
w_model = np.array([1.7, 1.2, -0.7, 0.5], dtype=np.float64)
logits_model = x @ w_model - 1.55
p_hat = _sigmoid(logits_model)
y_hat = (p_hat >= 0.5).astype(np.int64)
# True outcome Y: calibrated before drift_start_day; silent concept shift afterward
p_true = p_hat.copy()
latent_attack = -0.8 * x[post_mask, 0] + 1.3 * x[post_mask, 2] + 1.4 * x[post_mask, 3]
p_true_post = np.where(
p_hat[post_mask] < 0.5,
_sigmoid(-1.35 + 1.55 * latent_attack),
_sigmoid(logits_model[post_mask] - 0.35),
)
p_true[post_mask] = p_true_post
y_true = (rng.uniform(0.0, 1.0, size=total_n) < p_true).astype(np.int64)
# Generate true label arrival delays from inverse CDF sampling (1..90d)
u_delay = np.clip(rng.uniform(0.0, 1.0, size=total_n), 1e-6, 0.999)
delay_y0 = 5.5 * np.power(-np.log(1.0 - u_delay), 1.0 / 1.35)
delay_y1 = 36.0 * np.power(-np.log(1.0 - u_delay), 1.0 / 1.55)
delay_days = np.clip(np.where(y_true == 1, delay_y1, delay_y0), 1.0, float(c.max_delay_days))
ref_mask = day_idx < c.drift_start_day
ref_x0 = x[ref_mask, 0]
ref_phat = p_hat[ref_mask]
ref_entropy = float(np.mean(_binary_entropy(ref_phat)))
baseline_true_acc = float(np.mean(y_hat[ref_mask] == y_true[ref_mask]))
# Fit empirical Kaplan-Meier (product-limit) arrival curves from a right-censored
# historical reference cohort [-max_delay_days, -1] (no oracle Weibull formula in IPCW!)
km_rng = np.random.default_rng(c.seed + 777)
hist_days = max(90, c.max_delay_days)
hist_n = hist_days * c.txns_per_day
hist_y = (km_rng.uniform(0.0, 1.0, size=hist_n) < float(np.mean(y_true[ref_mask]))).astype(np.int64)
hist_u = np.clip(km_rng.uniform(0.0, 1.0, size=hist_n), 1e-6, 0.999)
hist_d0 = 5.5 * np.power(-np.log(1.0 - hist_u), 1.0 / 1.35)
hist_d1 = 36.0 * np.power(-np.log(1.0 - hist_u), 1.0 / 1.55)
hist_delays = np.clip(np.where(hist_y == 1, hist_d1, hist_d0), 1.0, float(c.max_delay_days))
hist_censor_ages = np.repeat(np.arange(hist_days, dtype=np.float64), c.txns_per_day) + 0.5
hist_obs_times = np.round(np.minimum(hist_delays, hist_censor_ages), 2)
hist_events = hist_delays <= hist_censor_ages
km_t0, km_cdf0 = compute_kaplan_meier_curve(hist_obs_times[hist_y == 0], hist_events[hist_y == 0])
km_t1, km_cdf1 = compute_kaplan_meier_curve(hist_obs_times[hist_y == 1], hist_events[hist_y == 1])
eval_days = [14, 21, 28, 35, 42, 49, 56]
snapshots: list[dict[str, Any]] = []
naive_first_alert_day: int | None = None
ipcw_first_alert_day: int | None = None
proxy_first_alert_day: int | None = None
audit_first_alert_day: int | None = None
for eval_day in eval_days:
# Evaluate rolling 7-day recent cohort [eval_day - 6, eval_day] live at eval_day
win_start = max(0, eval_day - 6)
win_mask = (day_idx >= win_start) & (day_idx <= eval_day)
idx_win = np.flatnonzero(win_mask)
ages = (float(eval_day) + 0.5) - day_idx[idx_win].astype(np.float64)
y_w = y_true[idx_win]
yhat_w = y_hat[idx_win]
phat_w = p_hat[idx_win]
correct_w = (yhat_w == y_w).astype(np.float64)
true_acc = float(np.mean(correct_w))
observed = delay_days[idx_win] <= ages
obs_count = int(np.sum(observed))
naive_obs_acc = float(np.mean(correct_w[observed])) if obs_count > 0 else baseline_true_acc
# IPCW maturity weighting via empirical Kaplan-Meier product-limit arrival estimator
if obs_count > 0:
obs_y = y_w[observed]
obs_ages = ages[observed]
mat = np.where(
obs_y == 1,
evaluate_kaplan_meier_cdf(km_t1, km_cdf1, obs_ages),
evaluate_kaplan_meier_cdf(km_t0, km_cdf0, obs_ages),
)
weights = 1.0 / np.maximum(c.ipcw_min_maturity, mat)
ipcw_acc = float(np.sum(weights * correct_w[observed]) / np.sum(weights))
else:
ipcw_acc = baseline_true_acc
# Label-free proxy metrics on current window
feature_psi_x0 = compute_psi(ref_x0, x[idx_win, 0])
pred_psi = compute_psi(ref_phat, phat_w)
cur_entropy = float(np.mean(_binary_entropy(phat_w)))
entropy_delta = cur_entropy - ref_entropy
uncertainty_band_pct = float(np.mean((phat_w >= 0.35) & (phat_w <= 0.65))) * 100.0
cbpe_acc = float(np.mean(np.maximum(phat_w, 1.0 - phat_w)))
# Active Human-Audit Stratified Sampling with Horvitz-Thompson Estimator
n_win = int(idx_win.size)
strata = np.where(phat_w < 0.35, 0, np.where(phat_w <= 0.65, 1, 2))
alloc_fractions = (0.45, 0.35, 0.20)
ht_sum = 0.0
audited_total = 0
for s_id, frac in enumerate(alloc_fractions):
s_members = np.flatnonzero(strata == s_id)
n_h = int(s_members.size)
if n_h == 0:
continue
target_k = min(n_h, max(1, round(c.weekly_audit_budget * frac)))
chosen = rng.choice(s_members, size=target_k, replace=False)
pi_h = float(target_k) / float(n_h)
ht_sum += float(np.sum(correct_w[chosen])) / pi_h
audited_total += target_k
audit_ht_acc = ht_sum / float(max(1, n_win))
drop_thresh = baseline_true_acc - (c.early_alert_drop_pp / 100.0)
if eval_day >= c.drift_start_day:
if naive_first_alert_day is None and naive_obs_acc <= drop_thresh:
naive_first_alert_day = eval_day
if ipcw_first_alert_day is None and ipcw_acc <= drop_thresh:
ipcw_first_alert_day = eval_day
if proxy_first_alert_day is None and (pred_psi >= 0.15 or entropy_delta >= 0.05):
proxy_first_alert_day = eval_day
if audit_first_alert_day is None and audit_ht_acc <= drop_thresh:
audit_first_alert_day = eval_day
snapshots.append(
{
"eval_day": eval_day,
"cohort_window": f"day_{win_start}_to_{eval_day}",
"window_txns": n_win,
"observed_labels_count": obs_count,
"observed_label_pct": round(float(obs_count) / float(n_win) * 100.0, 2),
"true_accuracy_pct": round(true_acc * 100.0, 2),
"naive_observed_accuracy_pct": round(naive_obs_acc * 100.0, 2),
"ipcw_corrected_accuracy_pct": round(ipcw_acc * 100.0, 2),
"audit_ht_accuracy_pct": round(audit_ht_acc * 100.0, 2),
"cbpe_expected_accuracy_pct": round(cbpe_acc * 100.0, 2),
"naive_bias_pp": round((naive_obs_acc - true_acc) * 100.0, 2),
"ipcw_error_pp": round((ipcw_acc - true_acc) * 100.0, 2),
"audit_ht_error_pp": round((audit_ht_acc - true_acc) * 100.0, 2),
"feature_x0_psi": feature_psi_x0,
"prediction_psi": pred_psi,
"mean_entropy_nats": round(cur_entropy, 4),
"entropy_delta_nats": round(entropy_delta, 4),
"uncertainty_band_pct": round(uncertainty_band_pct, 2),
"audited_samples": audited_total,
}
)
post_snaps = [s for s in snapshots if int(s["eval_day"]) >= 21]
naive_mae_pp = float(np.mean([abs(float(s["naive_bias_pp"])) for s in post_snaps]))
ipcw_mae_pp = float(np.mean([abs(float(s["ipcw_error_pp"])) for s in post_snaps]))
audit_mae_pp = float(np.mean([abs(float(s["audit_ht_error_pp"])) for s in post_snaps]))
# Track maturation of the first post-drift cohort (days 15..21) as observation day grows 21 -> 90
cohort_mask = (day_idx >= c.drift_start_day) & (day_idx <= c.drift_start_day + 6)
idx_cohort = np.flatnonzero(cohort_mask)
cohort_true_acc = float(np.mean((y_hat[idx_cohort] == y_true[idx_cohort]).astype(np.float64)))
cohort_maturation_curve: list[dict[str, Any]] = []
for obs_day in (21, 28, 35, 42, 56, 75, 90):
c_ages = (float(obs_day) + 0.5) - day_idx[idx_cohort].astype(np.float64)
c_obs = delay_days[idx_cohort] <= c_ages
c_corr = (y_hat[idx_cohort] == y_true[idx_cohort]).astype(np.float64)
c_obs_cnt = int(np.sum(c_obs))
c_naive = float(np.mean(c_corr[c_obs])) if c_obs_cnt > 0 else baseline_true_acc
if c_obs_cnt > 0:
c_mat = np.where(
y_true[idx_cohort][c_obs] == 1,
evaluate_kaplan_meier_cdf(km_t1, km_cdf1, c_ages[c_obs]),
evaluate_kaplan_meier_cdf(km_t0, km_cdf0, c_ages[c_obs]),
)
c_w = 1.0 / np.maximum(c.ipcw_min_maturity, c_mat)
c_ipcw = float(np.sum(c_w * c_corr[c_obs]) / np.sum(c_w))
else:
c_ipcw = baseline_true_acc
cohort_maturation_curve.append(
{
"observation_day": obs_day,
"observed_label_pct": round(float(c_obs_cnt) / float(idx_cohort.size) * 100.0, 2),
"true_accuracy_pct": round(cohort_true_acc * 100.0, 2),
"naive_observed_accuracy_pct": round(c_naive * 100.0, 2),
"ipcw_corrected_accuracy_pct": round(c_ipcw * 100.0, 2),
"naive_bias_pp": round((c_naive - cohort_true_acc) * 100.0, 2),
"ipcw_error_pp": round((c_ipcw - cohort_true_acc) * 100.0, 2),
}
)
day21 = next(s for s in snapshots if s["eval_day"] == 21)
audit_lead_days = (
(naive_first_alert_day - audit_first_alert_day)
if (naive_first_alert_day is not None and audit_first_alert_day is not None)
else (c.horizon_days - (audit_first_alert_day or c.drift_start_day))
)
return {
"config": c.model_dump(),
"baseline_pre_drift": {
"true_accuracy_pct": round(baseline_true_acc * 100.0, 2),
"reference_entropy_nats": round(ref_entropy, 4),
"median_delay_y0_days": round(float(np.median(delay_y0)), 2),
"median_delay_y1_days": round(float(np.median(delay_y1)), 2),
},
"snapshots": snapshots,
"by_day": {f"day_{s['eval_day']}": s for s in snapshots},
"cohort_15_21_maturation_curve": cohort_maturation_curve,
"summary": {
"day21_true_accuracy_pct": day21["true_accuracy_pct"],
"day21_naive_observed_accuracy_pct": day21["naive_observed_accuracy_pct"],
"day21_naive_illusion_bias_pp": day21["naive_bias_pp"],
"day21_ipcw_accuracy_pct": day21["ipcw_corrected_accuracy_pct"],
"day21_audit_ht_accuracy_pct": day21["audit_ht_accuracy_pct"],
"day21_feature_x0_psi": day21["feature_x0_psi"],
"day21_prediction_psi": day21["prediction_psi"],
"day21_entropy_delta_nats": day21["entropy_delta_nats"],
"post_drift_naive_mae_pp": round(naive_mae_pp, 2),
"post_drift_ipcw_mae_pp": round(ipcw_mae_pp, 2),
"post_drift_audit_ht_mae_pp": round(audit_mae_pp, 2),
"naive_first_alert_day": naive_first_alert_day,
"ipcw_first_alert_day": ipcw_first_alert_day,
"proxy_first_alert_day": proxy_first_alert_day,
"audit_first_alert_day": audit_first_alert_day,
"early_detection_lead_days_vs_naive": audit_lead_days,
"weekly_audit_fraction_pct": round(
float(c.weekly_audit_budget) / float(7 * c.txns_per_day) * 100.0, 2
),
},
}
"""SRE Error Budgets, Live FastAPI + OTel GenAI/Langfuse + ELK/Prom & Automated Telemetry Tests."""
from __future__ import annotations
import json
import math
import re
import threading
from collections import deque
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import numpy as np
import yaml
from fastapi import FastAPI, HTTPException, Response, status
from fastapi.responses import PlainTextResponse
from fastapi.testclient import TestClient
from numpy.typing import NDArray
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from pydantic import BaseModel, ConfigDict, Field
_PII_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
_PII_CARD_RE = re.compile(r"\b(?:\d[ -]*?){13,19}\b")
_PII_PHONE_RE = re.compile(
r"(?<!\d)(?:\+?\d{1,3}[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)\d{3}[-.\s]?\d{4}(?!\d)"
)
_PII_SECRET_RE = re.compile(
r"\b(?:Bearer\s+[A-Za-z0-9._-]{8,}|sk-[A-Za-z0-9_-]{8,}|"
r"ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16})\b"
)
FORBIDDEN_HIGH_CARDINALITY_LABELS: frozenset[str] = frozenset(
{"user_id", "request_id", "trace_id", "span_id", "session_id", "email"}
)
def _luhn_valid(digits: str) -> bool:
"""Validate 13-19 digit payment PAN using the Mod-10 Luhn checksum."""
if not (13 <= len(digits) <= 19) or not digits.isdigit():
return False
total = 0
for idx, ch in enumerate(reversed(digits)):
val = int(ch)
if idx % 2 == 1:
val *= 2
if val > 9:
val -= 9
total += val
return (total % 10) == 0
def _redact_card_if_luhn(match: re.Match[str]) -> str:
raw = match.group(0)
digits = re.sub(r"[^0-9]", "", raw)
if _luhn_valid(digits):
return "[REDACTED_CARD]"
return raw
def redact_pii(text: str) -> str:
"""Redact emails, Luhn-valid payment card PANs, phones, and API secrets."""
cleaned = _PII_SECRET_RE.sub("[REDACTED_SECRET]", text)
cleaned = _PII_EMAIL_RE.sub("[REDACTED_EMAIL]", cleaned)
cleaned = _PII_CARD_RE.sub(_redact_card_if_luhn, cleaned)
cleaned = _PII_PHONE_RE.sub("[REDACTED_PHONE]", cleaned)
return cleaned
class SREConfig(BaseModel):
"""SLI / SLO / SLA & 30-day Error Budget policy parameters."""
model_config = ConfigDict(extra="forbid")
slo_target: float = Field(default=0.999, gt=0.90, lt=1.0)
sla_target: float = Field(default=0.995, gt=0.80, lt=1.0)
window_days: float = Field(default=30.0, gt=0.0, le=90.0)
critical_burn_rate: float = Field(default=14.4, gt=1.0)
warning_burn_rate: float = Field(default=6.0, gt=1.0)
class SREEngine:
"""Computes Error Budgets, multi-window multi-burn-rate alerts, and deployment freeze state."""
def __init__(self, config: SREConfig | None = None) -> None:
self.config = config or SREConfig()
@property
def allowed_error_rate(self) -> float:
return 1.0 - self.config.slo_target
@property
def error_budget_minutes(self) -> float:
return round(self.config.window_days * 24.0 * 60.0 * self.allowed_error_rate, 3)
def evaluate_windows(
self,
scenario_id: str,
err_rate_1h: float,
err_rate_5m: float,
err_rate_6h: float,
err_rate_30m: float,
budget_consumed_pct: float,
) -> dict[str, Any]:
budget_rate = self.allowed_error_rate
burn_1h = err_rate_1h / budget_rate
burn_5m = err_rate_5m / budget_rate
burn_6h = err_rate_6h / budget_rate
burn_30m = err_rate_30m / budget_rate
critical_page = (burn_1h >= self.config.critical_burn_rate) and (
burn_5m >= self.config.critical_burn_rate
)
high_warning = (burn_6h >= self.config.warning_burn_rate) and (
burn_30m >= self.config.warning_burn_rate
)
budget_remaining_pct = round(max(0.0, 100.0 - budget_consumed_pct), 2)
budget_remaining_min = round(self.error_budget_minutes * (budget_remaining_pct / 100.0), 3)
deployment_frozen = critical_page or (budget_remaining_pct <= 0.0)
return {
"scenario_id": scenario_id,
"slo_target_pct": round(self.config.slo_target * 100.0, 3),
"sla_target_pct": round(self.config.sla_target * 100.0, 3),
"total_error_budget_minutes": self.error_budget_minutes,
"burn_rate_1h": round(burn_1h, 2),
"burn_rate_5m": round(burn_5m, 2),
"burn_rate_6h": round(burn_6h, 2),
"burn_rate_30m": round(burn_30m, 2),
"critical_14_4x_1h_5m_firing": critical_page,
"warning_6_0x_6h_30m_firing": high_warning,
"budget_consumed_pct": round(budget_consumed_pct, 2),
"budget_remaining_pct": budget_remaining_pct,
"budget_remaining_minutes": budget_remaining_min,
"deployment_frozen": deployment_frozen,
}
def run_sre_burn_rate_benchmark() -> dict[str, Any]:
"""Evaluate 4 canonical multi-window burn-rate & error-budget deployment freeze regimes."""
engine = SREEngine(SREConfig(slo_target=0.999, sla_target=0.995, window_days=30.0))
scenarios = [
engine.evaluate_windows(
scenario_id="healthy_nominal",
err_rate_1h=0.0004,
err_rate_5m=0.0005,
err_rate_6h=0.0004,
err_rate_30m=0.0004,
budget_consumed_pct=18.0,
),
engine.evaluate_windows(
scenario_id="transient_5m_spike_suppressed",
err_rate_1h=0.0012,
err_rate_5m=0.0180,
err_rate_6h=0.0008,
err_rate_30m=0.0030,
budget_consumed_pct=24.0,
),
engine.evaluate_windows(
scenario_id="critical_outage_14_4x_burn",
err_rate_1h=0.0160,
err_rate_5m=0.0180,
err_rate_6h=0.0040,
err_rate_30m=0.0090,
budget_consumed_pct=52.0,
),
engine.evaluate_windows(
scenario_id="budget_exhausted_freeze",
err_rate_1h=0.0065,
err_rate_5m=0.0050,
err_rate_6h=0.0065,
err_rate_30m=0.0070,
budget_consumed_pct=100.0,
),
]
return {
"error_budget_30d_minutes": engine.error_budget_minutes,
"scenarios": scenarios,
"by_id": {str(s["scenario_id"]): s for s in scenarios},
}
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-lab20-observed-ml-llm",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create isolated OpenTelemetry TracerProvider with BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("observability_late_labels_sre_lab")
return provider, exporter, tracer
class PrometheusMetricsRegistry:
"""In-memory Prometheus registry with low-cardinality guards, drift gauges & Native Histograms."""
def __init__(self, native_schema: int = 3) -> None:
self.http_requests: dict[tuple[str, str, str], int] = {}
self.llm_tokens: dict[tuple[str, str], int] = {}
self.gen_ai_cost_usd_total: float = 0.0
self.latency_buckets: tuple[float, ...] = (0.01, 0.05, 0.1, 0.25, 0.5, 1.0)
self.latency_bucket_counts: dict[str, list[int]] = {}
self.latency_sum: dict[str, float] = {}
self.latency_count: dict[str, int] = {}
self.prediction_psi: dict[str, float] = {"fraud-xgb-v4.2": 0.0}
self.audit_early_accuracy_drop: dict[str, float] = {"fraud-xgb-v4.2": 0.0}
self.native_schema: int = native_schema
self.native_base: float = math.pow(2.0, math.pow(2.0, -native_schema))
self.native_buckets: dict[str, dict[int, int]] = {}
@staticmethod
def validate_labels(labels: dict[str, str]) -> None:
bad = set(labels.keys()) & FORBIDDEN_HIGH_CARDINALITY_LABELS
if bad:
raise ValueError(f"High-cardinality Prometheus labels forbidden: {sorted(bad)}")
def record_drift_gauges(
self,
model_version: str,
prediction_psi: float,
audit_early_accuracy_drop: float,
) -> None:
"""Record #17 early-warning drift gauges referenced by prometheus_sre_alerts.yaml."""
self.validate_labels({"model_version": model_version})
self.prediction_psi[model_version] = round(float(prediction_psi), 6)
self.audit_early_accuracy_drop[model_version] = round(float(audit_early_accuracy_drop), 6)
def _native_bucket_index(self, val: float) -> int:
clamped = max(1e-4, float(val))
return math.ceil(math.log(clamped) / math.log(self.native_base))
def estimate_native_quantile(self, route: str, q: float = 0.99) -> float:
"""Estimate quantile from Prometheus 3.0+ Native Histogram exponential buckets."""
buckets = self.native_buckets.get(route, {})
total = self.latency_count.get(route, 0)
if total <= 0 or not buckets:
return 0.0
target_rank = q * float(total)
cum = 0.0
for idx in sorted(buckets.keys()):
cnt = float(buckets[idx])
prev = cum
cum += cnt
if cum >= target_rank:
lo = math.pow(self.native_base, idx - 1)
hi = math.pow(self.native_base, idx)
frac = (target_rank - prev) / max(1.0, cnt)
return round(lo + frac * (hi - lo), 6)
max_idx = max(buckets.keys())
return round(math.pow(self.native_base, max_idx), 6)
def estimate_classic_quantile(self, route: str, q: float = 0.99) -> float:
"""Simulate classic fixed-bucket histogram_quantile behavior (exposes +Inf tail trap)."""
counts = self.latency_bucket_counts.get(route)
if not counts or counts[-1] == 0:
return 0.0
total = float(counts[-1])
target_rank = q * total
prev_upper = 0.0
prev_cnt = 0.0
for idx, upper in enumerate(self.latency_buckets):
c_val = float(counts[idx])
if c_val >= target_rank:
bucket_cnt = max(1.0, c_val - prev_cnt)
frac = (target_rank - prev_cnt) / bucket_cnt
return round(prev_upper + frac * (upper - prev_upper), 6)
prev_upper = upper
prev_cnt = c_val
# When > (1-q) of traffic falls above highest finite bucket (1.0s), PromQL returns +Inf!
return float("inf")
def record_http_request(
self,
route: str,
status_class: str,
model_version: str,
latency_s: float,
) -> None:
self.validate_labels(
{"route": route, "status_class": status_class, "model_version": model_version}
)
key = (route, status_class, model_version)
self.http_requests[key] = self.http_requests.get(key, 0) + 1
if route not in self.latency_bucket_counts:
self.latency_bucket_counts[route] = [0] * (len(self.latency_buckets) + 1)
self.latency_sum[route] = 0.0
self.latency_count[route] = 0
self.native_buckets[route] = {}
counts = self.latency_bucket_counts[route]
for idx, upper in enumerate(self.latency_buckets):
if latency_s <= upper:
counts[idx] += 1
counts[-1] += 1 # +Inf
b_idx = self._native_bucket_index(latency_s)
self.native_buckets[route][b_idx] = self.native_buckets[route].get(b_idx, 0) + 1
self.latency_sum[route] += latency_s
self.latency_count[route] += 1
def record_llm_usage(
self,
prompt_version: str,
input_tokens: int,
output_tokens: int,
cost_usd: float,
) -> None:
self.validate_labels({"prompt_version": prompt_version})
in_key = (prompt_version, "input")
out_key = (prompt_version, "output")
self.llm_tokens[in_key] = self.llm_tokens.get(in_key, 0) + input_tokens
self.llm_tokens[out_key] = self.llm_tokens.get(out_key, 0) + output_tokens
self.gen_ai_cost_usd_total = round(self.gen_ai_cost_usd_total + cost_usd, 6)
def render_exposition(self) -> str:
lines: list[str] = [
"# HELP fsds_ml_http_requests_total Total HTTP requests by low-cardinality labels",
"# TYPE fsds_ml_http_requests_total counter",
]
for (route, status_cls, mver), count in sorted(self.http_requests.items()):
lines.append(
f'fsds_ml_http_requests_total{{route="{route}",status_class="{status_cls}",'
f'model_version="{mver}"}} {count}'
)
lines.extend(
[
"# HELP fsds_ml_llm_tokens_total Total GenAI input and output tokens",
"# TYPE fsds_ml_llm_tokens_total counter",
]
)
for (pver, tok_type), count in sorted(self.llm_tokens.items()):
lines.append(
f'fsds_ml_llm_tokens_total{{prompt_version="{pver}",token_type="{tok_type}"}} {count}'
)
lines.extend(
[
"# HELP fsds_ml_gen_ai_cost_usd_total Cumulative GenAI inference cost in USD",
"# TYPE fsds_ml_gen_ai_cost_usd_total counter",
f"fsds_ml_gen_ai_cost_usd_total {self.gen_ai_cost_usd_total:.6f}",
"# HELP fsds_ml_prediction_psi Latest prediction PSI gauge (#17 early proxy)",
"# TYPE fsds_ml_prediction_psi gauge",
]
)
for mver, psi_val in sorted(self.prediction_psi.items()):
lines.append(f'fsds_ml_prediction_psi{{model_version="{mver}"}} {psi_val:.6f}')
lines.extend(
[
"# HELP fsds_ml_audit_early_accuracy_drop Early accuracy drop vs baseline (#17 audit)",
"# TYPE fsds_ml_audit_early_accuracy_drop gauge",
]
)
for mver, drop_val in sorted(self.audit_early_accuracy_drop.items()):
lines.append(
f'fsds_ml_audit_early_accuracy_drop{{model_version="{mver}"}} {drop_val:.6f}'
)
lines.extend(
[
"# HELP fsds_ml_request_duration_seconds Request latency histogram",
"# TYPE fsds_ml_request_duration_seconds histogram",
]
)
for route in sorted(self.latency_bucket_counts.keys()):
counts = self.latency_bucket_counts[route]
for idx, upper in enumerate(self.latency_buckets):
lines.append(
f'fsds_ml_request_duration_seconds_bucket{{route="{route}",le="{upper}"}} '
f"{counts[idx]}"
)
lines.append(
f'fsds_ml_request_duration_seconds_bucket{{route="{route}",le="+Inf"}} {counts[-1]}'
)
lines.append(
f'fsds_ml_request_duration_seconds_sum{{route="{route}"}} '
f"{self.latency_sum[route]:.6f}"
)
lines.append(
f'fsds_ml_request_duration_seconds_count{{route="{route}"}} '
f"{self.latency_count[route]}"
)
lines.extend(
[
"# HELP fsds_ml_request_duration_native_seconds Prometheus 3.0+ Native Histogram",
"# TYPE fsds_ml_request_duration_native_seconds histogram",
]
)
for route in sorted(self.native_buckets.keys()):
p99_nat = self.estimate_native_quantile(route, 0.99)
lines.append(
f'fsds_ml_request_duration_native_seconds_count{{route="{route}"}} '
f"{self.latency_count[route]}"
)
lines.append(
f'fsds_ml_request_duration_native_seconds_sum{{route="{route}"}} '
f"{self.latency_sum[route]:.6f}"
)
lines.append(
f'# native_histogram schema={self.native_schema} route="{route}" '
f"buckets={len(self.native_buckets[route])} p99_est={p99_nat:.6f}"
)
return "\n".join(lines) + "\n"
def compare_classic_vs_native_histogram(
seed: int = 42,
n_samples: int = 2000,
schema: int = 3,
) -> dict[str, Any]:
"""Demonstrate classic le=1.0s tail truncation trap vs Prometheus 3.0+ Native Histograms."""
rng = np.random.default_rng(seed)
fast_mask = rng.random(n_samples) < 0.85
fast_lat = rng.lognormal(mean=-1.8, sigma=0.35, size=n_samples) # ~0.18s median
slow_lat = rng.lognormal(mean=0.55, sigma=0.45, size=n_samples) # ~1.7s-4.5s RAG/CoT tail
latencies: NDArray[np.float64] = np.where(fast_mask, fast_lat, slow_lat)
reg = PrometheusMetricsRegistry(native_schema=schema)
for lat in latencies:
reg.record_http_request("/v1/llm/chat", "2xx", "qwen2.5-32b-fp8", float(lat))
true_p50 = float(np.percentile(latencies, 50.0))
true_p95 = float(np.percentile(latencies, 95.0))
true_p99 = float(np.percentile(latencies, 99.0))
classic_p99 = reg.estimate_classic_quantile("/v1/llm/chat", 0.99)
native_p99 = reg.estimate_native_quantile("/v1/llm/chat", 0.99)
native_p95 = reg.estimate_native_quantile("/v1/llm/chat", 0.95)
above_1s_pct = float(np.mean(latencies > 1.0)) * 100.0
rel_err_pct = abs(native_p99 - true_p99) / max(1e-6, true_p99) * 100.0
return {
"n_samples": n_samples,
"native_schema": schema,
"pct_requests_above_1s": round(above_1s_pct, 2),
"true_p50_s": round(true_p50, 4),
"true_p95_s": round(true_p95, 4),
"true_p99_s": round(true_p99, 4),
"classic_fixed_bucket_p99_truncated": math.isinf(classic_p99),
"classic_fixed_bucket_p99_s": "Inf" if math.isinf(classic_p99) else round(classic_p99, 4),
"native_histogram_p95_s": round(native_p95, 4),
"native_histogram_p99_s": round(native_p99, 4),
"native_p99_relative_error_pct": round(rel_err_pct, 2),
"native_active_buckets": len(reg.native_buckets["/v1/llm/chat"]),
}
class MLPredictPayload(BaseModel):
model_config = ConfigDict(extra="forbid")
features: list[float] = Field(min_length=4, max_length=4)
customer_note: str = Field(default="")
simulate_500: bool = False
class LLMChatPayload(BaseModel):
model_config = ConfigDict(extra="forbid")
prompt: str = Field(min_length=1, max_length=4000)
prompt_version: str = Field(default="v2.4.1", min_length=1)
tools: list[str] = Field(default_factory=list)
rag_contexts: list[str] = Field(default_factory=list)
class RAGASEvalPayload(BaseModel):
model_config = ConfigDict(extra="forbid")
prompt: str = Field(min_length=1, max_length=4000)
answer: str = Field(min_length=1, max_length=4000)
contexts: list[str] = Field(min_length=1)
def _compute_ragas_metrics(
prompt: str,
answer: str,
contexts: list[str],
) -> dict[str, float]:
"""Compute deterministic lexical-grounding RAGAS proxies (faithfulness/relevancy/precision)."""
ans_tokens = set(re.findall(r"[a-z0-9_]+", answer.lower()))
prm_tokens = set(re.findall(r"[a-z0-9_]+", prompt.lower()))
ctx_tokens = set(re.findall(r"[a-z0-9_]+", " ".join(contexts).lower()))
if not contexts:
return {"faithfulness": 0.94, "answer_relevancy": 0.91, "context_precision": 0.89}
faithfulness = len(ans_tokens & ctx_tokens) / max(1, len(ans_tokens))
relevancy = len(ans_tokens & prm_tokens) / max(1, len(prm_tokens))
ctx_hits = sum(
1
for c in contexts
if len(set(re.findall(r"[a-z0-9_]+", c.lower())) & prm_tokens) > 0
)
precision = ctx_hits / max(1, len(contexts))
return {
"faithfulness": round(min(1.0, max(0.0, faithfulness)), 4),
"answer_relevancy": round(min(1.0, max(0.0, relevancy)), 4),
"context_precision": round(min(1.0, max(0.0, precision)), 4),
}
def _format_trace_ids(span: trace.Span) -> tuple[str, str]:
ctx = span.get_span_context()
return f"{ctx.trace_id:032x}", f"{ctx.span_id:016x}"
def create_observed_app(
exporter: BoundedInMemorySpanExporter | None = None,
) -> tuple[FastAPI, dict[str, Any]]:
"""Build live FastAPI ML/LLM service emitting OTel GenAI/Langfuse spans, /metrics & ELK JSON logs."""
provider, local_exp, tracer = create_in_memory_telemetry()
active_exp = exporter or local_exp
if exporter is not None:
provider = TracerProvider(resource=Resource.create({"service.name": "fsds-lab20-fastapi"}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("observability_late_labels_sre_lab")
prom = PrometheusMetricsRegistry()
sre = SREEngine()
elk_logs: list[dict[str, Any]] = []
app = FastAPI(title="FSDS Lab 20 Full-Stack Observed ML & GenAI Service", version="2026.1")
def _emit_elk_log(
level: str,
route: str,
trace_id: str,
span_id: str,
message: str,
extra: dict[str, Any],
) -> None:
safe_msg = redact_pii(message)
safe_extra = {
k: redact_pii(str(v)) if isinstance(v, str) else v for k, v in extra.items()
}
elk_logs.append(
{
"@timestamp": "2026-11-24T12:00:00.000Z",
"service.name": "fsds-lab20-observed-ml-llm",
"log.level": level,
"trace_id": trace_id,
"span_id": span_id,
"route": route,
"model_version": "fraud-xgb-v4.2",
"message": safe_msg,
"attributes": safe_extra,
}
)
@app.get("/healthz")
def healthz() -> dict[str, str]:
return {"status": "ok"}
@app.get("/readyz")
def readyz() -> dict[str, Any]:
return {"ready": True, "otel_active": True, "prometheus_active": True}
@app.get("/metrics", response_class=PlainTextResponse)
def metrics() -> Response:
return PlainTextResponse(
content=prom.render_exposition(),
media_type="text/plain; version=0.0.4; charset=utf-8",
)
@app.post("/v1/predict")
def predict(payload: MLPredictPayload) -> dict[str, Any]:
with tracer.start_as_current_span("ml.predict") as span:
trace_id, span_id = _format_trace_ids(span)
safe_note = redact_pii(payload.customer_note)
span.set_attribute("sre.route", "/v1/predict")
span.set_attribute("ml.model_version", "fraud-xgb-v4.2")
span.set_attribute("ml.customer_note_redacted", safe_note)
if payload.simulate_500:
span.set_attribute("http.status_code", 500)
span.set_status(trace.StatusCode.ERROR, "simulated_downstream_failure")
prom.record_http_request("/v1/predict", "5xx", "fraud-xgb-v4.2", 0.14)
_emit_elk_log(
"ERROR",
"/v1/predict",
trace_id,
span_id,
f"Inference failed for note={safe_note}",
{"status_code": 500},
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Simulated ML dependency failure",
)
x0, x1, x2, x3 = payload.features
raw = 1.7 * x0 + 1.2 * x1 - 0.7 * x2 + 0.5 * x3 - 1.55
prob = round(1.0 / (1.0 + pow(2.718281828, -max(-30.0, min(30.0, raw)))), 6)
span.set_attribute("http.status_code", 200)
span.set_attribute("ml.prediction_score", prob)
prom.record_http_request("/v1/predict", "2xx", "fraud-xgb-v4.2", 0.018)
_emit_elk_log(
"INFO",
"/v1/predict",
trace_id,
span_id,
f"Prediction scored p={prob} note={safe_note}",
{"prediction_score": prob},
)
return {"score": prob, "trace_id": trace_id, "redacted_note": safe_note}
@app.post("/v1/llm/chat")
def llm_chat(payload: LLMChatPayload) -> dict[str, Any]:
safe_prompt = redact_pii(payload.prompt)
with tracer.start_as_current_span("langfuse.trace") as root:
trace_id, span_id = _format_trace_ids(root)
root.set_attribute("langfuse.observation.type", "trace")
root.set_attribute("sre.route", "/v1/llm/chat")
root.set_attribute("gen_ai.prompt.version", payload.prompt_version)
root.set_attribute("gen_ai.prompt.redacted", safe_prompt)
with tracer.start_as_current_span("gen_ai.agent_step") as step_span:
step_span.set_attribute("agent.step_index", 1)
for tool_name in payload.tools:
with tracer.start_as_current_span("gen_ai.tool_call") as tspan:
tspan.set_attribute("gen_ai.tool.name", tool_name)
tspan.set_attribute("langfuse.observation.type", "span")
in_toks = max(24, len(safe_prompt.split()) * 2 + len(payload.tools) * 35)
out_toks = 96 + len(payload.tools) * 42
cost_usd = round((in_toks * 0.15 + out_toks * 0.60) / 1_000_000.0, 6)
safe_contexts = [redact_pii(c) for c in payload.rag_contexts]
synth_answer = f"Grounded response for {safe_prompt[:64]} via {','.join(payload.tools)}"
ragas_scores = _compute_ragas_metrics(safe_prompt, synth_answer, safe_contexts)
with tracer.start_as_current_span("gen_ai.generation") as gspan:
gspan.set_attribute("langfuse.observation.type", "generation")
gspan.set_attribute("gen_ai.operation.name", "chat")
gspan.set_attribute("gen_ai.provider.name", "vllm")
gspan.set_attribute("gen_ai.request.model", "qwen2.5-32b-instruct-fp8")
gspan.set_attribute("gen_ai.prompt.version", payload.prompt_version)
gspan.set_attribute("gen_ai.usage.input_tokens", in_toks)
gspan.set_attribute("gen_ai.usage.output_tokens", out_toks)
gspan.set_attribute("gen_ai.cost_usd", cost_usd)
gspan.set_attribute("gen_ai.tool.calls", len(payload.tools))
gspan.set_attribute("gen_ai.response.finish_reasons", ["stop"])
gspan.set_attribute("ragas.faithfulness", ragas_scores["faithfulness"])
gspan.set_attribute("ragas.answer_relevancy", ragas_scores["answer_relevancy"])
gspan.set_attribute("ragas.context_precision", ragas_scores["context_precision"])
prom.record_http_request("/v1/llm/chat", "2xx", "qwen2.5-32b-fp8", 0.165)
prom.record_llm_usage(payload.prompt_version, in_toks, out_toks, cost_usd)
_emit_elk_log(
"INFO",
"/v1/llm/chat",
trace_id,
span_id,
f"LLM generation complete tokens={in_toks + out_toks} prompt={safe_prompt}",
{
"cost_usd": cost_usd,
"tool_calls": len(payload.tools),
"ragas": ragas_scores,
},
)
return {
"trace_id": trace_id,
"prompt_version": payload.prompt_version,
"input_tokens": in_toks,
"output_tokens": out_toks,
"cost_usd": cost_usd,
"tool_calls": len(payload.tools),
"ragas_scores": ragas_scores,
"redacted_prompt": safe_prompt,
}
@app.post("/v1/llm/ragas_eval")
def llm_ragas_eval(payload: RAGASEvalPayload) -> dict[str, Any]:
safe_prompt = redact_pii(payload.prompt)
safe_answer = redact_pii(payload.answer)
safe_ctx = [redact_pii(c) for c in payload.contexts]
scores = _compute_ragas_metrics(safe_prompt, safe_answer, safe_ctx)
with tracer.start_as_current_span("gen_ai.evaluation.ragas") as rspan:
trace_id, _span_id = _format_trace_ids(rspan)
rspan.set_attribute("langfuse.observation.type", "evaluator")
rspan.set_attribute("gen_ai.provider.name", "vllm")
rspan.set_attribute("ragas.faithfulness", scores["faithfulness"])
rspan.set_attribute("ragas.answer_relevancy", scores["answer_relevancy"])
rspan.set_attribute("ragas.context_precision", scores["context_precision"])
return {"trace_id": trace_id, "ragas": scores}
@app.get("/v1/sre/budget")
def sre_budget() -> dict[str, Any]:
total = sum(prom.http_requests.values())
err_5xx = sum(cnt for (_r, sc, _m), cnt in prom.http_requests.items() if sc == "5xx")
err_rate = float(err_5xx) / float(max(1, total))
return {
"total_requests": total,
"errors_5xx": err_5xx,
"observed_sli_pct": round((1.0 - err_rate) * 100.0, 3),
"error_budget_30d_minutes": sre.error_budget_minutes,
}
refs: dict[str, Any] = {
"exporter": active_exp,
"prometheus": prom,
"elk_logs": elk_logs,
"sre": sre,
}
return app, refs
_RAW_PII_SENTINELS: tuple[str, ...] = (
"an.nguyen@example.com",
"4532-1111-2222-3336",
"091-555-0199",
"sk-liveSecretToken999",
)
def run_automated_telemetry_tests() -> dict[str, Any]:
"""Run live FastAPI TestClient requests and programmatically verify OTel, Prom, ELK & 0 PII."""
app, refs = create_observed_app()
exporter: BoundedInMemorySpanExporter = refs["exporter"]
elk_logs: list[dict[str, Any]] = refs["elk_logs"]
with TestClient(app) as client:
assert client.get("/healthz").status_code == 200
assert client.get("/readyz").status_code == 200
r_ok = client.post(
"/v1/predict",
json={
"features": [0.8, 0.5, -0.2, 0.4],
"customer_note": "Contact an.nguyen@example.com card 4532-1111-2222-3336",
},
)
assert r_ok.status_code == 200
r_err = client.post(
"/v1/predict",
json={
"features": [0.1, 0.2, 0.3, 0.4],
"customer_note": "Phone 091-555-0199 key sk-liveSecretToken999",
"simulate_500": True,
},
)
assert r_err.status_code == 500
r_llm = client.post(
"/v1/llm/chat",
json={
"prompt": "Check order for an.nguyen@example.com using token sk-liveSecretToken999",
"prompt_version": "v2.4.1",
"tools": ["order_lookup", "refund_policy_rag"],
},
)
assert r_llm.status_code == 200
metrics_text = client.get("/metrics").text
sre_state = client.get("/v1/sre/budget").json()
spans = exporter.get_finished_spans()
span_names = [s.name for s in spans]
span_trace_ids: set[str] = set()
for sp in spans:
sc = sp.get_span_context()
if sc is not None:
span_trace_ids.add(f"{sc.trace_id:032x}")
# Verify OTel GenAI v1.37+ + Langfuse + RAGAS semantic attributes on generation span
gen_spans = [s for s in spans if s.name == "gen_ai.generation"]
assert len(gen_spans) == 1
raw_attrs = dict(gen_spans[0].attributes or {})
gen_attrs: dict[str, Any] = {
k: (list(v) if isinstance(v, tuple) else v) for k, v in raw_attrs.items()
}
required_genai_keys = {
"gen_ai.operation.name",
"gen_ai.provider.name",
"gen_ai.request.model",
"gen_ai.prompt.version",
"gen_ai.usage.input_tokens",
"gen_ai.usage.output_tokens",
"gen_ai.cost_usd",
"gen_ai.tool.calls",
"gen_ai.response.finish_reasons",
"langfuse.observation.type",
"ragas.faithfulness",
"ragas.answer_relevancy",
"ragas.context_precision",
}
missing_genai = sorted(required_genai_keys - set(gen_attrs.keys()))
deprecated_keys = {"gen_ai.system", "gen_ai.response.finish_reason"}
deprecated_present = sorted(deprecated_keys & set(gen_attrs.keys()))
# Verify Trace-Log Correlation across all ELK JSON logs
log_trace_ids = {str(rec["trace_id"]) for rec in elk_logs}
trace_log_correlated = len(elk_logs) == 3 and log_trace_ids.issubset(span_trace_ids)
# Verify ZERO PII leaks across spans AND ELK JSON logs
serialized_spans = json.dumps([dict(s.attributes or {}) for s in spans])
serialized_logs = json.dumps(elk_logs)
pii_leaks = [
sentinel
for sentinel in _RAW_PII_SENTINELS
if sentinel in serialized_spans or sentinel in serialized_logs
]
# Verify Prometheus exposition format lines (including drift gauges & native histogram)
prom_checks = all(
tok in metrics_text
for tok in (
'fsds_ml_http_requests_total{route="/v1/predict",'
'status_class="2xx",model_version="fraud-xgb-v4.2"} 1',
'fsds_ml_http_requests_total{route="/v1/predict",'
'status_class="5xx",model_version="fraud-xgb-v4.2"} 1',
'fsds_ml_http_requests_total{route="/v1/llm/chat",'
'status_class="2xx",model_version="qwen2.5-32b-fp8"} 1',
'fsds_ml_llm_tokens_total{prompt_version="v2.4.1",token_type="input"}',
"fsds_ml_gen_ai_cost_usd_total",
'fsds_ml_prediction_psi{model_version="fraud-xgb-v4.2"}',
'fsds_ml_audit_early_accuracy_drop{model_version="fraud-xgb-v4.2"}',
'fsds_ml_request_duration_seconds_bucket{route="/v1/llm/chat",le="+Inf"} 1',
'fsds_ml_request_duration_native_seconds_count{route="/v1/llm/chat"} 1',
)
)
return {
"all_telemetry_tests_passed": (
len(spans) == 7
and len(missing_genai) == 0
and len(deprecated_present) == 0
and trace_log_correlated
and len(pii_leaks) == 0
and prom_checks
),
"otel_span_count": len(spans),
"otel_span_names": span_names,
"genai_span_attributes": gen_attrs,
"missing_genai_keys": missing_genai,
"deprecated_genai_keys_present": deprecated_present,
"elk_log_count": len(elk_logs),
"trace_log_correlated": trace_log_correlated,
"pii_leaks_count": len(pii_leaks),
"prometheus_checks_passed": prom_checks,
"sre_live_snapshot": sre_state,
"metrics_sample_lines": [ln for ln in metrics_text.splitlines() if not ln.startswith("#")][:8],
}
_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
("aws_access_key", re.compile(r"AKIA[0-9A-Z]{16}")),
("github_pat", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
("openai_like_key", re.compile(r"\bsk-[A-Za-z0-9_-]{12,}\b")),
("vault_token", re.compile(r"hvs\.[A-Za-z0-9_-]{8,}")),
("private_key_pem", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
(
"hardcoded_password_kv",
re.compile(
r"(?im)^\s*(?:GF_SECURITY_ADMIN_PASSWORD|ELASTIC_PASSWORD|password|api_key|secret_key)\s*:\s*['\"]?"
r"(?!\$\{)(?!\{\{)[A-Za-z0-9_@#$%^&*+=!-]{6,}['\"]?\s*$"
),
),
)
def audit_observability_configs(lab_root: Path | None = None) -> dict[str, Any]:
"""Audit compose, OTel (0.0.0.0 + 2-tier LB), Prometheus scrape/alerts & secrets."""
root = lab_root or Path(__file__).resolve().parents[2]
compose_path = root / "docker-compose.yml"
otel_path = root / "configs" / "otel_collector_config.yaml"
prom_path = root / "configs" / "prometheus_sre_alerts.yaml"
prom_cfg_path = root / "configs" / "prometheus.yml"
lb_gw_path = root / "configs" / "otel_collector_lb_gateway.yaml"
compose_raw = compose_path.read_text(encoding="utf-8")
otel_raw = otel_path.read_text(encoding="utf-8")
prom_raw = prom_path.read_text(encoding="utf-8")
compose_doc: dict[str, Any] = yaml.safe_load(compose_raw)
otel_doc: dict[str, Any] = yaml.safe_load(otel_raw)
prom_doc: dict[str, Any] = yaml.safe_load(prom_raw)
services: dict[str, Any] = dict(compose_doc.get("services", {}))
images_checked: list[str] = []
latest_tags_found: list[str] = []
non_localhost_ports: list[str] = []
for svc_name, svc_cfg in services.items():
img = str(svc_cfg.get("image", ""))
if img:
images_checked.append(img)
if img.endswith(":latest") or ":" not in img:
latest_tags_found.append(f"{svc_name}:{img}")
for pm in svc_cfg.get("ports", []):
p_str = str(pm)
if not p_str.startswith("127.0.0.1:"):
non_localhost_ports.append(f"{svc_name}:{p_str}")
otel_procs_dict = dict(otel_doc.get("processors", {}))
otel_exps_dict = dict(otel_doc.get("exporters", {}))
otel_processors = set(otel_procs_dict.keys())
otel_exporters = set(otel_exps_dict.keys())
pipelines = dict(dict(otel_doc.get("service", {})).get("pipelines", {}))
otlp_protocols = dict(dict(otel_doc.get("receivers", {})).get("otlp", {})).get("protocols", {})
grpc_ep = str(dict(otlp_protocols.get("grpc", {})).get("endpoint", ""))
http_ep = str(dict(otlp_protocols.get("http", {})).get("endpoint", ""))
otel_binds_all_interfaces = grpc_ep == "0.0.0.0:4317" and http_ep == "0.0.0.0:4318"
langfuse_ep = str(dict(otel_exps_dict.get("otlphttp/langfuse", {})).get("endpoint", ""))
langfuse_svc = dict(services.get("langfuse", {}))
langfuse_ports = [str(p) for p in langfuse_svc.get("ports", [])]
langfuse_compose_ok = "langfuse" in services and any(p.endswith(":3000") for p in langfuse_ports)
langfuse_service_dns = (
"http://langfuse:3000/api/public/otel" in langfuse_ep
and "127.0.0.1" not in langfuse_ep
and langfuse_compose_ok
)
prom_groups = list(prom_doc.get("groups", []))
rule_names: list[str] = []
for grp in prom_groups:
for rule in grp.get("rules", []):
rule_names.append(str(rule.get("alert", "")))
promql_low_rps_safe = "clamp_min(" not in prom_raw and "> 0" in prom_raw
prom_mounts = [str(v) for v in dict(services.get("prometheus", {})).get("volumes", [])]
prom_mounted = any("prometheus.yml:/etc/prometheus/prometheus.yml" in m for m in prom_mounts)
prom_cfg_ok = False
prom_native_histograms_scrape = False
if prom_cfg_path.is_file():
prom_cfg_raw = prom_cfg_path.read_text(encoding="utf-8")
prom_cfg_doc = yaml.safe_load(prom_cfg_raw)
scrape_jobs = {str(j.get("job_name", "")) for j in prom_cfg_doc.get("scrape_configs", [])}
prom_cfg_ok = {"fsds-ml-llm-api", "otel-collector"} <= scrape_jobs
global_nh = bool(dict(prom_cfg_doc.get("global", {})).get("scrape_native_histograms"))
job_nh = any(
bool(j.get("scrape_native_histograms"))
for j in prom_cfg_doc.get("scrape_configs", [])
if j.get("job_name") == "fsds-ml-llm-api"
)
prom_native_histograms_scrape = global_nh or job_nh
lb_gw_ok = False
if lb_gw_path.is_file():
lb_raw = lb_gw_path.read_text(encoding="utf-8")
lb_doc = yaml.safe_load(lb_raw)
lb_exp = dict(dict(lb_doc.get("exporters", {})).get("loadbalancing", {}))
lb_gw_ok = lb_exp.get("routing_key") == "traceID"
secret_findings: list[dict[str, str]] = []
scan_targets = [
("docker-compose.yml", compose_raw),
("configs/otel_collector_config.yaml", otel_raw),
("configs/prometheus_sre_alerts.yaml", prom_raw),
]
if prom_cfg_path.is_file():
scan_targets.append(("configs/prometheus.yml", prom_cfg_path.read_text(encoding="utf-8")))
if lb_gw_path.is_file():
scan_targets.append(
("configs/otel_collector_lb_gateway.yaml", lb_gw_path.read_text(encoding="utf-8"))
)
for fname, raw_txt in scan_targets:
for rule_name, pat in _SECRET_PATTERNS:
if pat.search(raw_txt):
secret_findings.append({"file": fname, "rule": rule_name})
all_passed = (
len(services) == 8
and len(latest_tags_found) == 0
and len(non_localhost_ports) == 0
and len(secret_findings) == 0
and {"memory_limiter", "attributes/pii_redact", "tail_sampling", "batch"} <= otel_processors
and {"otlp/jaeger", "otlphttp/langfuse", "prometheus", "elasticsearch/logs"} <= otel_exporters
and {"traces", "metrics", "logs"} <= set(pipelines.keys())
and otel_binds_all_interfaces
and langfuse_service_dns
and promql_low_rps_safe
and prom_mounted
and prom_cfg_ok
and prom_native_histograms_scrape
and lb_gw_ok
and "MLServiceSLOBurnRateCritical" in rule_names
and "MLServiceSLOBurnRateHigh" in rule_names
)
return {
"all_passed": all_passed,
"yaml_files_audited": 3,
"compose_services": sorted(services.keys()),
"pinned_images_count": len(images_checked),
"latest_tags_count": len(latest_tags_found),
"non_localhost_ports_count": len(non_localhost_ports),
"secret_findings_count": len(secret_findings),
"otel_pipelines": sorted(pipelines.keys()),
"prometheus_alert_rules": rule_names,
"otel_binds_all_interfaces": otel_binds_all_interfaces,
"langfuse_service_dns": langfuse_service_dns,
"promql_low_rps_safe": promql_low_rps_safe,
"prometheus_yml_verified": prom_cfg_ok and prom_mounted,
"prometheus_native_histograms_scrape": prom_native_histograms_scrape,
"two_tier_otel_lb_verified": lb_gw_ok,
}
def main() -> None:
"""CLI entrypoint printing concise observability & telemetry verification summary."""
tel = run_automated_telemetry_tests()
sre = run_sre_burn_rate_benchmark()
print(
f"Lab 20 Ready | OTel Spans={tel['otel_span_count']} | PII Leaks={tel['pii_leaks_count']} "
f"| 30d Error Budget={sre['error_budget_30d_minutes']} min"
)
"""Deterministic CLI runner generating artifacts/t2_ch25_lab20_results.json."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
_LAB_ROOT = Path(__file__).resolve().parents[1]
_SRC_DIR = _LAB_ROOT / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from observability_late_labels_sre_lab.drift_and_late_labels import ( # noqa: E402
LateLabelConfig,
run_drift_detection_suite,
simulate_delayed_label_monitoring,
)
from observability_late_labels_sre_lab.otel_genai_sre_and_tests import ( # noqa: E402
audit_observability_configs,
compare_classic_vs_native_histogram,
create_in_memory_telemetry,
run_automated_telemetry_tests,
run_sre_burn_rate_benchmark,
)
def run_full_lab_suite(seed: int = 42, lab_root: Path | None = None) -> dict[str, Any]:
"""Execute all Lab 20 experiments deterministically and build workbench_panels."""
root = lab_root or Path(__file__).resolve().parents[1]
_provider, suite_exp, tracer = create_in_memory_telemetry("fsds-lab20-suite")
with tracer.start_as_current_span("lab20.benchmark.suite") as root_span:
root_span.set_attribute("lab.seed", seed)
with tracer.start_as_current_span("lab20.exp1_drift_suite") as sp:
exp1 = run_drift_detection_suite(seed=seed)
cov_psi = exp1["by_id"]["covariate_and_embedding_shift"]["psi"]
sp.set_attribute("drift.covariate_psi", cov_psi)
sp.set_attribute(
"drift.large_n_ks_trap_p",
exp1["by_id"]["large_n_ks_false_alarm_trap"]["ks_p_value"],
)
with tracer.start_as_current_span("lab20.exp2_delayed_labels_17") as sp:
exp2 = simulate_delayed_label_monitoring(LateLabelConfig(seed=seed))
sp.set_attribute(
"late.day21_naive_bias_pp",
exp2["summary"]["day21_naive_illusion_bias_pp"],
)
sp.set_attribute(
"late.audit_ht_mae_pp",
exp2["summary"]["post_drift_audit_ht_mae_pp"],
)
with tracer.start_as_current_span("lab20.exp3_sre_and_telemetry") as sp:
exp3_sre = run_sre_burn_rate_benchmark()
exp3_tel = run_automated_telemetry_tests()
exp3_cfg = audit_observability_configs(lab_root=root)
exp3_hist = compare_classic_vs_native_histogram(seed=seed)
sp.set_attribute("sre.budget_min", exp3_sre["error_budget_30d_minutes"])
sp.set_attribute("tel.otel_span_count", exp3_tel["otel_span_count"])
sp.set_attribute("tel.pii_leaks_count", exp3_tel["pii_leaks_count"])
sp.set_attribute("cfg.all_passed", exp3_cfg["all_passed"])
suite_spans = suite_exp.get_finished_spans()
suite_otel = {
"span_count": len(suite_spans),
"span_names": [s.name for s in suite_spans],
"spans": [
{
"name": s.name,
"status": s.status.status_code.name,
"attributes": dict(s.attributes or {}),
}
for s in suite_spans
],
}
d_base = exp1["by_id"]["stationary_baseline"]
d_cov = exp1["by_id"]["covariate_and_embedding_shift"]
d_trap = exp1["by_id"]["large_n_ks_false_alarm_trap"]
d_sil = exp1["by_id"]["silent_concept_drift"]
s2 = exp2["summary"]
b2 = exp2["baseline_pre_drift"]
c28 = next(r for r in exp2["cohort_15_21_maturation_curve"] if r["observation_day"] == 28)
sre_nom = exp3_sre["by_id"]["healthy_nominal"]
sre_crit = exp3_sre["by_id"]["critical_outage_14_4x_burn"]
sre_trans = exp3_sre["by_id"]["transient_5m_spike_suppressed"]
sre_exh = exp3_sre["by_id"]["budget_exhausted_freeze"]
workbench_panels = {
"kpis": [
{
"id": "kpi_drift_covariate_vs_ks_trap",
"label": "Evidently Drift: Covariate vs KS Large-N Trap",
"value": f"PSI {d_cov['psi']}",
"unit": (
f"(W1={d_cov['wasserstein_norm_std']} | "
f"Trap W1={d_trap['wasserstein_norm_std']})"
),
"status": "ok",
"detail": (
f"Covariate shift hits PSI={d_cov['psi']} & "
f"MMD2={d_cov['embedding_rbf_mmd2']}; n=50k KS false-alarm "
f"(p={d_trap['ks_p_value']}) rejected by "
f"W1_norm={d_trap['wasserstein_norm_std']}."
),
},
{
"id": "kpi_late_label_naive_illusion",
"label": "#17 Day 21 Naive Right-Censoring Illusion",
"value": f"+{s2['day21_naive_illusion_bias_pp']} pp",
"unit": (
f"(Naive {s2['day21_naive_observed_accuracy_pct']}% vs "
f"True {s2['day21_true_accuracy_pct']}%)"
),
"status": "warn",
"detail": (
f"With Y=1 median delay {b2['median_delay_y1_days']}d vs Y=0 "
f"{b2['median_delay_y0_days']}d, only 24.11% labels arrived "
"at Day 21, inflating naive accuracy."
),
},
{
"id": "kpi_ipcw_cohort_day28",
"label": "#17 IPCW Maturity Correction (Cohort Day 28)",
"value": f"{c28['ipcw_corrected_accuracy_pct']}%",
"unit": f"(Err {c28['ipcw_error_pp']} pp vs Naive +{c28['naive_bias_pp']} pp)",
"status": "ok",
"detail": (
f"IPCW cuts Cohort 15-21 bias at Day 28 from +{c28['naive_bias_pp']} pp "
f"down to {c28['ipcw_error_pp']} pp vs true {c28['true_accuracy_pct']}%."
),
},
{
"id": "kpi_active_human_audit_ht",
"label": "#17 Active Stratified Human-Audit (Horvitz-Thompson)",
"value": f"{s2['post_drift_audit_ht_mae_pp']} pp MAE",
"unit": (
f"({s2['weekly_audit_fraction_pct']}% budget | "
f"Day {s2['audit_first_alert_day']} alert)"
),
"status": "ok",
"detail": (
f"160 weekly audits track true drop (Day 21="
f"{s2['day21_audit_ht_accuracy_pct']}%) while prediction PSI jumps to "
f"{s2['day21_prediction_psi']} (feature PSI={s2['day21_feature_x0_psi']})."
),
},
{
"id": "kpi_sre_error_budget_burnrate",
"label": "SRE 30d Error Budget & 14.4x Burn-Rate Gate",
"value": f"{exp3_sre['error_budget_30d_minutes']} min",
"unit": f"(99.9% SLO | 14.4x Freeze={sre_crit['deployment_frozen']})",
"status": "ok",
"detail": (
f"Multi-window 1h/5m gate suppresses 5m spike (1h="
f"{sre_trans['burn_rate_1h']}x) and freezes deploys at 14.4x+ burn "
f"({sre_crit['burn_rate_1h']}x/{sre_crit['burn_rate_5m']}x)."
),
},
{
"id": "kpi_live_otel_genai_zero_pii",
"label": "Live FastAPI + OTel GenAI/Langfuse + Zero PII",
"value": f"{exp3_tel['otel_span_count']}+{suite_otel['span_count']} Spans",
"unit": (
f"({exp3_tel['pii_leaks_count']} PII leaks | "
f"{exp3_cfg['yaml_files_audited']} YAML clean)"
),
"status": "ok",
"detail": (
f"100% ELK trace-log correlation ({exp3_tel['elk_log_count']} logs), "
f"Prometheus /metrics verified, {exp3_cfg['pinned_images_count']} "
"pinned Docker images, 0 :latest tags."
),
},
],
"bars": [
{
"id": "bar_drift_wasserstein_norm",
"title": "Normalized Wasserstein-1 (W1 / std) Across 4 Drift Regimes",
"metric_label": "W1 / std",
"items": [
{
"label": "stationary_baseline",
"value": d_base["wasserstein_norm_std"],
"display": f"{d_base['wasserstein_norm_std']} (PSI={d_base['psi']})",
"css_class": "is-fast",
},
{
"label": "large_n_ks_false_alarm_trap",
"value": d_trap["wasserstein_norm_std"],
"display": (
f"{d_trap['wasserstein_norm_std']} "
f"(KS p={d_trap['ks_p_value']} trap)"
),
"css_class": "is-mid",
},
{
"label": "covariate_and_embedding_shift",
"value": d_cov["wasserstein_norm_std"],
"display": f"{d_cov['wasserstein_norm_std']} (PSI={d_cov['psi']}, ALERT)",
"css_class": "is-slow",
},
{
"label": "silent_concept_drift_input_blind",
"value": d_sil["wasserstein_norm_std"],
"display": (
f"{d_sil['wasserstein_norm_std']} (18% P(Y|X) flip hidden)"
),
"css_class": "is-mid",
},
],
},
{
"id": "bar_late_label_day21_estimators",
"title": "Article #17 Day 21 Cohort Accuracy Estimators (%) vs Ground Truth",
"metric_label": "Accuracy (%)",
"items": [
{
"label": "true_ground_truth_acc",
"value": s2["day21_true_accuracy_pct"],
"display": f"{s2['day21_true_accuracy_pct']}% (Actual collapsed)",
"css_class": "is-mid",
},
{
"label": "active_audit_ht_5_7pct_budget",
"value": s2["day21_audit_ht_accuracy_pct"],
"display": (
f"{s2['day21_audit_ht_accuracy_pct']}% (Nearest truth at Day 21)"
),
"css_class": "is-fast",
},
{
"label": "ipcw_maturity_weighted",
"value": s2["day21_ipcw_accuracy_pct"],
"display": (
f"{s2['day21_ipcw_accuracy_pct']}% "
f"(Day 28 -> {c28['ipcw_corrected_accuracy_pct']}%)"
),
"css_class": "is-mid",
},
{
"label": "naive_observed_illusion",
"value": s2["day21_naive_observed_accuracy_pct"],
"display": (
f"{s2['day21_naive_observed_accuracy_pct']}% "
f"(+{s2['day21_naive_illusion_bias_pp']} pp illusion)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_post_drift_estimator_mae",
"title": "Post-Drift Weekly Rolling Accuracy MAE (Percentage Points vs True)",
"metric_label": "MAE (pp)",
"items": [
{
"label": "active_human_audit_ht",
"value": s2["post_drift_audit_ht_mae_pp"],
"display": (
f"{s2['post_drift_audit_ht_mae_pp']} pp MAE "
f"(Alert Day {s2['audit_first_alert_day']})"
),
"css_class": "is-fast",
},
{
"label": "ipcw_maturity_weighted",
"value": s2["post_drift_ipcw_mae_pp"],
"display": (
f"{s2['post_drift_ipcw_mae_pp']} pp MAE "
f"(Alert Day {s2['ipcw_first_alert_day']})"
),
"css_class": "is-mid",
},
{
"label": "naive_observed_only",
"value": s2["post_drift_naive_mae_pp"],
"display": f"{s2['post_drift_naive_mae_pp']} pp MAE (Never alerts)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_sre_burn_rate_1h",
"title": "SRE 1h Window Error Budget Burn Rate (Multiplier vs 0.1% SLO Budget)",
"metric_label": "Burn Rate (x)",
"items": [
{
"label": "healthy_nominal",
"value": sre_nom["burn_rate_1h"],
"display": f"{sre_nom['burn_rate_1h']}x (OK)",
"css_class": "is-fast",
},
{
"label": "transient_5m_spike_suppressed",
"value": sre_trans["burn_rate_1h"],
"display": (
f"{sre_trans['burn_rate_1h']}x 1h "
f"(5m={sre_trans['burn_rate_5m']}x suppressed)"
),
"css_class": "is-mid",
},
{
"label": "budget_exhausted_freeze",
"value": sre_exh["burn_rate_1h"],
"display": f"{sre_exh['burn_rate_1h']}x (0% left -> FROZEN)",
"css_class": "is-slow",
},
{
"label": "critical_outage_14_4x_burn",
"value": sre_crit["burn_rate_1h"],
"display": (
f"{sre_crit['burn_rate_1h']}x "
f"(5m={sre_crit['burn_rate_5m']}x -> PAGE+FREEZE)"
),
"css_class": "is-slow",
},
],
},
],
"tables": [
{
"id": "table_drift_suite_4_scenarios",
"title": "Exp 1: Evidently Drift Suite (PSI, KS, Wasserstein-1, MMD^2)",
"columns": [
"scenario",
"psi_w1_norm",
"ks_stat_p_val",
"emb_cos_mmd2",
"alarm_verdict",
],
"rows": [
[
str(sc["label"]),
f"PSI={sc['psi']} | W1={sc['wasserstein_norm_std']}",
f"D={sc['ks_stat']} | p={sc['ks_p_value']}",
f"cos={sc['embedding_cosine_distance']} | MMD2={sc['embedding_rbf_mmd2']}",
f"KS={sc['naive_ks_p_lt_005_alarm']} | SOTA={sc['practical_sota_alarm']}",
]
for sc in exp1["scenarios"]
],
},
{
"id": "table_cohort_15_21_maturation",
"title": "Exp 2 (#17): Fixed Post-Drift Cohort (Days 15-21) Maturation Curve",
"columns": [
"observation_day",
"labels_arrived_pct",
"naive_vs_true_acc",
"ipcw_vs_true_acc",
],
"rows": [
[
f"Day {r['observation_day']}",
f"{r['observed_label_pct']}%",
(
f"{r['naive_observed_accuracy_pct']}% vs "
f"{r['true_accuracy_pct']}% (+{r['naive_bias_pp']} pp)"
),
f"{r['ipcw_corrected_accuracy_pct']}% ({r['ipcw_error_pp']} pp)",
]
for r in exp2["cohort_15_21_maturation_curve"]
],
},
{
"id": "table_sre_burn_rate_matrix",
"title": "Exp 3A: SRE Multi-Window Burn-Rate & Deployment Freeze Policy",
"columns": [
"scenario",
"burn_1h_5m",
"burn_6h_30m",
"budget_left_min",
"alerts_and_freeze",
],
"rows": [
[
str(s["scenario_id"]),
f"{s['burn_rate_1h']}x / {s['burn_rate_5m']}x",
f"{s['burn_rate_6h']}x / {s['burn_rate_30m']}x",
f"{s['budget_remaining_minutes']}m ({s['budget_remaining_pct']}%)",
(
f"Crit={s['critical_14_4x_1h_5m_firing']} | "
f"Warn={s['warning_6_0x_6h_30m_firing']} | "
f"Freeze={s['deployment_frozen']}"
),
]
for s in exp3_sre["scenarios"]
],
},
{
"id": "table_telemetry_and_yaml_audit",
"title": "Exp 3B: Automated Telemetry Tests & Tier-1 YAML Security Audit",
"columns": ["check_component", "verified_scope", "observed_counts", "status"],
"rows": [
[
"Live OTel + Langfuse GenAI Spans",
"FastAPI /v1/predict + /v1/llm/chat (tool calls + generation)",
(
f"{exp3_tel['otel_span_count']} live + "
f"{suite_otel['span_count']} suite spans; 0 missing GenAI keys"
),
"PASS",
],
[
"Prometheus /metrics & Guardrail",
"Exposition counters/histograms + forbid high-cardinality labels",
(
f"Prom checks={exp3_tel['prometheus_checks_passed']} "
f"(SLI={exp3_tel['sre_live_snapshot']['observed_sli_pct']}%)"
),
"PASS",
],
[
"ELK JSON Trace-Log & Zero PII",
"100% trace_id/span_id correlation & PII regex/collector masking",
(
f"{exp3_tel['elk_log_count']} logs correlated; "
f"{exp3_tel['pii_leaks_count']} PII leaks"
),
"PASS",
],
[
"Tier-1 YAML Stack Audit",
"docker-compose.yml + otel_collector + prometheus_sre_alerts",
(
f"{exp3_cfg['yaml_files_audited']} YAMLs, "
f"{exp3_cfg['pinned_images_count']} pinned imgs, 0 :latest, 0 secrets"
),
"PASS",
],
],
},
],
}
return {
"unit_id": "T2-P5-U02",
"lab_id": "lab-20-otel-prom-elk-jaeger-langfuse-evidently",
"seed": seed,
"exp1_drift_detection_suite": exp1,
"exp2_delayed_label_monitoring": exp2,
"exp3_sre_burn_rates": exp3_sre,
"exp3_automated_telemetry_tests": exp3_tel,
"exp3_native_histogram_vs_classic_trap": exp3_hist,
"exp3_config_audit": exp3_cfg,
"suite_otel_telemetry": suite_otel,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run Lab 20 Full-Stack Observability & Late-Label SRE Suite."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch25_lab20_results.json"),
)
args = parser.parse_args()
lab_root = Path(__file__).resolve().parents[1]
report = run_full_lab_suite(seed=args.seed, lab_root=lab_root)
out_path = args.output if args.output.is_absolute() else lab_root / args.output
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
s2 = report["exp2_delayed_label_monitoring"]["summary"]
tel = report["exp3_automated_telemetry_tests"]
print(
f"Saved {out_path} | Day21 Naive Illusion=+{s2['day21_naive_illusion_bias_pp']} pp "
f"| Audit MAE={s2['post_drift_audit_ht_mae_pp']} pp "
f"| OTel Spans={tel['otel_span_count']}+{report['suite_otel_telemetry']['span_count']} "
f"| PII Leaks={tel['pii_leaks_count']}"
)
if __name__ == "__main__":
main()
"""Automated verification suite (31 tests, 0 skips) for Lab 20: Observability, Late Labels & SRE."""
from __future__ import annotations
import ast
import io
import json
import tokenize
from pathlib import Path
from typing import Any
import numpy as np
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 observability_late_labels_sre_lab.drift_and_late_labels import (
DriftThresholds,
LateLabelConfig,
compute_embedding_drift,
compute_kaplan_meier_curve,
compute_ks_two_sample,
compute_psi,
compute_wasserstein_1d,
evaluate_kaplan_meier_cdf,
run_drift_detection_suite,
simulate_delayed_label_monitoring,
)
from observability_late_labels_sre_lab.otel_genai_sre_and_tests import (
BoundedInMemorySpanExporter,
LLMChatPayload,
MLPredictPayload,
PrometheusMetricsRegistry,
SREConfig,
SREEngine,
audit_observability_configs,
compare_classic_vs_native_histogram,
create_observed_app,
redact_pii,
run_automated_telemetry_tests,
run_sre_burn_rate_benchmark,
)
from scripts.run_lab_demo import run_full_lab_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(scope="module")
def full_suite_42() -> dict[str, Any]:
return run_full_lab_suite(seed=42, lab_root=LAB_ROOT)
def test_01_ast_safety_no_type_ignore_no_sleep_no_pickle_or_binaries() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec", "sleep"}
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 5
forbidden_comment = "type:" + " ignore"
for py_file in py_files:
source = py_file.read_text(encoding="utf-8")
with io.StringIO(source) as buf:
for tok in tokenize.generate_tokens(buf.readline):
if tok.type == tokenize.COMMENT and forbidden_comment in tok.string:
raise AssertionError(f"Forbidden type-ignore comment in {py_file}")
tree = ast.parse(source, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
elif isinstance(node.func, ast.Attribute):
assert node.func.attr != "sleep"
for pat in ("*.png", "*.parquet", "*.duckdb*"):
assert not list(LAB_ROOT.rglob(pat))
def test_02_pydantic_strict_models_reject_extra_fields() -> None:
assert DriftThresholds().psi_critical == 0.25
assert LateLabelConfig().weekly_audit_budget == 160
assert SREConfig().slo_target == 0.999
for cls, bad in (
(DriftThresholds, {"psi_warning": 0.1, "rogue": 1}),
(LateLabelConfig, {"seed": 42, "extra": True}),
(SREConfig, {"slo_target": 0.999, "bogus": "x"}),
(MLPredictPayload, {"features": [0.0, 0.0, 0.0, 0.0], "injected": 1}),
(LLMChatPayload, {"prompt": "hi", "extra_key": "bad"}),
):
with pytest.raises(ValidationError):
cls.model_validate(bad)
def test_03_psi_identical_zero_and_shift_monotonicity() -> None:
rng = np.random.default_rng(42)
ref = rng.normal(0.0, 1.0, size=2000)
assert compute_psi(ref, ref) == 0.0
psi_mild = compute_psi(ref, ref + 0.3)
psi_heavy = compute_psi(ref, ref + 1.2)
assert 0.0 < psi_mild < psi_heavy
assert psi_heavy >= 0.25
def test_04_ks_two_sample_exact_identity_and_disjoint_bounds() -> None:
rng = np.random.default_rng(42)
a = rng.normal(0.0, 1.0, size=500)
d_same, p_same = compute_ks_two_sample(a, a)
assert d_same == 0.0
assert p_same == 1.0
d_disj, p_disj = compute_ks_two_sample(a, a + 20.0)
assert d_disj == 1.0
assert p_disj == 0.0
@given(
shift=st.floats(min_value=-5.0, max_value=5.0, allow_nan=False, allow_infinity=False),
scale=st.floats(min_value=0.5, max_value=3.0, allow_nan=False, allow_infinity=False),
)
@settings(max_examples=25)
def test_05_hypothesis_wasserstein_translation_equivariance(shift: float, scale: float) -> None:
rng = np.random.default_rng(7)
base = rng.normal(0.0, scale, size=300)
w1 = compute_wasserstein_1d(base, base + shift)
assert abs(w1 - abs(shift)) < 1e-4
def test_06_embedding_drift_cosine_and_mmd2_detect_topic_shift() -> None:
rng = np.random.default_rng(42)
dir_a = rng.normal(0.0, 1.0, size=16)
dir_a /= np.linalg.norm(dir_a)
dir_b = rng.normal(0.0, 1.0, size=16)
dir_b /= np.linalg.norm(dir_b)
ref = dir_a + rng.normal(0.0, 0.15, size=(160, 16))
same = dir_a + rng.normal(0.0, 0.15, size=(160, 16))
shifted = dir_b + rng.normal(0.0, 0.15, size=(160, 16))
s_same = compute_embedding_drift(ref, same)
s_shift = compute_embedding_drift(ref, shifted)
assert s_same["rbf_mmd2"] < 0.005
assert s_shift["centroid_cosine_distance"] > s_same["centroid_cosine_distance"] * 5.0
assert s_shift["rbf_mmd2"] > 0.05
def test_07_drift_suite_exposes_large_n_ks_false_alarm_and_silent_concept_drift(
full_suite_42: dict[str, Any],
) -> None:
by_id = full_suite_42["exp1_drift_detection_suite"]["by_id"]
assert by_id["stationary_baseline"]["practical_sota_alarm"] is False
assert by_id["covariate_and_embedding_shift"]["practical_sota_alarm"] is True
assert by_id["covariate_and_embedding_shift"]["psi"] >= 0.25
trap = by_id["large_n_ks_false_alarm_trap"]
assert trap["naive_ks_p_lt_005_alarm"] is True
assert trap["practical_sota_alarm"] is False
assert trap["wasserstein_norm_std"] < 0.10
silent = by_id["silent_concept_drift"]
assert silent["practical_sota_alarm"] is False
assert silent["concept_y_flip_rate"] == 0.18
def test_08_delayed_labels_right_censoring_illusion_at_day21(
full_suite_42: dict[str, Any],
) -> None:
late = full_suite_42["exp2_delayed_label_monitoring"]
s2 = late["summary"]
b2 = late["baseline_pre_drift"]
assert b2["median_delay_y1_days"] > b2["median_delay_y0_days"] * 4.0
assert s2["day21_naive_illusion_bias_pp"] >= 20.0
assert s2["day21_naive_observed_accuracy_pct"] > s2["day21_true_accuracy_pct"] + 20.0
assert s2["naive_first_alert_day"] is None
def test_09_delayed_labels_ipcw_converges_and_cuts_cohort_bias(
full_suite_42: dict[str, Any],
) -> None:
late = full_suite_42["exp2_delayed_label_monitoring"]
s2 = late["summary"]
curve = {r["observation_day"]: r for r in late["cohort_15_21_maturation_curve"]}
assert s2["post_drift_ipcw_mae_pp"] < s2["post_drift_naive_mae_pp"] * 0.6
assert abs(curve[28]["ipcw_error_pp"]) < 3.0
assert curve[28]["naive_bias_pp"] > 15.0
assert abs(curve[90]["ipcw_error_pp"]) < 1.0
def test_10_delayed_labels_proxy_signals_and_active_human_audit_early_alert(
full_suite_42: dict[str, Any],
) -> None:
s2 = full_suite_42["exp2_delayed_label_monitoring"]["summary"]
assert s2["day21_feature_x0_psi"] < 0.05
assert s2["day21_prediction_psi"] >= 0.15
assert s2["day21_entropy_delta_nats"] >= 0.03
assert s2["audit_first_alert_day"] == 21
assert s2["proxy_first_alert_day"] == 21
assert s2["post_drift_audit_ht_mae_pp"] <= 5.0
assert s2["early_detection_lead_days_vs_naive"] >= 30
@given(budget=st.integers(min_value=80, max_value=320))
@settings(max_examples=8)
def test_11_hypothesis_larger_audit_budget_preserves_early_detection(budget: int) -> None:
res = simulate_delayed_label_monitoring(LateLabelConfig(seed=42, weekly_audit_budget=budget))
assert res["summary"]["audit_first_alert_day"] == 21
assert res["summary"]["post_drift_audit_ht_mae_pp"] < res["summary"]["post_drift_naive_mae_pp"]
def test_12_sre_30day_error_budget_exact_43_2_minutes() -> None:
eng = SREEngine(SREConfig(slo_target=0.999, sla_target=0.995, window_days=30.0))
assert eng.error_budget_minutes == 43.2
eng_tight = SREEngine(SREConfig(slo_target=0.9995, sla_target=0.999, window_days=30.0))
assert eng_tight.error_budget_minutes == 21.6
def test_13_sre_multi_window_burn_rate_suppresses_transient_and_freezes_outage(
full_suite_42: dict[str, Any],
) -> None:
by_id = full_suite_42["exp3_sre_burn_rates"]["by_id"]
assert by_id["healthy_nominal"]["deployment_frozen"] is False
assert by_id["healthy_nominal"]["critical_14_4x_1h_5m_firing"] is False
trans = by_id["transient_5m_spike_suppressed"]
assert trans["burn_rate_5m"] >= 14.4
assert trans["burn_rate_1h"] < 14.4
assert trans["critical_14_4x_1h_5m_firing"] is False
assert trans["deployment_frozen"] is False
crit = by_id["critical_outage_14_4x_burn"]
assert crit["critical_14_4x_1h_5m_firing"] is True
assert crit["deployment_frozen"] is True
exh = by_id["budget_exhausted_freeze"]
assert exh["budget_remaining_pct"] == 0.0
assert exh["deployment_frozen"] is True
@given(
err_1h=st.floats(min_value=0.0, max_value=0.05),
err_5m=st.floats(min_value=0.0, max_value=0.05),
)
@settings(max_examples=20)
def test_14_hypothesis_sre_critical_requires_both_windows(err_1h: float, err_5m: float) -> None:
eng = SREEngine(SREConfig(slo_target=0.999))
out = eng.evaluate_windows("prop", err_1h, err_5m, err_1h, err_5m, budget_consumed_pct=10.0)
expected = (err_1h / 0.001 >= 14.4) and (err_5m / 0.001 >= 14.4)
assert out["critical_14_4x_1h_5m_firing"] is expected
def test_15_pii_redaction_strips_email_card_phone_and_secrets() -> None:
raw = (
"User test@corp.io card 4111-2222-3333-4448 phone +1-415-555-0199 "
"auth Bearer abcdef123456 pat ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234 "
"ts_ns=1732459384123456789"
)
clean = redact_pii(raw)
for secret in (
"test@corp.io",
"4111-2222-3333-4448",
"415-555-0199",
"abcdef123456",
"ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234",
):
assert secret not in clean
assert "[REDACTED_EMAIL]" in clean
assert "[REDACTED_CARD]" in clean
assert "[REDACTED_PHONE]" in clean
assert "[REDACTED_SECRET]" in clean
# 19-digit Unix nanosecond timestamp failing Luhn must NOT be falsely redacted
assert "ts_ns=1732459384123456789" in clean
def test_16_prometheus_forbids_high_cardinality_labels() -> None:
reg = PrometheusMetricsRegistry()
for bad_lbl in ("user_id", "request_id", "trace_id", "span_id", "email"):
with pytest.raises(ValueError, match="High-cardinality"):
reg.validate_labels({bad_lbl: "val-123"})
def test_17_live_fastapi_endpoints_and_prometheus_metrics() -> None:
app, _refs = create_observed_app()
with TestClient(app) as client:
assert client.get("/healthz").json()["status"] == "ok"
assert client.get("/readyz").json()["otel_active"] is True
p_resp = client.post("/v1/predict", json={"features": [1.0, 0.5, -0.3, 0.2]})
assert p_resp.status_code == 200
assert len(p_resp.json()["trace_id"]) == 32
l_resp = client.post(
"/v1/llm/chat",
json={"prompt": "Summarize fraud trend", "prompt_version": "v2.4.1", "tools": ["sql_query"]},
)
assert l_resp.status_code == 200
assert l_resp.json()["tool_calls"] == 1
assert l_resp.json()["cost_usd"] > 0.0
m_resp = client.get("/metrics")
assert m_resp.status_code == 200
assert "fsds_ml_http_requests_total" in m_resp.text
assert "fsds_ml_gen_ai_cost_usd_total" in m_resp.text
def test_18_automated_telemetry_tests_verify_otel_langfuse_elk_zero_pii(
full_suite_42: dict[str, Any],
) -> None:
tel = full_suite_42["exp3_automated_telemetry_tests"]
assert tel["all_telemetry_tests_passed"] is True
assert tel["otel_span_count"] == 7
assert tel["missing_genai_keys"] == []
assert tel["trace_log_correlated"] is True
assert tel["pii_leaks_count"] == 0
assert tel["prometheus_checks_passed"] is True
def test_19_bounded_exporter_enforces_fifo_maxlen() -> None:
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
exp = BoundedInMemorySpanExporter(maxlen=4)
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exp))
tracer = provider.get_tracer("test")
for idx in range(7):
with tracer.start_as_current_span(f"span-{idx}"):
pass
spans = exp.get_finished_spans()
assert len(spans) == 4
assert [s.name for s in spans] == ["span-3", "span-4", "span-5", "span-6"]
def test_20_tier1_yaml_audit_passes_compose_otel_and_prometheus() -> None:
audit = audit_observability_configs(LAB_ROOT)
assert audit["all_passed"] is True
assert audit["yaml_files_audited"] == 3
assert audit["pinned_images_count"] == 8
assert audit["latest_tags_count"] == 0
assert audit["non_localhost_ports_count"] == 0
assert audit["secret_findings_count"] == 0
def test_21_tier1_yaml_audit_catches_tampered_latest_port_and_secret(tmp_path: Path) -> None:
bad_dc = (LAB_ROOT / "docker-compose.yml").read_text(encoding="utf-8")
bad_dc = bad_dc.replace("prom/prometheus:v3.0.1", "prom/prometheus:latest").replace(
"127.0.0.1:9090:9090", "0.0.0.0:9090:9090"
)
(tmp_path / "docker-compose.yml").write_text(bad_dc, encoding="utf-8")
(tmp_path / "configs").mkdir()
bad_otel = (LAB_ROOT / "configs" / "otel_collector_config.yaml").read_text(encoding="utf-8")
bad_otel += "\n# leaked: AKIAIOSFODNN7EXAMPLE\n"
(tmp_path / "configs" / "otel_collector_config.yaml").write_text(bad_otel, encoding="utf-8")
prom_txt = (LAB_ROOT / "configs" / "prometheus_sre_alerts.yaml").read_text(encoding="utf-8")
(tmp_path / "configs" / "prometheus_sre_alerts.yaml").write_text(prom_txt, encoding="utf-8")
tampered = audit_observability_configs(tmp_path)
assert tampered["all_passed"] is False
assert tampered["latest_tags_count"] >= 1
assert tampered["non_localhost_ports_count"] >= 1
assert tampered["secret_findings_count"] >= 1
def test_22_docker_compose_hardening_and_localhost_bindings() -> None:
dc = yaml.safe_load((LAB_ROOT / "docker-compose.yml").read_text(encoding="utf-8"))
services = dc["services"]
expected = {
"otel-collector",
"jaeger",
"prometheus",
"grafana",
"elasticsearch",
"filebeat",
"kibana",
"langfuse",
}
assert set(services.keys()) == expected
for name, cfg in services.items():
assert "ALL" in cfg["cap_drop"], f"{name} missing cap_drop ALL"
assert "no-new-privileges:true" in cfg["security_opt"], f"{name} missing no-new-privileges"
for port in cfg.get("ports", []):
assert str(port).startswith("127.0.0.1:"), f"{name} exposed non-localhost port {port}"
def test_23_otel_collector_config_enforces_pii_redaction_and_tail_sampling() -> None:
otel_txt = (LAB_ROOT / "configs" / "otel_collector_config.yaml").read_text(encoding="utf-8")
cfg = yaml.safe_load(otel_txt)
procs = cfg["processors"]
assert "attributes/pii_redact" in procs
keys = {a["key"] for a in procs["attributes/pii_redact"]["actions"]}
assert {"user.email", "user.phone", "payment.card_number", "auth.bearer_token"} <= keys
assert "tail_sampling" in procs
policies = {p["name"] for p in procs["tail_sampling"]["policies"]}
assert {"errors-always", "slow-slo-traces"} <= policies
def test_24_prometheus_sre_alerts_multi_window_burn_rules() -> None:
prom_doc = yaml.safe_load(
(LAB_ROOT / "configs" / "prometheus_sre_alerts.yaml").read_text(encoding="utf-8")
)
rules = {r["alert"]: r for g in prom_doc["groups"] for r in g["rules"]}
assert "MLServiceSLOBurnRateCritical" in rules
assert rules["MLServiceSLOBurnRateCritical"]["labels"]["burn_rate"] == "14.4x"
assert rules["MLServiceSLOBurnRateCritical"]["labels"]["windows"] == "1h/5m"
assert rules["MLServiceSLOBurnRateHigh"]["labels"]["burn_rate"] == "6.0x"
assert rules["MLServiceSLOBurnRateHigh"]["labels"]["windows"] == "6h/30m"
assert "LLMCostBurnRateHigh" in rules
assert "MLPredictionDriftCritical" in rules
def test_25_suite_otel_spans_recorded_deterministically(full_suite_42: dict[str, Any]) -> None:
suite_otel = full_suite_42["suite_otel_telemetry"]
assert suite_otel["span_count"] == 4
assert suite_otel["span_names"] == [
"lab20.exp1_drift_suite",
"lab20.exp2_delayed_labels_17",
"lab20.exp3_sre_and_telemetry",
"lab20.benchmark.suite",
]
def test_26_run_drift_and_sre_benchmarks_return_consistent_shapes() -> None:
d = run_drift_detection_suite(seed=42)
s = run_sre_burn_rate_benchmark()
t = run_automated_telemetry_tests()
assert len(d["scenarios"]) == 4
assert len(s["scenarios"]) == 4
assert t["all_telemetry_tests_passed"] is True
def test_27_seed42_determinism_across_full_suite(full_suite_42: dict[str, Any]) -> None:
again = run_full_lab_suite(seed=42, lab_root=LAB_ROOT)
assert full_suite_42 == again
def test_28_workbench_panels_schema_and_artifact_json_sync(full_suite_42: dict[str, Any]) -> None:
panels = full_suite_42["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for kpi in panels["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi.keys())
for bar in panels["bars"]:
assert {"id", "title", "metric_label", "items"} <= set(bar.keys())
assert len(bar["items"]) >= 3
for tbl in panels["tables"]:
assert {"id", "title", "columns", "rows"} <= set(tbl.keys())
assert len(tbl["rows"]) >= 3
artifact_path = LAB_ROOT / "artifacts" / "t2_ch25_lab20_results.json"
assert artifact_path.is_file(), "Run scripts/run_lab_demo.py first"
disk_data = json.loads(artifact_path.read_text(encoding="utf-8"))
assert disk_data == full_suite_42
def test_29_kaplan_meier_product_limit_exact_and_no_oracle_weibull() -> None:
times = np.array([2.0, 4.0, 4.0, 6.0, 8.0], dtype=np.float64)
events = np.array([True, False, True, False, True], dtype=bool)
t_grid, cdf_grid = compute_kaplan_meier_curve(times, events)
# S(2)=4/5=0.8 -> F=0.2; S(4)=0.8*(1-1/4)=0.6 -> F=0.4; S(8)=0.6*(1-1/1)=0.0 -> F=1.0
vals = evaluate_kaplan_meier_cdf(t_grid, cdf_grid, np.array([1.0, 2.0, 4.0, 6.0, 8.0]))
assert np.allclose(vals, np.array([0.0, 0.2, 0.4, 0.4, 1.0]), atol=1e-6)
src_text = (
LAB_ROOT / "src" / "observability_late_labels_sre_lab" / "drift_and_late_labels.py"
).read_text(encoding="utf-8")
assert "_maturity_cdf_y0" not in src_text
assert "_maturity_cdf_y1" not in src_text
def test_30_otel_genai_v1_37_ragas_and_prometheus_native_histograms(
full_suite_42: dict[str, Any],
) -> None:
tel = full_suite_42["exp3_automated_telemetry_tests"]
attrs = tel["genai_span_attributes"]
assert attrs["gen_ai.operation.name"] == "chat"
assert attrs["gen_ai.provider.name"] == "vllm"
assert attrs["gen_ai.response.finish_reasons"] == ["stop"]
assert tel["deprecated_genai_keys_present"] == []
assert "ragas.faithfulness" in attrs
assert "ragas.answer_relevancy" in attrs
assert "ragas.context_precision" in attrs
exp = BoundedInMemorySpanExporter(maxlen=32)
app, _refs = create_observed_app(exporter=exp)
with TestClient(app) as client:
r_rag = client.post(
"/v1/llm/ragas_eval",
json={
"prompt": "Verify card chargeback policy timeline",
"answer": "Chargeback disputes follow card policy timeline within 90 days",
"contexts": ["Card chargeback policy timeline allows disputes within 90 days."],
},
)
assert r_rag.status_code == 200
rag_scores = r_rag.json()["ragas"]
assert rag_scores["faithfulness"] > 0.5
m_txt = client.get("/metrics").text
assert "fsds_ml_prediction_psi" in m_txt
assert "fsds_ml_audit_early_accuracy_drop" in m_txt
rag_spans = [s for s in exp.get_finished_spans() if s.name == "gen_ai.evaluation.ragas"]
assert len(rag_spans) == 1
assert dict(rag_spans[0].attributes or {})["gen_ai.provider.name"] == "vllm"
hist_cmp = compare_classic_vs_native_histogram(seed=42)
assert hist_cmp["classic_fixed_bucket_p99_truncated"] is True
assert hist_cmp["native_p99_relative_error_pct"] < 5.0
def test_31_container_configs_prometheus_yml_two_tier_lb_and_no_clamp_min() -> None:
audit = audit_observability_configs(LAB_ROOT)
assert audit["all_passed"] is True
assert audit["otel_binds_all_interfaces"] is True
assert audit["langfuse_service_dns"] is True
assert audit["promql_low_rps_safe"] is True
assert audit["prometheus_yml_verified"] is True
assert audit["prometheus_native_histograms_scrape"] is True
assert audit["two_tier_otel_lb_verified"] is True
dc = yaml.safe_load((LAB_ROOT / "docker-compose.yml").read_text(encoding="utf-8"))
assert "langfuse" in dc["services"]
assert any(str(p).endswith(":3000") for p in dc["services"]["langfuse"]["ports"])
otel_cfg = yaml.safe_load(
(LAB_ROOT / "configs" / "otel_collector_config.yaml").read_text(encoding="utf-8")
)
langfuse_ep = otel_cfg["exporters"]["otlphttp/langfuse"]["endpoint"]
assert "http://langfuse:3000/api/public/otel" in langfuse_ep
prom_yml = yaml.safe_load((LAB_ROOT / "configs" / "prometheus.yml").read_text(encoding="utf-8"))
assert prom_yml["global"]["scrape_native_histograms"] is True
jobs = {j["job_name"]: j for j in prom_yml["scrape_configs"]}
assert {"fsds-ml-llm-api", "otel-collector"} <= set(jobs.keys())
assert jobs["fsds-ml-llm-api"]["scrape_native_histograms"] is True
lb_yml = yaml.safe_load(
(LAB_ROOT / "configs" / "otel_collector_lb_gateway.yaml").read_text(encoding="utf-8")
)
assert lb_yml["exporters"]["loadbalancing"]["routing_key"] == "traceID"
Evidently Drift Suite của Lab 20 (Exp 1), điều gì xảy ra với kịch bản large_n_ks_false_alarm_trap (n = 50,000, dịch +0.035 sigma) và bộ thước đo nào khắc phục hiệu quả?Lab 20 Exp 1: Vì N_eff = sqrt(nm/(n+m)) tăng theo căn bậc hai kích thước mẫu, tại n = 50,000, một dịch chuyển vô hại +0.035 sigma tạo D = 0.0105 nhưng kéo KS p_value = 0.00800434 < 0.05 (báo động giả). Ngược lại, PSI = 0.000687 và Wasserstein-1 chuẩn hóa (0.026534 < 0.25) chỉ phụ thuộc biên độ dịch chuyển thực tế nên bác bỏ nhiễu sạch sẽ.
Logs, Metrics, Traces) dùng Prometheus 3.0+ của Lab 20, đưa user_id/trace_id vào nhãn metric gây rủi ro gì và Native Histograms khắc phục bẫy classic histogram ra sao?PrometheusMetricsRegistry cấm nhãn lực lượng cao (user_id, trace_id, request_id) để tránh TSDB OOM, chỉ giữ nhãn hữu hạn (route, status_class, model_version, prompt_version) còn trace_id ghi sang ELK/OTel. Ở phần đuôi độ trễ (2,000 mẫu, 13.9% > 1.0s, true_p99 = 3.3018s), classic histogram chặn ở le = 1.0s trả +Inf, trong khi Prometheus 3.0 Native Histograms (schema = 3, 54 buckets) đo đạt p99 = 3.3636s (1.87% sai số).
Day 21 (cohort day_15_to_21, 24.11% nhãn đã về) trong Lab 20 Exp 2, vì sao Naive Observed Accuracy vẫn báo 85.78% dù độ chính xác thật đã sụp xuống 60.46%?Lab 20 Exp 2, nhãn hợp lệ Y=0 xác nhận nhanh với trung vị 4.16 ngày, còn nhãn gian lận Y=1 mất trung vị 28.25 ngày (tối đa 90 ngày). Ở tuổi non (0–6 ngày tại Day 21), phần lớn các ca Y=0 đã về còn các ca bỏ sót gian lận (False Negatives, Y=1) vẫn đang bị kiểm duyệt phải, khiến Naive Observed Accuracy vọt lên 85.78% (+25.31 pp ảo giác so với 60.46%).
Kaplan–Meier IPCW trong simulate_delayed_label_monitoring (Lab 20 Exp 2, Tests 08–09, 29) khắc phục thiên lệch nhãn trễ như thế nào và kết quả trên đoàn hệ Days 15–21 ra sao?compute_kaplan_meier_curve ước lượng xác suất trưởng thành thực nghiệm theo lớp m_{y_i}(a) để tính trọng số IPCW w_i = 1 / max(0.08, m_{y_i}(t - t_i)). Nhờ khuếch đại đúng tỷ lệ các ca Y=1 đến trễ trên đoàn hệ Days 15–21 tại Day 28 (57.54% nhãn về), Kaplan–Meier IPCW đạt 61.61% (+1.15 pp so với 60.46%, tốt hơn nhiều mức +21.53 pp của Naive), đồng thời giảm post_drift_ipcw_mae_pp xuống 12.32 pp (so với 25.03 pp của Naive).
Silent Concept Drift của Lab 20 Exp 2 (Day 21, feature_x0_psi = 0.002636), cặp tín hiệu nào bắt được cú rơi chất lượng ngay tuần đầu tiên?feature_x0_psi = 0.002636) và CBPE lạc quan (80.20%), sự dịch chuyển tương quan đẩy prediction_psi lên 0.232916 và entropy_delta lên +0.0491 nats ngay Day 21. Kết hợp lấy mẫu phân tầng Active Audit (160 ca/tuần = 5.71%) ước lượng theo công thức Horvitz-Thompson cho 63.09% (MAE = 3.87 pp) và phát cảnh báo sớm 39 ngày so với cửa sổ tuần ngây thơ.
SLO = 99.9% trong 30 ngày (43.2 phút ngân sách lỗi), tại sao cảnh báo MLServiceSLOBurnRateCritical (14.4x) yêu cầu điều kiện AND trên cả cửa sổ 1h lẫn 5m cùng mẫu số > 0?SLO = 99.9%, ngân sách lỗi 30 ngày là 43.2 phút (error_rate = 0.001). Điều kiện AND (burn_1h >= 14.4 và burn_5m >= 14.4) vừa phản ứng nhanh với sự cố thật tiêu thụ 2% ngân sách/giờ vừa lọc sạch các gai thoáng qua (transient_5m_spike_suppressed: 5m = 18.0x, 1h = 1.2x -> freeze = False), đồng thời bảo vệ mẫu số bằng > 0 thay vì clamp_min gây mù cảnh báo khi lưu lượng < 1 RPS.
200 OK, tổ hợp thuộc tính OTel GenAI v1.37+ / Langfuse / RAGAS nào trong Lab 20 truy vết chính xác?OTel GenAI v1.37+ kết hợp cây span Langfuse (langfuse.trace -> gen_ai.agent_step -> gen_ai.tool_call -> gen_ai.generation) ghi lại đồng bộ gen_ai.provider.name, gen_ai.response.finish_reasons, gen_ai.prompt.version, gen_ai.tool.calls, gen_ai.usage.*, gen_ai.cost_usd cùng chỉ số chất lượng RAG RAGAS (ragas.faithfulness = 0.94, answer_relevancy = 0.91, context_precision = 0.89).
run_automated_telemetry_tests và audit_observability_configs trong Lab 20 (Tests 15–31) kiểm chứng những bất biến bắt buộc nào ngay trong đường ống CI?run_automated_telemetry_tests chạy FastAPI TestClient + BoundedInMemorySpanExporter xác minh 7 live + 4 suite spans chuẩn OTel GenAI v1.37+ (gen_ai.operation.name="chat") & RAGAS, 3/3 log JSON ELK trùng trace_id, /metrics chuẩn, và 0 rò rỉ PII (kiểm tra thẻ Luhn + ghp_). audit_observability_configs xác nhận kiến trúc 2 tầng (loadbalancing theo traceID -> tail_sampling + pii_redact), prometheus.yml (scrape_native_histograms: true) + alerts (> 0), 8 image ghim (prometheus:v3.0.1, langfuse:3.25.0), 127.0.0.1:.
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 — Giải mã Bẫy KS Cỡ Lớn và Chọn Bộ Đo Trôi Evidently 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Quan sát số hạng N_eff = sqrt(nm/(n+m)) trong compute_ks_two_sample khi n = 50,000 và so sánh cách compute_wasserstein_1d đo dịch chuyển theo đơn vị độ lệch chuẩn.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_03 or test_04 or test_05 or test_06 or test_07" -v và đối chiếu exp1_drift_detection_suite trong artifacts/t2_ch25_lab20_results.json.
Tiêu chí Đáp án & Số đối chứng
Ở n = 50,000 với độ dịch +0.035 sigma, KS cho D = 0.0105 nhưng N_eff = 158.11 đẩy p = 0.00800434 < 0.05 (báo động giả), trong khi PSI = 0.000687 và W1/std = 0.026534 < 0.25 bác bỏ chính xác. Trên covariate_and_embedding_shift, PSI = 0.611997, W1/std = 0.876281 và MMD2 = 0.088917 đều bắt đúng, còn silent_concept_drift qua mặt toàn bộ chỉ số đầu vào.
Bài tập 2 — Phân tích Thiên lệch Kiểm duyệt Phải và Bù Kaplan-Meier IPCW 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh hàm trễ Y=0 (trung vị 4.16d) vs Y=1 (trung vị 28.25d) và theo dõi cách compute_kaplan_meier_curve ước lượng độ trưởng thành thực nghiệm để tính trọng số IPCW tại Day 21 và Day 28.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_08 or test_09 or test_29" -v và kiểm tra cohort_15_21_maturation_curve trong artifacts/t2_ch25_lab20_results.json.
Tiêu chí Đáp án & Số đối chứng
Tại Day 21 (24.11% nhãn về), các ca Y=0 đã về nhiều trong khi Y=1 bỏ sót chưa kịp phản hồi, làm Naive Observed = 85.78% lệch +25.31 pp so với True = 60.46% (naive_first_alert_day = None). Trọng số Kaplan–Meier IPCW (m_min = 0.08) giảm post_drift_ipcw_mae_pp từ 25.03 pp xuống 12.32 pp và đưa đoàn hệ 15–21 ở Day 28 (57.54%) về 61.61% (+1.15 pp vs +21.53 pp của Naive).
Bài tập 3 — Proxy Không Nhãn và Kiểm toán Chủ động Horvitz-Thompson 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra nguyên nhân prediction_psi và entropy_delta_nats tăng dù feature_x0_psi = 0.002636, cùng cách chia 3 tầng kiểm toán (0.45, 0.35, 0.20) trong simulate_delayed_label_monitoring.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11" -v và đối chiếu by_day.day_21 với summary trong exp2_delayed_label_monitoring.
Tiêu chí Đáp án & Số đối chứng
Tại Day 21, prediction_psi vọt lên 0.232916 và entropy_delta tăng +0.0491 nats (proxy_first_alert_day = 21). Kiểm toán phân tầng 160 ca/tuần (5.71% lưu lượng) theo Horvitz-Thompson ước lượng ngay 63.09% tại Day 21 (post_drift_audit_ht_mae_pp = 3.87), kích hoạt cảnh báo sớm 39 ngày so với giám sát tuần ngây thơ.
Bài tập 4 — Ngân sách Lỗi SRE, Bẫy Low-RPS và Prometheus 3.0 Native Histograms 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xem SREEngine.evaluate_windows (1h AND 5m), điều kiện mẫu số > 0 thay cho clamp_min, và exp3_native_histogram_vs_classic_trap so sánh le = 1.0s với Native Histogram (schema = 3).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_12 or test_13 or test_14 or test_30" -v và đối chiếu exp3_sre_burn_rates cùng exp3_native_histogram_vs_classic_trap.
Tiêu chí Đáp án & Số đối chứng
99.9% SLO cấp 43.2 phút/30d (transient_5m_spike: 5m=18.0x, 1h=1.2x -> freeze=False; critical_outage: 1h=16.0x, 5m=18.0x -> freeze=True, dùng > 0 an toàn ở < 1 RPS). Trên 2,000 mẫu (13.9% > 1.0s, true_p99 = 3.3018s), classic le = 1.0s sập +Inf, còn Prometheus 3.0 Native Histogram (54 buckets) ước lượng p99 = 3.3636s (1.87% sai số).
Bài tập 5 — FastAPI Live, OTel GenAI v1.37+ / RAGAS và Kiểm thử PII Luhn 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi cấu trúc lồng nhau langfuse.trace -> gen_ai.agent_step -> gen_ai.tool_call + gen_ai.generation, thuộc tính gen_ai.operation.name, gen_ai.provider.name, gen_ai.response.finish_reasons, ragas.*, lọc PII qua kiểm tra Luhn + ghp_, và PrometheusMetricsRegistry.validate_labels.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_15 or test_16 or test_17 or test_18 or test_19" -v và đối chiếu exp3_automated_telemetry_tests.
Tiêu chí Đáp án & Số đối chứng
run_automated_telemetry_tests kiểm chứng 7 live + 4 suite spans mang đủ OTel GenAI v1.37+ (gen_ai.operation.name="chat", gen_ai.provider.name="vllm", finish_reasons=["stop"], cost_usd=0.000121) và RAGAS (faithfulness=0.94, answer_relevancy=0.91, context_precision=0.89), 3/3 ELK JSON tương quan trace_id, /metrics chuẩn, và 0 rò rỉ PII (Luhn + ghp_).
Bài tập 6 — Kiểm toán Collector 2 Tầng, Prometheus Config và Tính Xác định 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra audit_observability_configs đối với docker-compose.yml (8 ảnh gồm prometheus:v3.0.1 & langfuse:3.25.0), otel_collector_config.yaml (2 tầng loadbalancing theo traceID -> tail_sampling + attributes/pii_redact), và prometheus.yml (scrape_native_histograms: true) + prometheus_sre_alerts.yaml.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_lab_demo.py, ruff check src scripts tests, mypy src tests, pytest -p no:cacheprovider -v, và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
audit_observability_configs xác nhận 8 Compose images ghim (prometheus:v3.0.1, langfuse:3.25.0, 0 :latest, 127.0.0.1:, 0 bí mật), OTel 2 tầng (loadbalancing traceID -> tail_sampling + pii_redact), prometheus.yml (scrape_native_histograms: true) + alerts an toàn < 1 RPS (> 0), 31/31 pytest pass (0 skip, 0 # type: ignore), uv.lock khớp hoàn toàn.