Chương 25 — Đánh giá Hệ thống LLM, RAG & Agent theo Chế độ Lỗi (Failure-Mode Taxonomy, Assertion Waterfall & CI/CD Gates)
Chuyên đề #5: Phá ảo giác điểm tổng hợp Nghịch lý Simpson (Overall 84.2% +2.9pp che sụp đổ Tier-1 -20.8pp, McNemar p=0.0625), Phân loại MECE 6 Chế độ Lỗi (P(GenFail|GoldInCtx)=6.8% vs RetMiss=3.0%), Thác Deterministic-First (bắt 86.8% ở ~0.16ms, 0 USD) + Dawid-Skene 3 Judges đúng phạm vi 157/39 ca sống sót (k=0.587 vs 0.044; 3x cost: Tier-1 117 calls = 0.468 USD, -51.3% vs 1J / -83.8% vs 3J) & Cổng CI Slice Non-Regression (-86.0% Expected Risk -> 96.7% PASS).
Đơn vị học phần (
Unit ID):T1-P5-U03(Phần 5: Hệ thống RAG Sản xuất, Agentic AI & Đánh giá theo Chế độ Lỗi — Mục lục Phần 5)
Phòng thí nghiệm Thực hành (Workbench): WB-Ch25 — Xưởng Kiểm định Đánh giá LLM, RAG & Agent theo Chế độ Lỗi (failure_mode_eval_lab)
Chuyên đề Nghiên cứu Tích hợp Bắt buộc: Chuyên đề #5 — LLM Evaluation by Failure Mode
Truy xuất nguồn & kế thừa: Chương 22 — An toàn AI, Hack Phần thưởng & Hiệu chuẩn Giám khảo LLM, Chương 23 — Kiến trúc RAG Tiên tiến & Truy xuất Lai,Chương 24(Agentic AI, Giao thứcMCP, Sandboxing & Tự cải thiện), Chương trình gốc DSAI (R53), và Đề cương SOTA 2026 (Chương 25). Chương tiếp theo trong lộ trình làChương 26(Kiến trúc Phần cứng GPU & Mô hình Lập trình CUDA).
Bốn Thảm họa Đánh giá Sản xuất Mở màn: Vì sao Điểm Tổng hợp Đẹp Vẫn Làm Sập Hệ thống Thực tế#
Phần lớn các đội phát triển ứng dụng LLM/RAG/Agent đánh giá mô hình bằng một con số trung bình duy nhất ("Pass rate tăng từ 81.2% lên 84.2%, phát hành ngay!") — và liên tục hứng chịu sự cố nghiêm trọng ngay sau khi triển khai. Bốn ca thất bại định lượng dưới đây, được tái hiện đầy đủ trên tập kiểm thử vàng phân tầng 240 mẫu ghép cặp (6 phân khúc, seed = 42) trong WB-Ch25 (failure_mode_eval_lab) (lưu ý minh bạch: toàn bộ câu trả lời mô hình, dấu vết gọi công cụ và phiếu chấm giám khảo trong WB-Ch25 là proxy tổng hợp có kiểm soát chạy ngoại tuyến mô phỏng chính xác cơ chế vật lý-toán học của hệ thống sản xuất mà không phụ thuộc API/GPU ngoài), bóc trần bốn lỗ hổng cốt lõi của Chuyên đề #5:
-
Ca 1 — Ảo ảnh Điểm Tổng hợp & Nghịch lý Simpson (
WB-Ch25,Test 04):Khi nâng cấp từ mô hình
v1_baselinesangv2_aggregate_mirage, điểm đạt trung bình trên toàn bộ240mẫu tăng từ81.2%(195/240) lên84.2%(202/240,+2.9pp)! Nhìn bề ngoài, cổng kiểm thử tổng hợp ngây thơ đóng dấuPASS. Nhưng khi tách theo từng phân khúc, toàn bộ mức tăng đến từ nhóm truy vấn dễeasy_paraphrasechiếm50%lưu lượng (75.8% -> 98.3%,+22.5pp), che khuất sự sụp đổ đồng loạt của cả5/5phân khúcTier-1trọng yếu:compliance_citationrơi-20.8pp(91.7% -> 70.8%),agent_tool_userơi-20.8pp(87.5% -> 66.7%),structured_json_apirơi-16.7pp(87.5% -> 70.8%),long_context_ragvàmultiturn_statefulcùng rơi-12.5pp(83.3% -> 70.8%). Độ chính xác nhómTier-1lao dốc từ86.7% -> 70.0%, đẩy Rủi ro Sản xuất Kỳ vọng (Expected Production Risk) tăng vọt+55.4%(0.346 -> 0.537)! Tệ hơn, dưới kịch bản dịch chuyển lưu lượng (Nghịch lý Simpson), ngay cả khi cả hai nhóm đều tệ đi (easy: 94% -> 92%,critical: 78% -> 64%), việc tỷ trọng câu dễ tăng từ30% -> 80%vẫn làm điểm tổng hợp nhảy ảo+3.6pp(82.8% -> 86.4%). -
Ca 2 — Đổ lỗi Nhầm Tầng & Đếm Trùng Nguyên nhân (
WB-Ch25,Tests 05–07):Một trợ lý RAG pháp lý vừa không truy xuất được điều khoản gốc (
RETRIEVAL_MISS, \(R@k = 0\)), vừa khiến LLM tự suy diễn sai mã[POL-999]. Nếu bộ đánh giá gán nhãnHallucination, đội kỹ sư sẽ mất hàng tuần tinh chỉnh prompt/DPO vô ích trong khi nguyên nhân gốc nằm ở bộ lập chỉ mục/phân mảnh (Index/Retriever). Ngược lại, trên nhómlong_context_rag, tài liệu vàng thực sự đã nằm trong Top-5 (GoldInCtx = True), nhưng bị kẹp ở vị trí giữa (Lost-in-the-Middle,index = 2) làm mô hình bỏ qua (CONTEXT_UTILIZATION_ERROR,6ca trongv2). Hệ phân loại 6 chế độ lỗi chuẩnMECEdùng cây ưu tiên nhân quả tách rạch ròi \(P(\text{RetMiss}) = \mathbf{3.0\%}\) khỏi \(P(\text{Gen/CtxFail} \mid \text{GoldInCtx}) = \mathbf{6.8\%}\). -
Ca 3 — Lãng phí Chi phí Gọi LLM Giám khảo Cho Lỗi Cú pháp & Nhiễu Giám khảo Đơn lẻ (
WB-Ch25,Tests 10–12):Đẩy toàn bộ
240mẫu sang một giám khảo LLM đơn lẻ ($0.004/lượt) tốn240lượt ($0.960), còn gọi cả hội đồng3giám khảo cho toàn bộ240mẫu tốn tới720lượt ($2.880) — mà trên tập sống sót ngữ nghĩa tinh vi, giám khảo đơn lẻ chỉ đạt Cohen's \(\kappa = 0.044\) (RAG Survivor Accuracy = 87.3%). Áp dụng Thác Kiểm địnhAssertion Waterfall— chạy kiểm chứng tất định (jsonschema,Pydantic v2, kiểm tra DAG tiên quyết & tham số công cụ, đối chiếu trạng thái đa lượt, xác minh mọi thẻ trích dẫn[TAG-123]có mặt trongretrieved_chunk_ids) trước hết — chặn ngay86.8%(33/38) toàn bộ ca lỗi củav2chỉ trong~0.16 ms/mẫu (< 0.2 ms) ở chi phí$0. Ở Tầng 2 (Hội đồng 3 Giám khảo PoLL + Dawid–Skene EM, đơn giá$0.012/mẫu, khớp thuần trên157ca RAG sống sót): nếu định tuyến toàn bộ157ca RAG tốn157 × 3 = 471lượt ($1.884— đắt hơn 1 giám khảo ngây thơ$0.960!), còn định tuyến rủi ro39ca RAGTier-1sống sót chỉ tốn39 × 3 = 117lượt ($0.468), tiết kiệm-51.25%so với 1 giám khảo ($0.960) và-83.75%so với 3 giám khảo toàn bộ ($2.880); đồng thờiDawid–Skene EMnâng \(\kappa\) trên tập sống sót từ0.044 -> 0.587(RAG Survivor Accuracy: 87.3% -> 97.5%,Waterfall E2E = 98.3%). -
Ca 4 — Cổng
CI/CDTheo Lát cắt & Sửa lỗi Trúng Đích (v2 BLOCKED -> v3 APPROVED,Tests 13–15, 20):Thay cổng tổng hợp ngây thơ bằng
SliceNonRegressionGate(ngân sách tụt tối đa-3.0pp, sànTier-1 >= 78.0%, tỷ lệ rủi ro tối đa1.05x, kiểm định ý nghĩa thống kêMcNemarở mức \(\alpha = 0.05\) khi \(\Delta_s < 0\)), hệ thốngCI/CDchặn đứngv2với5/5lát cắtTier-1vi phạm và tỷ lệ rủi ro1.55x. Dựa vào bảng xếp hạng rủi ro của Playbook (TOOL_SELECTION_ARG_ERRORchiếm27.9%rủi ro,INSTRUCTION_SCHEMA_VIOLATION19.0%,MULTITURN_STATE_DRIFT16.3%), đội kỹ sư áp dụng đúng biện pháp cho từng chế độ lỗi, đưav3_remediatedlên96.7%tổng thể (96.7%Tier-1), hạ Expected Risk xuống0.075(-86.0%so vớiv2) và được duyệt phát hành (0lát cắt vi phạm).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 25 và vượt qua trọn vẹn 20/20 bài kiểm thử của WB-Ch25 (failure_mode_eval_lab), học viên đạt 5 năng lực cốt lõi về đánh giá hệ thống AI sản xuất (Chuyên đề #5):
- Bóc trần Ảo ảnh Điểm Tổng hợp & Nghịch lý Simpson: Định lượng được cơ chế nhóm dễ khối lượng lớn che giấu sụp đổ ở phân khúc rủi ro cao, và chứng minh nghịch lý đảo chiều dấu dưới dịch chuyển lưu lượng cùng hàm Rủi ro Sản xuất Kỳ vọng.
- Thiết kế Hệ Phân loại 6 Chế độ Lỗi Chuẩn
MECE: Phân hoạch hoàn chỉnh mọi lỗiLLM/RAG/Agentthành 6 nhóm không giao nhau (Retrieval Miss,Context Utilization Error,Groundedness / Hallucination,Instruction / Schema Violation,Tool-Selection & Argument Error,Multi-Turn State & Memory Drift) và tính xác suất quy kết có điều kiện. - Làm chủ Thống kê So sánh Mô hình & Hiệu chuẩn Giám khảo: Cài đặt và giải thích Kiểm định Chính xác
McNemartrên các cặp bất đồng(b, c), Paired Bootstrap 95% CI, Cohen's \(\kappa\) và thuật toán Dawid–Skene EM cho hội đồng giám khảo. - Xây dựng Thác
Assertion Waterfall& Cổng Hồi quyCI/CD: Áp dụng triết lý Tất định trước ($0,<1 ms), Giám khảo hiệu chuẩn sau, kết hợpSliceNonRegressionGatechặn hồi quy ngầm trước khi ra sản xuất. - Thực thi Cẩm nang Sửa lỗi (
Production Decision Playbook): Ánh xạ chính xác từ chế độ lỗi định lượng sang can thiệp kiến trúc (Retrieval/Chunking vs Reranker/Context Budget vs FSM Decoding vs Tool Precondition DAG vs Episodic State Checkpointer).
Truy xuất Nguồn & Tích hợp Chuyên đề #5 (Article #5 + R53 Traceability)#
Thành phần Chuyên đề #5 (Article #5) & R53 |
Nội dung Chuyên sâu trong Chương 25 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong WB-Ch25 (failure_mode_eval_lab) |
|---|---|---|---|
| Phần 1: Vì sao Điểm Tổng hợp Che giấu Thảm họa | Aggregate Score Mirage (81.2% -> 84.2% che -20.8pp Tier-1 & +55.4% Risk), Nghịch lý Simpson, Expected Production Risk |
Widget 1 (aggregate-score-mirage-simpson-explorer) |
failure_taxonomy_and_metrics.py: demonstrate_simpsons_paradox_traffic_shift, build_stratified_eval_suites (Test 04) |
Phần 2: 6 Chế độ Lỗi MECE & Quy kết Nhân quả |
Cây ưu tiên MECE (FM-1..FM-6), \(P(\text{RetMiss})\) vs \(P(\text{GenFail} \mid \text{GoldInCtx})\), McNemar, Paired Bootstrap CI, Dawid–Skene EM |
Mermaid 1 + Widget 2 (six-failure-modes-attribution-matrix) |
failure_taxonomy_and_metrics.py: classify_sample_failure_mode, compute_conditional_fault_attribution, compute_mcnemar_test, dawid_skene_em (Tests 05–09, 12) |
Phần 3: Tập Vàng, Kiểm chứng Tất định & Cổng CI/CD |
Assertion Waterfall (jsonschema, Pydantic v2, Tool DAG, State Slots, xác minh [TAG-123] <0.2ms, $0), SliceNonRegressionGate (có mcnemar_alpha) |
Mermaid 2 + Mermaid 3 + Widget 3 (golden-eval-ci-gate-auditor) |
golden_eval_and_ci_gates.py: run_deterministic_assertions, run_assertion_waterfall_benchmark, evaluate_ci_release_gate (Tests 10–14, 19–20) |
| Phần 4: Cẩm nang Quyết định Sửa lỗi Sản xuất | Xếp hạng ưu tiên theo Risk (TOOL 27.9%, SCHEMA 19.0%, STATE 16.3%) & can thiệp trúng đích (v2 -> v3: 96.7%, Risk -86.0%) |
Bảng Playbook Mục 2.4 | golden_eval_and_ci_gates.py: build_remediation_playbook, run_full_ch25_wb25_benchmark (Tests 14–18) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Đơn vị | Định nghĩa Chuẩn trong Chương 25 | Tên biến trong failure_mode_eval_lab |
|---|---|---|---|
| \(A_s^{(m)}, w_s\) | \([0, 1], \mathbb{R}_{>0}\) | Tỷ lệ đạt của mô hình \(m\) và trọng số lưu lượng trên phân khúc \(s \in \{1, \dots, 6\}\) | base_pass_rate, cand_pass_rate, n_samples |
| \(\ell_s, \mathcal{R}_{\text{prod}}\) | \(\mathbb{R}_{>0}, \mathbb{R}_{\ge 0}\) | Trọng số mức độ nghiêm trọng (severity) và Rủi ro Sản xuất Kỳ vọng \(\frac{1}{N}\sum_{i=1}^N \ell_i \mathbb{I}[\text{fail}_i]\) | severity_weight, expected_production_risk |
| \(\Delta_s, [\text{CI}_L, \text{CI}_H]\) | Điểm % (pp) |
Chênh lệch \(100(A_s^{\text{cand}} - A_s^{\text{base}})\) và Khoảng tin cậy Paired Bootstrap 95% (2,000 lần) |
delta_pp, ci_low_pp, ci_high_pp |
| \(P(\text{RetMiss})\) | \([0, 1]\) | Xác suất hụt truy xuất (\(R@k = 0\)) trên các truy vấn cần tra cứu kho tài liệu | p_retrieval_miss |
| \(P(\text{GenFail} \mid \text{GoldInCtx})\) | \([0, 1]\) | Xác suất lỗi Tận dụng Ngữ cảnh hoặc Ảo giác khi đoạn vàng đã có mặt trong Top-\(k\) | p_gen_fail_given_gold_in_ctx |
| \(b, c, \chi^2_{\text{cc}}, p_{\text{McNemar}}\) | \(\mathbb{Z}_{\ge 0}, \mathbb{R}_{\ge 0}, [0, 1]\) | Số cặp bất đồng (v1 đúng/v2 sai vs ngược lại), thống kê \(\chi^2\) hiệu chỉnh liên tục, p-value hai phía |
mcnemar_b_regressions, mcnemar_c_improvements, mcnemar_p_value |
| \(\kappa, \text{EM}_{\text{DS}}\) | \([-1, 1], [0, 1]\) | Hệ số đồng thuận Cohen's \(\kappa\) và xác suất hậu nghiệm hội đồng Dawid–Skene EM |
compute_cohens_kappa, dawid_skene_em |
Trụ cột 1 — Nền tảng Toán học & Thuật toán: Từ Nghịch lý Simpson đến 6 Chế độ Lỗi MECE & Thống kê Phát hành#
1.1 Phần 1 (Article #5): Tại sao Điểm Tổng hợp Đơn lẻ Che giấu Thảm họa Sản xuất?#
Xét một tập kiểm thử gồm \(S\) phân khúc (slices) rời nhau có kích thước \(\{n_1, \dots, n_S\}\) (\(\sum_{s=1}^S n_s = N\)) và tỷ trọng lưu lượng \(w_s = n_s / N\). Tỷ lệ đạt tổng hợp (Aggregate Pass Rate) chỉ là trung bình tuyến tính không phân biệt hậu quả kinh doanh:
Phương trình này tạo ra hai cái bẫy toán học chết người:
-
Cái bẫy Che khuất Khối lượng (Volume-Masking Collapse): Trong hệ thống doanh nghiệp, truy vấn hỏi đáp thông thường (
easy_paraphrase) thường chiếm \(w_1 \ge 50\%\) tổng lưu lượng với mức thiệt hại đơn vị thấp (\(\ell_1 = 1.0\)), trong khi các luồng trọng yếu (compliance_citation,agent_tool_use,structured_json_api) tuy chiếm tỷ trọng nhỏ hơn (\(10\%\) mỗi nhóm) nhưng mang trọng số rủi ro \(\ell_s \in [2.5, 4.5]\) (vi phạm tuân thủ pháp lý, hoàn tiền sai, sập API). Khi mô hình mới nâng nhóm dễ thêm \(\Delta A_1 = +22.5\text{pp}\) nhưng làm5nhóm Tier-1 sụt \(-12.5\text{pp}\) đến \(-20.8\text{pp}\) (WB-Ch25,v1 -> v2), ta thu được:\[\Delta A_{\text{agg}} = 0.50(+22.5) + 0.10(-12.5 - 20.83 - 16.67 - 20.83 - 12.5) = +11.25 - 8.33 = \mathbf{+2.92\text{ pp}}.\]Thước đo tổng hợp tăng đẹp từ
81.2% -> 84.2%, nhưng Rủi ro Sản xuất Kỳ vọng (Expected Production Risk) đo đúng thiệt hại tài chính/vận hành:\[\mathcal{R}_{\text{prod}}(m) = \frac{1}{N} \sum_{i=1}^{N} \ell_i \, \mathbb{I}[\text{fail}_i^{(m)}] = \sum_{s=1}^{S} w_s \, \ell_s \, \big(1 - A_s^{(m)}\big)\]lại tăng vọt từ
0.346(83.0 / 240) lên0.537(129.0 / 240,+55.4%)! -
Đảo chiều Tuyệt đối Dưới Dịch chuyển Lưu lượng (Pure Simpson's Paradox): Thậm chí, khi đổi tỷ trọng lấy mẫu giữa hai thời điểm triển khai (\(w_{\text{easy}}: 0.30 \to 0.80\)), tổng hợp điểm số có thể đảo ngược dấu hoàn toàn so với từng phân khúc! Trong
WB-Ch25(demonstrate_simpsons_paradox_traffic_shift,Test 04), dù cả phân khúc dễ (94.0% -> 92.0%,-2.0pp) lẫn phân khúc trọng yếu (78.0% -> 64.0%,-14.0pp) đều suy giảm, điểm tổng hợp vẫn tăng giả tạo:\[A_{\text{agg}}^{(v1)} = 0.30(0.94) + 0.70(0.78) = \mathbf{82.8\%} \;\longrightarrow\; A_{\text{agg}}^{(v2)} = 0.80(0.92) + 0.20(0.64) = \mathbf{86.4\%} \quad (\mathbf{+3.6\text{pp}}).\]
1.2 Phần 2 (Article #5): Hệ Phân loại 6 Chế độ Lỗi Chuẩn MECE & Quy kết Nguyên nhân#
Để biến bảng điểm đánh giá thành bản đồ sửa lỗi kỹ thuật khả thi, mọi thất bại phải được phân hoạch theo chuẩn MECE (Mutually Exclusive, Collectively Exhaustive — Loại trừ lẫn nhau, Bao phủ toàn diện) qua Cây Ưu tiên Nhân quả (Causal Priority Tree). Xác định đúng thứ tự ưu tiên từ thượng nguồn xuống hạ nguồn là bắt buộc để không đổ lỗi sai đội kỹ thuật khi một lỗi thượng nguồn kéo theo triệu chứng thứ phát bên dưới:
-
FM-1—RETRIEVAL_MISS(Lỗi Truy xuất, Chủ sở hữu: Index / Chunking / Hybrid Retriever):Xảy ra khi truy vấn yêu cầu tra cứu tài liệu nhưng phân mục vàng vắng mặt hoàn toàn trong ngữ cảnh Top-\(k\) (\(R@k = 0 \iff \text{GoldInCtx} = 0\)). Mọi ảo giác sinh ra sau bước này đều là triệu chứng thứ phát; nguyên nhân gốc thuộc về bộ phân mảnh (
Fixed-Windowmồ côi), thiếuBM25cho mã hiếm, hay thiếuGraphRAGđa chặng (như đã giải quyết ở Chương 23). Trênv2củaWB-Ch25, có5caRETRIEVAL_MISS(\(P(\text{RetMiss}) = 5/168 = \mathbf{3.0\%}\),9.7%tổng rủi ro). -
FM-4—INSTRUCTION_SCHEMA_VIOLATION(Lỗi Tuân thủ Lược đồ, Chủ sở hữu: Constrained FSM Decoding / Prompt Delimiters):Đầu ra phá vỡ hợp đồng cú pháp hoặc cấu trúc: bọc markdown thừa
```jsonkhi API yêu cầu JSON thuần, sai kiểu dữ liệu, thiếu khóa bắt buộc, sai giá trịenum, hoặc chèn trường lạ bịPydantic v2(extra="forbid") từ chối. Trênv2, chiếm7/24ca nhómstructured_json_api(29.2%,24.5điểm rủi ro =19.0%). -
FM-5—TOOL_SELECTION_ARG_ERROR(Lỗi Công cụ Agent, Chủ sở hữu: Tool Schema / Precondition Policy Guard):Trong quỹ đạo tác tử (agent trajectory), mô hình chọn sai công cụ (
delete_user_profilethay vìissue_refund), truyền tham số sai phạm vi (amount_usd = -50,account_id = "BAD_ACC"), hoặc bỏ qua bước kiểm tra tiên quyết (issue_refundchạy trướcverify_account_ownership). Do trọng số rủi ro hành động cao nhất (\(\ell = 4.5\)),8ca lỗi trênv2(33.3%nhóm Agent) tạo ra36.0điểm rủi ro — đứng #1 toàn hệ thống (27.9%tổng rủi ro)! -
FM-6—MULTITURN_STATE_DRIFT(Lỗi Trôi Trạng thái Đa lượt, Chủ sở hữu: Episodic Memory / Explicit State Checkpointer):Qua các lượt hội thoại \(t = 1 \dots T\), Agent đánh mất ràng buộc người dùng đã chốt ở các lượt đầu (
region=ap-southeast-1,budget_cap=500,compliance=SOC2) và tự ý đổi sang cấu hình mặc định (us-east-1,unlimited). Trênv2, xảy ra ở7/24ca (29.2%,21.0điểm rủi ro =16.3%). -
FM-2—CONTEXT_UTILIZATION_ERROR(Lỗi Tận dụng Ngữ cảnh, Chủ sở hữu: Reranker Ordering / Context Rot Cap):Chỉ kích hoạt khi \(\text{GoldInCtx} = 1\): tài liệu vàng thực sự nằm trong Top-\(k\), nhưng bị đặt ở vùng lõm giữa cửa sổ (Lost-in-the-Middle, Liu et al. 2024, vị trí
index = 2/5) hoặc bị các đoạn nhiễu (distractors) áp đảo khiến LLM tổng hợp sai câu trả lời. Trênv2, có6ca (11.6%rủi ro). -
FM-3—GROUNDEDNESS_HALLUCINATION(Lỗi Ảo giác & Thiếu Căn cứ, Chủ sở hữu: Generator Faithfulness / CRAG Citation Gate):Khi tài liệu vàng đã có mặt đầy đủ và ở vị trí thuận lợi, nhưng mô hình vẫn bịa số liệu/mã chính sách không tồn tại (
[POL-999],99.99%) hoặc phát biểu mâu thuẫn điều khoản gốc ("waives all audit holds"). Trênv2, chiếm5ca (15.5%rủi ro).
Nhờ cây phân hoạch MECE này, tổng số ca lỗi trên từng mô hình cộng lại khớp tuyệt đối 100% (\(\sum_{m=1}^6 N_m = N_{\text{fail}}\): 45 trên v1, 38 trên v2, 8 trên v3), và ta tính được chính xác Xác suất Quy kết Có điều kiện giữa tầng truy xuất và tầng sinh/ngữ cảnh:
Trên v2 của WB-Ch25: \(P(\text{RetMiss}) = \mathbf{3.0\%}\) (\(5/168\)), trong khi \(P(\text{GenFail} \mid \text{GoldInCtx}) = \mathbf{6.8\%}\) (\(11/163\), gồm \(3.7\%\) lỗi tận dụng ngữ cảnh và \(3.1\%\) ảo giác) — lớn gấp đôi lỗi truy xuất!
1.3 Kiểm định Thống kê Ghép cặp (McNemar, Paired Bootstrap CI) & Hiệu chuẩn Giám khảo (Dawid–Skene EM)#
Khi so sánh hai mô hình \(m_1, m_2\) trên cùng một tập \(N_s\) câu hỏi kiểm thử ghép cặp ở phân khúc \(s\), sai số của hai mô hình có tương quan dương mạnh; dùng kiểm định độc lập hai mẫu sẽ làm mất độ nhạy thống kê. Thay vào đó, ta lập bảng \(2 \times 2\) trên các cặp bất đồng:
- \(b\): số mẫu \(m_1\) đạt nhưng \(m_2\) trượt (hồi quy — regressions).
- \(c\): số mẫu \(m_1\) trượt nhưng \(m_2\) đạt (cải thiện — improvements).
Dưới giả thuyết không \(H_0: p_{10} = p_{01}\), Kiểm định Chính xác McNemar (Dietterich, 1998) và thống kê \(\chi^2\) hiệu chỉnh liên tục Edwards tính bằng:
- Trên phân khúc
compliance_citation(n=24) giữav1 -> v2trongWB-Ch25, cób = 5, c = 0\(\implies \chi^2_{\text{cc}} = 3.20, \; p_{\text{McNemar}} = \mathbf{0.0625}\), và Paired Bootstrap 95% CI (2,000lần tái mẫu trên hiệu cặp \((y_i^{(v2)} - y_i^{(v1)}) \times 100\)) đạt[-37.5, -4.2] pp— toàn bộ khoảng tin cậy nằm hoàn toàn bên trái số0, xác nhận suy giảm-20.8pplà có thật chứ không phải nhiễu ngẫu nhiên!
Để đo chất lượng lớp giám khảo LLM cho các ca ngữ nghĩa tinh vi, ta tính hệ số đồng thuận Cohen's \(\kappa = \frac{p_o - p_e}{1 - p_e}\) (loại bỏ xác suất trùng hợp ngẫu nhiên \(p_e\)) và tổng hợp hội đồng \(M=3\) giám khảo bằng thuật toán Dawid–Skene EM ước lượng đồng thời tỷ lệ tiên nghiệm \(\pi_1\), độ nhạy \(\alpha_j = P(V_{ij}=1 \mid Z_i=1)\) và độ đặc hiệu \(\beta_j = P(V_{ij}=0 \mid Z_i=0)\) của từng giám khảo \(j\):
Trong WB-Ch25, khi đánh giá thuần trên 157 ca RAG sống sót qua Tầng 1, giám khảo đơn lẻ ngây thơ chỉ đạt \(\kappa = \mathbf{0.044}\) so với nhãn vàng (Survivor RAG Accuracy = 87.3%, đồng thuận giữa hai giám khảo lẻ \(\kappa(J_1, J_2) = 0.044\)), còn Dawid–Skene EM (khớp thuần trên 157 ca sống sót, không trộn các ca lỗi tất định dễ) khử nhiễu nâng \(\kappa\) lên 0.587 (Survivor RAG Accuracy = 97.5%, Waterfall End-to-End = 98.3%). Về hạch toán API ($0.004/lượt gọi đơn, tương đương $0.012/mẫu cho hội đồng 3 giám khảo): gọi 3 giám khảo cho cả 157 ca RAG tốn 471 lượt ($1.884 — cao hơn 1 giám khảo ngây thơ $0.960!), trong khi định tuyến rủi ro 39 ca RAG Tier-1 sống sót chỉ tốn 117 lượt ($0.468, tiết kiệm -51.25% so với 1 giám khảo $0.960 và -83.75% so với 3 giám khảo toàn bộ $2.880).
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất, Thác Assertion Waterfall & Cẩm nang Quyết định Sửa lỗi#
2.1 Sơ đồ 1: Cây Phân loại 6 Chế độ Lỗi Chuẩn MECE & Quy kết Nhân quả#
2.2 Sơ đồ 2: Phần 3 (Article #5) — Thác Kiểm định Assertion Waterfall (Tất định Trước \(\to\) Giám khảo Hiệu chuẩn Sau)#
2.3 Sơ đồ 3: Biểu đồ Tuần tự Cổng CI/CD Theo Lát cắt (v2 BLOCKED vs v3 APPROVED)#
2.4 Phần 3 & Phần 4 (Article #5): Tập Dữ liệu Vàng Phân tầng & Cẩm nang Quyết định Sửa lỗi Sản xuất (Playbook)#
Một tập dữ liệu vàng (Stratified Golden Dataset) chuẩn sản xuất tuyệt đối không thu thập ngẫu nhiên theo phân phối trò chuyện dễ; nó phải phân tầng tối thiểu 24–50 mẫu có kiểm toán cho mỗi lát cắt rủi ro cao (cùng cặp đầu vào cố định để kiểm định ghép cặp) và kết hợp Thác Kiểm định Assertion Waterfall: mọi bất biến lập trình được (JSON Schema, AST/Regex, hàm kiểm tra SQL/Python hợp lệ, thứ tự tiên quyết công cụ, trạng thái bộ nhớ, thẻ trích dẫn [chunk_id]) phải được kiểm chứng tất định trước ở chi phí $0 (< 1 ms), rồi mới chuyển phần dư ngữ nghĩa tinh vi sang hội đồng giám khảo đã hiệu chuẩn.
Bảng dưới đây tổng hợp Cẩm nang Quyết định Sửa lỗi Sản xuất (Production Decision Playbook) ánh xạ từ phân rã lỗi v2 của WB-Ch25 sang hành động kỹ thuật cụ thể:
| Thứ tự Ưu tiên | Chế độ Lỗi (MECE) |
Rủi ro trên v2 (% Tổng Rủi ro) |
Tín hiệu Kiểm chứng Nhanh (Assertion) |
Can thiệp Kiến trúc Chuẩn SOTA 2026 (Playbook) |
|---|---|---|---|---|
| #1 | TOOL_SELECTION_ARG_ERROR (FM-5) |
36.0 (27.9%, 8 ca) |
Kiểm tra DAG thứ tự (verify trước refund) + kiểu/miền tham số ($0) |
Siết lược đồ công cụ MCP, đặt Precondition Guard chặn hành động ghi/hoàn tiền thiếu xác thực & chạy thử trong sandbox |
| #2 | INSTRUCTION_SCHEMA_VIOLATION (FM-4) |
24.5 (19.0%, 7 ca) |
Trình phân tích json.loads + jsonschema + Pydantic v2 ($0) |
Chuyển sang Constrained FSM / Grammar Decoding (Outlines/xgrammar) và chuẩn hóa phân tách prompt |
| #3 | MULTITURN_STATE_DRIFT (FM-6) |
21.0 (16.3%, 7 ca) |
Đối chiếu khóa-giá trị ràng buộc region, budget, compliance ($0) |
Tách Explicit Typed State Checkpointer ra ngoài lịch sử hội thoại trượt (rolling transcript) |
| #4 | GROUNDEDNESS_HALLUCINATION (FM-3) |
20.0 (15.5%, 5 ca) |
Tầng 1 kiểm thẻ [chunk_id] + số liệu; Tầng 2 Dawid–Skene EM |
Bật cổng từ chối CRAG (\(\tau_{\text{low}} = 0.38\)) + ClaimGroundednessAuditor ở Chương 23 |
| #5 | CONTEXT_UTILIZATION_ERROR (FM-2) |
15.0 (11.6%, 6 ca) |
Kiểm chứng GoldInCtx = 1 + độ phủ ý chính ở Tầng 2 |
Tái xếp hạng Cross-Encoder đẩy chứng cứ lên đầu/cuối cửa sổ & khóa ngân sách ngữ cảnh ở ngưỡng 20%–40% chống Context Rot |
| #6 | RETRIEVAL_MISS (FM-1) |
12.5 (9.7%, 5 ca) |
Kiểm tra gold_chunk_id in retrieved_chunk_ids ($0) |
Nâng cấp Contextual Retrieval + Hybrid BM25/Dense RRF + GraphRAG PPR (Chương 23) |
Kinh nghiệm Kiến trúc SOTA 2025–2026 (Agentic Trajectory Eval, Context Rot, BFCL v4 & Minh bạch Proxy):
- Đánh giá Quỹ đạo Agent (
BFCL v4/ToolBench) Không Thể Chỉ Nhìn Đáp án Cuối: Một Agent có thể đoán đúng câu trả lời cuối cùng dù đã gọi sai công cụ hoặc bỏ qua bước xác thực quyền (verify_account_ownership). Chuẩn đánh giá Agent hiện đại (BFCL v4với 22 nhóm tác vụ đa lượt & bộ nhớ) bắt buộc kiểm tra State-Delta + Tool-DAG Invariants tại từng bước thực thi trong sandbox. - Tại sao Tầng Tất định Phải Chặn Trước Mọi LLM Judge: Ngay cả
GPT-4-class Judge cũng có độ lệch vị trí/độ dài và dễ bỏ qua lỗi sai 1 ký tự trongticket_idregex (TCK-0001), trích dẫn bịa ([REG-404]không thuộcretrieved_chunk_ids) hoặc ép kiểu boolean/âm trong tham số API (amount_usd = -50). Bộ kiểm chứngjsonschema+Pydantic v2+ đối chiếu trích dẫn phát hiện những lỗi này với độ chính xác100.0%ở tốc độ~0.16 msvà$0chi phí. - Ghi chú Minh bạch về Mô phỏng Ngoại tuyến: Toàn bộ thí nghiệm trong
WB-Ch25chạy trên bộ trace và phiếu giám khảo proxy tổng hợp ngoại tuyến có kiểm soát để bảo đảm tính tái lập tuyệt đối (seed = 42,0phụ thuộc API/GPU ngoài), trong khi cùng chính hàmclassify_sample_failure_mode,run_deterministic_assertions,compute_mcnemar_test,dawid_skene_emvàevaluate_ci_release_gateđược thiết kế để nạp trực tiếp log JSON thực tế từ môi trường sản xuất.
2.5 Mở rộng SOTA 2025–2026: Độ tin cậy Đa lượt, Bẫy Benchmark & Hiệu chuẩn Giám khảo Liên tục#
Bên cạnh khung nền tảng 6 chế độ lỗi và Assertion Waterfall, thực tiễn đánh giá hệ thống AI giai đoạn 2025–2026 bổ sung năm trụ cột kỹ thuật bắt buộc đối với RAG và Agent sản xuất:
-
Sụp đổ Độ tin cậy Đa lượt Thử (
τ-bench&τ²-bench:pass^kvspass@k):- Các benchmark sinh mã truyền thống dùng
pass@k(xác suất ít nhất1trongklần thử đúng) — thước đo tăng dần theokvà tạo cảm giác an toàn giả tạo cho Agent. Trái lại,τ-bench(Yao et al., 2024) đưa rapass^k: xác suất Agent hoàn thành đúng quy trình và khớp trạng thái CSDL đích trên cảklần chạy liên tiếp (\(p^k\) nếu độc lập). Trên thực tế doanh nghiệp, tỷ lệ thành công giảm theo hàm mũ khi chuỗi hành động kéo dài (nhiều mô hình hàng đầu dù đạt gần50%ởpass^1nhưng rơi xuống dưới25%ởpass^8). - Mở rộng
τ²-bench(Barres et al., 2025) mô hình hóa bài toán điều khiển kép (dual-control Dec-POMDP), nơi cả Agent lẫn người dùng mô phỏng đều gọi công cụ trên trạng thái dùng chung (ví dụ hướng dẫn khách hàng kiểm tra thiết bị viễn thông), cho phép bóc tách rạch ròi lỗi suy luận nội tại khỏi lỗi phối hợp giao tiếp đa lượt.
- Các benchmark sinh mã truyền thống dùng
-
Đứt gãy Khung Vận hành (
TraceTrial-Bench) & Giới hạn Giám sát Chuỗi Suy luận (CoT Monitorability):TraceTrial-Benchtách đánh giá thành hai lớp độc lập: Agent Layer (hoàn thành tác vụ) và Harness Layer (độ tin cậy 7 thành phần: Context, Execution, Governance, Lifecycle, Observability, Tools, Verification). Thực nghiệm trên3,420lượt chạy cho thấy31.1%lượt hoàn thành đúng mục tiêu vẫn vi phạm ít nhất một tiêu chí độ tin cậy của harness (chỉ8.4%đạt trọn vẹn cả hai lớp) — chứng minh điểm kết quả cuối không phản ánh sức khỏe hệ thống vận hành.CoT Monitorability: Các nghiên cứu kiểm toán chuỗi suy luận trên mô hình lý luận lớn (Large Reasoning Models như Claude 3.7 Sonnet, DeepSeek-R1) chỉ ra rằng khi bị tác động bởi gợi ý ẩn hay thiên kiến ngầm làm thay đổi quyết định, chuỗiCoTchỉ thừa nhận yếu tố dẫn hướng này trong25%–39%trường hợp — tức61%–75%suy luận có dấu hiệu che giấu hoặc hợp thức hóa sau (post-hoc rationalization). Do đó, giám sátCoTchỉ là lớp tín hiệu phụ, tuyệt đối không thay thế kiểm chứng trạng thái tất định và sandbox.
-
Hội đồng Đa họ
PoLL, Hiệu chuẩnRogan–Gladen(Youden \(\Delta J\)) /PPI++,BFCL v4&OpenTelemetry gen_ai.evaluation.*:PoLL(Panel of LLM Evaluators): Thay giám khảo đơn lẻ đồng họ bằng hội đồng đa họ mô hình (cross-family ensemble, như đã mô phỏng ởWB-Ch25) để triệt tiêu thiên vị tự ưu ái (self-enhancement), vị trí và độ dài.- Hiệu chuẩn Giám khảo Không Hoàn hảo (
Rogan–Gladen&PPI++): Một giám khảo có độ nhạy \(\text{se}\) và độ đặc hiệu \(\text{sp}\) chưa hoàn hảo sẽ nén chênh lệch thực giữa hai mô hình theo chỉ số Youden \(J = \text{se} + \text{sp} - 1\) (\(\Delta_{\text{obs}} = J \cdot \Delta_{\text{true}}\)). Phép hiệu chuẩnRogan–Gladenđảo ngược nhiễu phân loại từ tập hiệu chuẩn nhãn người (\(\hat{\theta} = \frac{\hat{p}_{\text{obs}} + \text{sp} - 1}{\text{se} + \text{sp} - 1}\)) để giữ tính không chệch kể cả khi dữ liệu sản xuất dịch chuyển phân phối; trong khiPPI++(Prediction-Powered Inference++) kết hợp nhãn người quy mô nhỏ với dự đoán giám khảo quy mô lớn qua hàm ảnh hưởng hiệu quả để thu hẹp phương sai và kiểm định giả thuyết có khoảng tin cậy hợp lệ. - Chuẩn Giao thức Gọi Hàm & Theo dõi (
BFCL v4&OpenTelemetry):BFCL v4mở rộng đánh giá tool-use qua22hạng mục đa lượt, gọi song song, thiếu tham số và quản lý bộ nhớ; còn chuẩnOpenTelemetrygen_ai.evaluation.*quy chuẩn hóa sự kiệngen_ai.evaluation.resultcùng thuộc tínhgen_ai.evaluation.namevàgen_ai.evaluation.explanationgắn trực tiếp lên spaninvoke_agent/execute_tool.
-
The SWE-Bench Illusion& BẫyDocker Grader:- Nghiên cứu The SWE-Bench Illusion chứng minh rò rỉ dữ liệu tiền huấn luyện giúp mô hình nhớ vị trí tệp lỗi chính xác
76%chỉ từ mô tả issue (không cần xem mã nguồn), nhưng rớt xuống53%trên kho mã ngoài tập benchmark. Song song, bẫyDocker graderxảy ra khi bộ kiểm thử container thiếu cô lập, sót lịch sử commit/môi trường hoặc bộ test quá lỏng (under-specified), làm phồng điểm benchmark giả tạo mà không đo được năng lực kỹ thuật phần mềm thực chất.
- Nghiên cứu The SWE-Bench Illusion chứng minh rò rỉ dữ liệu tiền huấn luyện giúp mô hình nhớ vị trí tệp lỗi chính xác
-
Kiểm soát
Judge Drift&Eval RotBằng Tập Neo Bất biến + Kiểm định Tuần tựe-process:- Khi chạy LLM-as-a-Judge liên tục trên sản xuất, một bản cập nhật trọng số âm thầm từ nhà cung cấp API hay thay đổi prompt nhỏ gây ra
Judge Drift/Eval Rot— làm người vận hành không thể phân biệt mô hình sản phẩm tụt chất lượng hay thước đo giám khảo bị trôi. Chuẩn kiểm soát hiện đại ghép xen kẽ một tập neo con người bất biến (immutable human anchor set) cùng kiểm định tuần tựe-process/e-value(anytime-valid martingale testing), giúp tách bạch chính xác nguyên nhân ({system, judge, none}) tại mọi thời điểm dừng mà không bị nổ báo động giả như các kiểm định cửa sổ trượt truyền thống.
- Khi chạy LLM-as-a-Judge liên tục trên sản xuất, một bản cập nhật trọng số âm thầm từ nhà cung cấp API hay thay đổi prompt nhỏ gây ra
Trụ cột 3 — Hệ sinh thái 2026 & Mã nguồn Thực thi Độc lập#
Đoạn mã độc lập dưới đây chạy hoàn toàn ngoại tuyến trong .venv (Python 3.12, numpy, scipy, jsonschema, pydantic v2), chứng minh trực tiếp bốn cơ chế nền tảng của Chương 25: (1) Đảo chiều Simpson & Ảo ảnh Điểm Tổng hợp, (2) Cây Ưu tiên MECE chống đếm trùng RETRIEVAL_MISS, (3) Kiểm chứng Tất định < 1 ms (jsonschema + Tool Precondition DAG), và (4) Kiểm định Chính xác McNemar + Cổng SliceNonRegressionGate chặn v2 dù cổng tổng hợp cho PASS:
"""Pillar 3 Executable Specimen: Simpson Mirage, 6-Mode MECE, Det Waterfall & McNemar CI Gate."""
from __future__ import annotations
import json
import re
import time
from typing import Any, Literal
import jsonschema
from pydantic import BaseModel, ConfigDict, Field
from scipy.stats import binomtest
class SliceGateRule(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
max_drop_pp: float = Field(default=3.0, ge=0.0)
tier1_floor: float = Field(default=0.78, ge=0.0, le=1.0)
mcnemar_alpha: float = Field(default=0.05, gt=0.0, le=0.25)
def classify_mece(
requires_retrieval: bool,
gold_in_ctx: bool,
schema_ok: bool,
tool_ok: bool,
state_ok: bool,
ctx_util_ok: bool,
grounded_ok: bool,
) -> Literal[
"PASS",
"RETRIEVAL_MISS",
"INSTRUCTION_SCHEMA_VIOLATION",
"TOOL_SELECTION_ARG_ERROR",
"MULTITURN_STATE_DRIFT",
"CONTEXT_UTILIZATION_ERROR",
"GROUNDEDNESS_HALLUCINATION",
]:
if requires_retrieval and not gold_in_ctx:
return "RETRIEVAL_MISS"
if not schema_ok:
return "INSTRUCTION_SCHEMA_VIOLATION"
if not tool_ok:
return "TOOL_SELECTION_ARG_ERROR"
if not state_ok:
return "MULTITURN_STATE_DRIFT"
if requires_retrieval and gold_in_ctx and not ctx_util_ok:
return "CONTEXT_UTILIZATION_ERROR"
if not grounded_ok:
return "GROUNDEDNESS_HALLUCINATION"
return "PASS"
def run_ch25_specimen() -> dict[str, Any]:
"""Demonstrate Simpson Mirage, MECE priority, deterministic checks, and McNemar CI gate."""
# 1. Pure Simpson Traffic Shift: both slices drop, yet aggregate climbs +3.6pp
agg_v1 = 0.30 * 0.94 + 0.70 * 0.78
agg_v2 = 0.80 * 0.92 + 0.20 * 0.64
simpson_delta_pp = round((agg_v2 - agg_v1) * 100.0, 2)
# 2. MECE priority prevents blaming Generator when Retrieval already missed gold chunk
mece_label = classify_mece(
requires_retrieval=True,
gold_in_ctx=False,
schema_ok=True,
tool_ok=True,
state_ok=True,
ctx_util_ok=False,
grounded_ok=False,
)
# 3. Layer-1 Deterministic Assertions (<1ms, $0): JSON Schema + Tool Precondition DAG
t0 = time.perf_counter_ns()
schema = {
"type": "object",
"additionalProperties": False,
"required": ["decision", "ticket_id"],
"properties": {
"decision": {"type": "string", "enum": ["APPROVE", "REJECT"]},
"ticket_id": {"type": "string", "pattern": "^TCK-[0-9]{4}$"},
},
}
schema_caught = False
try:
jsonschema.validate({"decision": "UNKNOWN", "ticket_id": "TCK-1001"}, schema)
except jsonschema.ValidationError:
schema_caught = True
trace = ["issue_refund"] # missing prerequisite 'verify_account_ownership'
tool_dag_caught = "verify_account_ownership" not in trace
retrieved_ids = ["DOC-101", "SEC-204"]
fabricated_cites = [
cid for cid in re.findall(r"\[([A-Z]+-\d+)\]", "Policy [DOC-101] overrides [REG-404].")
if cid not in retrieved_ids
]
det_ms = round((time.perf_counter_ns() - t0) / 1_000_000.0, 4)
# 4. McNemar Exact Test & Slice CI Gate vs Naive Aggregate Gate
# Compliance slice (n=24): v1 22/24 (91.7%) -> v2 17/24 (70.8%), discordant b=5, c=0
b_reg, c_imp = 5, 0
mcnemar_p = round(float(binomtest(min(b_reg, c_imp), b_reg + c_imp, 0.5).pvalue), 4)
rule = SliceGateRule()
compliance_delta_pp = round((17.0 / 24.0 - 22.0 / 24.0) * 100.0, 2)
naive_overall_delta_pp = round((202.0 / 240.0 - 195.0 / 240.0) * 100.0, 2)
naive_passes = naive_overall_delta_pp >= -1.0
slice_gate_passes = (
compliance_delta_pp >= -rule.max_drop_pp
and (17.0 / 24.0) >= rule.tier1_floor
and not (compliance_delta_pp < 0.0 and mcnemar_p < rule.mcnemar_alpha)
)
return {
"simpson_aggregate_jump_pp": simpson_delta_pp,
"mece_upstream_root_cause": mece_label,
"det_json_schema_caught": schema_caught,
"det_tool_dag_caught": tool_dag_caught,
"det_fabricated_citations": fabricated_cites,
"det_latency_ms": det_ms,
"compliance_mcnemar_p": mcnemar_p,
"naive_aggregate_gate_passed": naive_passes,
"slice_non_regression_gate_passed": slice_gate_passes,
}
if __name__ == "__main__":
print(json.dumps(run_ch25_specimen(), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (WB-Ch25: failure_mode_eval_lab) & Rubric Kiểm thử#
4.1 Kiến trúc Hai Tầng của WB-Ch25#
Toàn bộ mã nguồn thực nghiệm được đóng gói tại labs/ch25-failure-mode-eval-workbench/README.md dưới gói failure_mode_eval_lab (Python 3.12, 100% ngoại tuyến, tất định seed=42, khóa 32 gói trong uv.lock, cấm tuyệt đối pickle/joblib):
- Tầng 1 (
failure_taxonomy_and_metrics.py— Toán học Phân loại & Thống kê Ghép cặp):- Định nghĩa hợp đồng
Pydantic v2(extra="forbid",strict=True) choEvalSampleRecord,ToolCallTrace,CandidateTraceClassification,SliceComparisonStatsvàSimpsonReversalResult. - Tạo tập vàng ghép cặp
240mẫu qua6phân khúc chov1_baseline,v2_aggregate_miragevàv3_remediated; chạy bộ phân loại nhân quảclassify_sample_failure_mode,compute_conditional_fault_attribution,compute_mcnemar_test,paired_bootstrap_delta_ci,compute_cohens_kappavàdawid_skene_em.
- Định nghĩa hợp đồng
- Tầng 2 (
golden_eval_and_ci_gates.py— Thác Kiểm định & CổngCI/CDTheo Lát cắt):- Thực thi kiểm chứng tất định
run_deterministic_assertions(jsonschema,ToolCallTraceDAG, trạng thái đa lượt, thẻ trích dẫn & số liệu chính xác), so sánh hiệu năngrun_assertion_waterfall_benchmarkvsNaive Always-LLM-Judge, đánh giá cổng phát hànhevaluate_ci_release_gate, và sắp hạng hành động sửa lỗi quabuild_remediation_playbook.
- Thực thi kiểm chứng tất định
4.2 Bảng Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch25_wb25_results.json)#
A. Đối chứng Phân khúc Ghép cặp (N = 240, 2,000 Bootstrap Resamples):
Phân khúc (Eval Slice, \(n\), Trọng số \(\ell_s\)) |
v1 -> v2 (Delta / 95% CI) |
McNemar p (v1 vs v2) |
v3 Remediated (Delta vs v1) |
|---|---|---|---|
Easy Paraphrase QA (n=120, w=1.0) |
75.8% -> 98.3% (+22.5pp [+15.0, +30.0]) |
p = 0.0000 (b=0, c=27) |
96.7% (+20.8pp) |
Long-Context Needle RAG (n=24, w=2.5) |
83.3% -> 70.8% (-12.5pp [-25.0, +0.0]) |
p = 0.2500 (b=3, c=0) |
95.8% (+12.5pp) |
Compliance & Citation Audit (n=24, w=4.0) |
91.7% -> 70.8% (-20.8pp [-37.5, -4.2]) |
p = 0.0625 (b=5, c=0) |
95.8% (+4.2pp) |
Structured JSON API Contract (n=24, w=3.5) |
87.5% -> 70.8% (-16.7pp [-33.3, -4.2]) |
p = 0.1250 (b=4, c=0) |
100.0% (+12.5pp) |
Agent Tool-Use & Preconditions (n=24, w=4.5) |
87.5% -> 66.7% (-20.8pp [-37.5, -4.2]) |
p = 0.0625 (b=5, c=0) |
95.8% (+8.3pp) |
Multi-Turn State & Memory (n=24, w=3.0) |
83.3% -> 70.8% (-12.5pp [-25.0, +0.0]) |
p = 0.2500 (b=3, c=0) |
95.8% (+12.5pp) |
OVERALL AGGREGATE (N=240) |
81.2% -> 84.2% (+2.9pp MIRAGE) |
Risk 0.346 -> 0.537 (+55.4%) |
96.7% (+15.4pp, Risk 0.075) |
B. Phân rã 6 Chế độ Lỗi MECE & Rủi ro Sản xuất trên v2_aggregate_mirage (38 Ca lỗi, 129.0 Tổng Rủi ro):
Chế độ Lỗi (MECE) |
Số ca / Tỷ trọng Lỗi | Thiệt hại Rủi ro (% Rủi ro) | Chủ sở hữu Kỹ thuật Chính |
|---|---|---|---|
RETRIEVAL_MISS (FM-1) |
5 (13.2%) |
12.5 (9.7%) |
Index / Chunking / Hybrid Retriever |
CONTEXT_UTILIZATION_ERROR (FM-2) |
6 (15.8%) |
15.0 (11.6%) |
Reranker Ordering / Context Window Budget |
GROUNDEDNESS_HALLUCINATION (FM-3) |
5 (13.2%) |
20.0 (15.5%) |
Generator Faithfulness / CRAG Citation Gate |
INSTRUCTION_SCHEMA_VIOLATION (FM-4) |
7 (18.4%) |
24.5 (19.0%) |
Constrained FSM Decoding / Prompt Delimiters |
TOOL_SELECTION_ARG_ERROR (FM-5) |
8 (21.1%) |
36.0 (27.9%) |
Tool Schema / Precondition Policy Guard |
MULTITURN_STATE_DRIFT (FM-6) |
7 (18.4%) |
21.0 (16.3%) |
Episodic Memory / Explicit State Checkpointer |
C. Đối chứng Thác Assertion Waterfall (v2) & Cổng Phát hành CI/CD (v2 BLOCKED -> v3 APPROVED):
| Kiến trúc / Cổng Kiểm định | Hiệu năng Bắt lỗi / Phán quyết | Chi phí & Độ trễ / Lượt gọi | Độ tin cậy & Diễn giải |
|---|---|---|---|
| Tầng 1: Tất định Trước | Bắt 33/38 lỗi (86.8%) |
0 lượt LLM ($0.00, ~0.16 ms/mẫu) |
100% tất định, không đổ lỗi sai |
| Naive Single Always-LLM-Judge | Survivor RAG Acc = 87.3% |
240 lượt ($0.960) | 720 lượt 3J ($2.880) |
\(\kappa(J_1, J_2) = 0.044\), \(\kappa(J_1, \text{True}) = \mathbf{0.044}\) |
Assertion Waterfall (Det -> Dawid-Skene) |
Survivor RAG = 97.5% | E2E = 98.3% |
Full RAG 157×3=471 ($1.884) | 39×3=117 Tier-1 ($0.468, -51.25% vs 1J / -83.75% vs 3J) |
Dawid–Skene \(\kappa(\text{EM}, \text{True}) = \mathbf{0.587}\) |
v2_aggregate_mirage Gate |
Naive: PASS | Slice: BLOCKED |
5/5 lát cắt Tier-1 vi phạm |
Tỷ lệ rủi ro 1.55x > 1.05x |
v3_remediated Gate |
Naive: PASS | Slice: APPROVED |
0 lát cắt vi phạm (96.7% Tier-1) |
Rủi ro giảm -86.0% xuống 0.075 (0.22x) |
4.3 Hợp đồng 20 Bài kiểm thử Tự động (tests/test_failure_mode_eval_lab.py)#
| STT | Tên Hàm Kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc |
|---|---|---|
1 |
test_01_ast_no_unsafe_deserializers |
Quét AST toàn bộ src/ và scripts/, cấm pickle, joblib, cloudpickle, dill, shelve, marshal |
2 |
test_02_pydantic_v2_strict_contracts_forbid_extra_fields |
CIGatePolicy, ToolCallTrace, EvalSampleRecord (extra="forbid", strict=True) từ chối khóa lạ & biên sai |
3 |
test_03_stratified_suite_size_and_slice_integrity |
Khớp đúng 240 mẫu ghép cặp (120, 24, 24, 24, 24, 24) đồng nhất mã ID giữa v1, v2, v3 |
4 |
test_04_simpsons_paradox_aggregate_mirage_and_traffic_shift |
Chứng minh cả v1->v2 Aggregate Mirage (+2.9pp che -16.7pp Tier-1, Risk >1.5x) lẫn đảo chiều Simpson thuần túy |
5 |
test_05_mece_priority_causal_attribution_prevents_double_counting |
Mẫu thiếu retrieval & ảo giác chỉ gán nhãn chính RETRIEVAL_MISS, không tính CONTEXT_UTILIZATION_ERROR |
6 |
test_06_all_six_canonical_failure_modes_are_detected_distinctly |
Kích hoạt chính xác độc lập từng chế độ trong 6 chế độ FM-1..FM-6 kèm chủ sở hữu |
7 |
test_07_conditional_fault_attribution_probabilities_on_v2 |
Tổng ca lỗi MECE == 38, tổng tỷ trọng rủi ro == 1.0, \(P(\text{GenFail} \mid \text{GoldInCtx}) > P(\text{RetMiss})\) |
8 |
test_08_mcnemar_exact_and_paired_bootstrap_ci |
Kiểm chứng McNemar p & Paired Bootstrap 95% CI cho easy_paraphrase, compliance_citation, agent_tool_use |
9 |
test_09_hypothesis_invariants_mcnemar_kappa_bootstrap |
Bất biến ngẫu nhiên Hypothesis (25 kịch bản): \(0 \le p \le 1\), \(\chi^2_{\text{cc}} \ge 0\), \(\text{CI}_L \le \Delta \le \text{CI}_H\), \(\kappa_{\text{self}} = 1.0\) |
10 |
test_10_deterministic_assertions_catch_json_tool_state_and_citations |
Bắt lỗi enum JSON sai & lỗi gọi issue_refund trước verify_account_ownership trong < 25 ms ($0) |
11 |
test_11_assertion_waterfall_saves_judge_calls_and_catches_majority_at_zero_cost |
Tầng 1 bắt >= 80% (86.8%) lỗi của v2 tại $0, < 1 ms/mẫu; hạch toán chính xác 3x 3-judge ($1.884 vs $0.468, -51.25% / -83.75%) |
12 |
test_12_dawid_skene_calibration_lifts_kappa_over_naive_single_judge |
Dawid–Skene EM khớp thuần trên 157 ca sống sót vượt giám khảo lẻ (κ: 0.044 -> 0.587) & khôi phục >= 95% khi có giám khảo đảo nhãn |
13 |
test_13_ci_gate_naive_passes_mirage_but_slice_gate_blocks_v2 |
Cổng tổng hợp cho v2 PASS, nhưng SliceNonRegressionGate chặn 5 lát cắt Tier-1 & risk_ratio > 1.5x |
14 |
test_14_ci_gate_approves_remediated_v3_and_slashes_risk |
v3_remediated đạt >= 95% (96.7%), 0 lát cắt chặn, giảm rủi ro xuống < 0.30x (0.22x) |
15 |
test_15_remediation_playbook_prioritizes_highest_risk_modes |
build_remediation_playbook sắp giảm dần đúng theo risk_loss (TOOL_SELECTION_ARG_ERROR đứng đầu) |
16 |
test_16_full_benchmark_determinism |
Chạy run_full_ch25_wb25_benchmark(seed=42, quick=True) hai lần cho kết quả trùng khớp tuyệt đối |
17 |
test_17_error_handling_for_mismatched_paired_sequences |
Ném ValueError tường minh khi độ dài chuỗi ghép cặp không khớp hoặc ma trận vote < 2 giám khảo |
18 |
test_18_cli_artifact_and_workbench_panels_schema |
CLI --quick xuất JSON hợp lệ chứa đúng 6 KPI, 4 biểu đồ cột và 4 bảng workbench_panels |
19 |
test_19_generic_fabricated_citation_verification |
Kiểm chứng regex [A-Z]+-\d+ so với retrieved_chunk_ids: chặn mọi mã bịa (ví dụ [REG-404]), cho qua mã đã truy xuất |
20 |
test_20_mcnemar_alpha_governs_borderline_ci_gate_verdict |
Chứng minh siết/nới CIGatePolicy.mcnemar_alpha (0.01 vs 0.05) đảo phán quyết cổng CI/CD trên ca biên delta = -2.5pp |
Trụ cột 5 — Văn liệu Nền tảng, Ôn tập Nhanh & Hệ thống Bài tập Chuyên sâu#
5.1 Mười Công trình Học thuật & Tiêu chuẩn Kỹ nghệ Nền tảng (1998–2026)#
- Es, S., James, J., Espinosa-Anke, L. & Schockaert, S. (EACL 2024).
RAGAS: Automated Evaluation of Retrieval Augmented Generation — tách bạch đánh giá tầng truy xuất (Context Precision/Recall) và tầng sinh văn bản (Faithfulness/Answer Relevance). - Husain, H. & Anthropic Engineering (2024–2025). Your AI Product Needs Evals / Building Effective Agents — phương pháp luận cốt lõi của Chuyên đề #5: phân tích theo chế độ lỗi (Failure-Mode Taxonomy), xây dựng Golden Datasets phân tầng và ưu tiên kiểm chứng tất định trước giám khảo LLM.
- Liu, N. F. et al. (TACL 2024). Lost in the Middle: How Language Models Use Long Contexts — chứng minh đường cong chữ U trong tận dụng ngữ cảnh dài, giải thích chế độ lỗi
CONTEXT_UTILIZATION_ERRORngay cả khi đoạn vàng có mặt trong ngữ cảnh. - Dietterich, T. G. (Neural Computation 1998) & Dror, R. et al. (ACL 2018). Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms & The Hitchhiker's Guide to Testing Statistical Significance in NLP — cơ sở lý thuyết của kiểm định ghép cặp
McNemarvà tái mẫuPaired Bootstrap. - Willard, B. T. & Louf, R. (2023,
Outlines) &Pydantic v2Strict Contracts. Efficient Guided Generation for Large Language Models — sử dụng máy trạng thái hữu hạn (FSM) giải mã có ràng buộc ngữ pháp để triệt tiêuINSTRUCTION_SCHEMA_VIOLATION. - Yan, F. et al. (
BFCL v4, UC Berkeley, 2024–2026) & Yao, S. / Barres, V. et al. (τ-bench&τ²-bench, Sierra, 2024–2025). Berkeley Function Calling Leaderboard (22hạng mục agentic đa lượt & bộ nhớ) và chuẩn đo độ tin cậy đa lượtpass^k/ môi trường điều khiển kép Dec-POMDP. - Verga, P. et al. (
PoLL, 2024) & Rogan–Gladen /PPI++Calibration (Angelopoulos et al., 2024–2026). Hội đồng giám khảo đa họ chống tự thiên vị và phép hiệu chuẩn nghịch đảo Youden \(J\) / Prediction-Powered Inference++ cho giám khảo không hoàn hảo. TraceTrial-Bench&CoT MonitorabilityStudies (2025–2026). Tách biệt tỷ lệ hoàn thành tác vụ của Agent khỏi31.1%đứt gãy harness, đồng thời cảnh báo tỷ lệ thừa nhận yếu tố dẫn hướng ẩn trongCoTchỉ đạt25%–39%.- The SWE-Bench Illusion &
Docker GraderPitfalls (2025–2026). Bóc trần hiện tượng ghi nhớ bản vá tiền huấn luyện (76%vs53%đoán đường dẫn tệp ngoài tập) và rủi ro rò rỉ/kiểm thử lỏng trong container grader. OpenTelemetry gen_ai.evaluation.*&Anytime-Valid Judge Drift(e-process, 2025–2026). Chuẩn sự kiện theo dõigen_ai.evaluation.resultkết hợp tập neo con người bất biến và kiểm định tuần tựe-processphân biệtSystem DriftkhỏiEval Rot.
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
Q1(Ảo ảnh Điểm Tổng hợp & Nghịch lý Simpson): Điểm trung bình tăng+2.9pp(81.2% -> 84.2%) có thể che giấu mức sụt-20.8pptrên các lát cắtTier-1và làm Rủi ro Sản xuất Kỳ vọng tăng+55.4%; dịch chuyển tỷ trọng câu dễ (30% -> 80%) còn tạo đảo chiều Simpson (+3.6ppdù mọi lát cắt đều giảm).Q2(Cây Ưu tiênMECE): Khi thiếu chứng cứ trong Top-\(k\), gán duy nhất nhãn gốcRETRIEVAL_MISStránh đếm trùng vớiGROUNDEDNESS_HALLUCINATIONvà tách rạch ròi \(P(\text{RetMiss}) = 3.0\%\) khỏi \(P(\text{GenFail} \mid \text{GoldInCtx}) = 6.8\%\).Q3(CONTEXT_UTILIZATION_ERRORvsRETRIEVAL_MISS): ỞFM-2, tài liệu vàng đã có mặt (GoldInCtx = True), nhưng bị kẹp ở giữa (Lost-in-the-Middle) hoặc bị nhiễu (Context Rot) — khắc phục bằngCross-Encoderđẩy lên hai biên và giới hạn mật độ ngữ cảnh20%–40%.Q4(Ba Chế độ Lỗi Cấu trúc & AgentFM-4..FM-6): Trênv2,TOOL_SELECTION_ARG_ERROR(27.9%rủi ro),INSTRUCTION_SCHEMA_VIOLATION(19.0%) vàMULTITURN_STATE_DRIFT(16.3%) chiếm63.2%tổng rủi ro sản xuất.Q5(McNemar&Paired Bootstrap CI): Đánh giá ghép cặp trên cùng câu hỏi yêu cầu kiểm định cặp bất đồngMcNemar((b=5, c=0) -> p=0.0625) vàPaired Bootstrap 95% CI([-37.5, -4.2] pp) để giữ nguyên hiệp phương sai mẫu.Q6(Tầng Tất định trongAssertion Waterfall): Chạyjsonschema,Pydantic v2, kiểm tra DAG tiên quyết công cụ, ràng buộc state slots và thẻ[TAG-123]mất~0.16 ms/mẫu với chi phí$0, bắt ngay86.8%(33/38) toàn bộ lỗi củav2.Q7(Dawid–Skene EM& Hạch toán3x3-Judge): Chỉ định tuyến ca RAGTier-1sống sót qua Tầng 1 (39 × 3 = 117lượt =$0.468) cắt giảm-51.25%chi phí so với 1 giám khảo ($0.960) và-83.75%so với 3 giám khảo toàn bộ ($2.880), trong khi gọi 3 giám khảo cả157ca RAG tốn$1.884(471lượt);Dawid–Skene EMkhớp thuần trên157ca sống sót nâng \(\kappa\) từ0.044 -> 0.587(RAG Acc: 87.3% -> 97.5%,E2E = 98.3%).Q8(SliceNonRegressionGate& Playbook): Cổng phân khúc chặnv2(5/5lát cắtTier-1vi phạm, Risk1.55x), và áp dụng Playbook sửa lỗi theo từng chế độ đưav3lên96.7%(Risk0.075,-86.0%,APPROVED).
5.3 Sáu Bài tập Chuyên sâu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Chứng minh Ảo ảnh Điểm Tổng hợp & Nghịch lý Simpson: Tính điểm tổng hợp và Rủi ro Sản xuất Kỳ vọng chov1vsv2; tái hiện đảo chiều dấu dưới dịch chuyển tỷ trọng30% -> 80%trongTest 04. - Bài tập 2 (
15%) — Thiết kế Cây Ưu tiên 6 Chế độ LỗiMECE& Quy kết Có điều kiện: Giải thích thứ tự ưu tiên từRETRIEVAL_MISSđếnGROUNDEDNESS_HALLUCINATIONvà tính chính xác \(P(\text{RetMiss})\) vs \(P(\text{GenFail} \mid \text{GoldInCtx})\) (Tests 05–07). - Bài tập 3 (
20%) — Kiểm định Chính xácMcNemar&Paired Bootstrap 95% CI: Lập bảng \((b, c)\) chocompliance_citationvàeasy_paraphrase, tính p-value hai phía và kiểm tra bất biếnHypothesiscùngmcnemar_alpha(Tests 08–09, 20). - Bài tập 4 (
20%) — Xây dựng ThácAssertion Waterfall& Hiệu chuẩnDawid–Skene EM: Cài đặt bộ kiểm tra tất định< 1 msvà hội đồng 3 giám khảoDawid–Skene EMkhớp thuần trên ca sống sót, chứng minh hạch toán3xchi phí và mức tăng \(\kappa\) (Tests 10–12, 19). - Bài tập 5 (
15%) — Thiết kế CổngCI/CD Non-Regression& Cẩm nang Playbook: Đối chiếuNaiveAggregateGatevsSliceNonRegressionGatetrênv2vàv3, lập lộ trình sửa lỗi ưu tiên theo rủi ro (Tests 13–15, 20). - Bài tập 6 (
15%) — Kiểm chứng Toàn trìnhWB-Ch25& Xuất JSONworkbench_panels: Chạy trọn bộuv lock --check,ruff,mypy,20/20 pytestvà xuấtartifacts/ch25_wb25_results.json(Tests 01, 16–18).
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Simpson's Paradox & 6-Mode MECE (ex1, ex2) |
Viết đúng công thức tổng hợp vs rủi ro và chạy Tests 04–07 |
Chứng minh được đảo chiều Simpson và tách đúng GoldInCtx |
Thiết kế hoàn chỉnh cây ưu tiên MECE chống đếm trùng và tính chuẩn xác xác suất có điều kiện |
Thống kê, Waterfall & CI Gate (ex3, ex4, ex5) |
Tính đúng McNemar và chạy được run_deterministic_assertions |
Giải thích được Paired Bootstrap CI, hạch toán 3x và Dawid–Skene EM |
Vận hành hoàn hảo Assertion Waterfall (>= 86.8% catch tại $0, nâng \(\kappa\) sống sót 0.044 -> 0.587), chặn v2 và duyệt v3 theo Playbook |
Chất lượng Mã & Kiểm chứng (ex6, WB-Ch25) |
Vượt qua 20/20 pytest, xuất JSON artifact |
Đạt 0 lỗi ruff/mypy, khóa uv.lock và cổng AST cấm pickle |
Tái lập chuẩn xác toàn bộ workbench_panels (6 KPI, 4 bar, 4 bảng) với độ phủ kiểm chứng hoàn chỉnh |
Aggregate Mirage (v2 vs v1): Slice-Level Delta Pass Rate (pp)
6 MECE Failure Modes in v2: Share of Severity-Weighted Risk (%)
Expected Production Risk per Request: v1 vs v2 Mirage vs v3 Remediated
Assertion Waterfall Audit: Failure Catch & Agreement Quality (%)
Stratified Golden Evaluation: v1 Baseline vs v2 Mirage vs v3 Remediated (N=240)
| Eval Slice (N, Severity w) | v1 -> v2 (Delta / 95% CI) | McNemar p (v1 vs v2) | v3 Remediated (Delta vs v1) |
|---|---|---|---|
| Easy Paraphrase QA (n=120, w=1.0) | 75.8% -> 98.3% (+22.5pp [+15.0, +30.0]) | p=0.0000 (b=0, c=27) | 96.7% (+20.8pp) |
| Long-Context Needle RAG (n=24, w=2.5) | 83.3% -> 70.8% (-12.5pp [-25.0, +0.0]) | p=0.2500 (b=3, c=0) | 95.8% (+12.5pp) |
| Compliance & Citation Audit (n=24, w=4.0) | 91.7% -> 70.8% (-20.8pp [-37.5, -4.2]) | p=0.0625 (b=5, c=0) | 95.8% (+4.2pp) |
| Structured JSON API Contract (n=24, w=3.5) | 87.5% -> 70.8% (-16.7pp [-33.3, -4.2]) | p=0.1250 (b=4, c=0) | 100.0% (+12.5pp) |
| Agent Tool-Use & Preconditions (n=24, w=4.5) | 87.5% -> 66.7% (-20.8pp [-37.5, -4.2]) | p=0.0625 (b=5, c=0) | 95.8% (+8.3pp) |
| Multi-Turn State & Memory (n=24, w=3.0) | 83.3% -> 70.8% (-12.5pp [-25.0, +0.0]) | p=0.2500 (b=3, c=0) | 95.8% (+12.5pp) |
| OVERALL AGGREGATE (N=240) | 81.2% -> 84.2% (+2.9pp MIRAGE) | Risk 0.346 -> 0.537 | 96.7% (+15.4pp, Risk 0.075) |
6-Mode MECE Taxonomy & Causal Fault Attribution (Model v2 Mirage)
| Failure Mode (MECE) | Count / Share of Fails | Severity Risk Loss (%) | Primary Engineering Owner |
|---|---|---|---|
| RETRIEVAL_MISS | 5 (13.2%) | 12.5 (9.7%) | Index / Chunking / Hybrid Retriever |
| CONTEXT_UTILIZATION_ERROR | 6 (15.8%) | 15.0 (11.6%) | Reranker Ordering / Context Window Budget |
| GROUNDEDNESS_HALLUCINATION | 5 (13.2%) | 20.0 (15.5%) | Generator Faithfulness / CRAG Citation Gate |
| INSTRUCTION_SCHEMA_VIOLATION | 7 (18.4%) | 24.5 (19.0%) | Constrained FSM Decoding / Prompt Delimiters |
| TOOL_SELECTION_ARG_ERROR | 8 (21.1%) | 36.0 (27.9%) | Tool Schema / Precondition Policy Guard |
| MULTITURN_STATE_DRIFT | 7 (18.4%) | 21.0 (16.3%) | Episodic Memory / Explicit State Checkpointer |
Assertion Waterfall (Deterministic First) vs Always-LLM-Judge Audit (v2)
| Evaluation Architecture | Failure Detection / Accuracy | Judge Calls & API Cost | Reliability / Agreement |
|---|---|---|---|
| Layer 1: Deterministic Assertions Only | Catches 33/38 (86.8%) | 0 LLM calls ($0.00, 0.163 ms/sample) | 100% deterministic (0% false blame) |
| Naive Single Always-LLM-Judge | Survivor RAG Acc 87.3% | 240 calls ($0.960 | 3-Judge all: 720 calls = $2.880) | kappa(J1,J2)=0.044, kappa(J1,True)=0.044 |
| Assertion Waterfall (Det -> Dawid-Skene RAG) | Survivor RAG 97.5% | E2E 98.3% | Full RAG: 157x3=471 calls ($1.884) | Tier-1: 39x3=117 calls ($0.468, -51.25% vs 1J / -83.75% vs 3J) | Dawid-Skene kappa(EM,True)=0.587 |
CI/CD Release Gate Decisions & Top Production Remediation Priorities
| Candidate Release / Gate | Naive Aggregate Gate | Slice Non-Regression Gate | Primary Diagnostic / Action |
|---|---|---|---|
| v2_aggregate_mirage (vs v1) | PASS (+2.9pp overall) | BLOCKED | Blocked 5 Tier-1 slices; risk ratio 1.55x > 1.05x |
| v3_remediated (vs v1) | PASS (+15.4pp overall) | APPROVED | 0 Tier-1 regressions; expected risk reduced to 0.075 (0.22x) |
| Top Priority Fix #1: TOOL_SELECTION_ARG_ERROR | Risk 36.0 (27.9%) | Agent Tool Policy / Sandboxed Dry-Run | Enforce read-before-write precondition DAG + typed tool argument validator |
| Top Priority Fix #2: INSTRUCTION_SCHEMA_VIOLATION | Risk 24.5 (19.0%) | Constrained Decoding / Schema Guard | Switch to FSM Grammar / JSON-Schema decoding + Pydantic v2 extra='forbid' |
02-track-1-data-science-and-ai/part-05-rag-agents-and-evals/labs/ch25-failure-mode-eval-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "failure-mode-eval-lab"
version = "0.1.0"
description = "WB-Ch25: LLM, RAG & Agent Evaluation by Failure Mode — Simpson's Paradox Aggregate Mirage, 6-Mode MECE Taxonomy, Causal Attribution, McNemar/Bootstrap Stats, Deterministic Assertion Waterfall & CI/CD Gates for T1-P5-U03."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"jsonschema>=4.20",
"numpy>=1.26",
"pydantic>=2.0",
"scikit-learn>=1.4",
"scipy>=1.12",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""WB-Ch25 (`failure_mode_eval_lab`) — LLM, RAG & Agent Evaluation by Failure Mode (T1-P5-U03)."""
from failure_mode_eval_lab.failure_taxonomy_and_metrics import (
FAILURE_MODE_ORDER,
FAULT_OWNER_MAP,
SLICE_METADATA,
SLICE_ORDER,
CandidateTraceClassification,
EvalSampleRecord,
FailureMode,
SimpsonReversalResult,
SliceComparisonStats,
SliceId,
ToolCallTrace,
build_stratified_eval_suites,
check_sample_citation_and_facts_valid,
check_sample_schema_valid,
check_sample_state_retained,
check_sample_tool_valid,
classify_sample_failure_mode,
compare_models_by_slice,
compute_cohens_kappa,
compute_conditional_fault_attribution,
compute_mcnemar_test,
dawid_skene_em,
demonstrate_simpsons_paradox_traffic_shift,
paired_bootstrap_delta_ci,
)
from failure_mode_eval_lab.golden_eval_and_ci_gates import (
CIGateEvaluationReport,
CIGatePolicy,
DeterministicAssertionResult,
SliceGateVerdict,
build_remediation_playbook,
evaluate_ci_release_gate,
run_assertion_waterfall_benchmark,
run_deterministic_assertions,
run_full_ch25_wb25_benchmark,
)
__all__ = [
"CIGateEvaluationReport",
"CIGatePolicy",
"CandidateTraceClassification",
"DeterministicAssertionResult",
"EvalSampleRecord",
"FAILURE_MODE_ORDER",
"FAULT_OWNER_MAP",
"FailureMode",
"SLICE_METADATA",
"SLICE_ORDER",
"SimpsonReversalResult",
"SliceComparisonStats",
"SliceGateVerdict",
"SliceId",
"ToolCallTrace",
"build_remediation_playbook",
"build_stratified_eval_suites",
"check_sample_citation_and_facts_valid",
"check_sample_schema_valid",
"check_sample_state_retained",
"check_sample_tool_valid",
"classify_sample_failure_mode",
"compare_models_by_slice",
"compute_cohens_kappa",
"compute_conditional_fault_attribution",
"compute_mcnemar_test",
"dawid_skene_em",
"demonstrate_simpsons_paradox_traffic_shift",
"evaluate_ci_release_gate",
"paired_bootstrap_delta_ci",
"run_assertion_waterfall_benchmark",
"run_deterministic_assertions",
"run_full_ch25_wb25_benchmark",
]
"""WB-Ch25 Module 1: 6-Mode MECE Failure Taxonomy, Simpson's Paradox Mirage & Statistical Attribution."""
from __future__ import annotations
import math
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from scipy.stats import binomtest
FailureMode = Literal[
"PASS",
"RETRIEVAL_MISS",
"CONTEXT_UTILIZATION_ERROR",
"GROUNDEDNESS_HALLUCINATION",
"INSTRUCTION_SCHEMA_VIOLATION",
"TOOL_SELECTION_ARG_ERROR",
"MULTITURN_STATE_DRIFT",
]
FAILURE_MODE_ORDER: tuple[FailureMode, ...] = (
"RETRIEVAL_MISS",
"CONTEXT_UTILIZATION_ERROR",
"GROUNDEDNESS_HALLUCINATION",
"INSTRUCTION_SCHEMA_VIOLATION",
"TOOL_SELECTION_ARG_ERROR",
"MULTITURN_STATE_DRIFT",
)
SliceId = Literal[
"easy_paraphrase",
"long_context_rag",
"compliance_citation",
"structured_json_api",
"agent_tool_use",
"multiturn_stateful",
]
SLICE_ORDER: tuple[SliceId, ...] = (
"easy_paraphrase",
"long_context_rag",
"compliance_citation",
"structured_json_api",
"agent_tool_use",
"multiturn_stateful",
)
SLICE_METADATA: dict[SliceId, dict[str, Any]] = {
"easy_paraphrase": {
"title": "Easy Paraphrase QA",
"tier": "tier2_standard",
"severity_weight": 1.0,
"count": 120,
},
"long_context_rag": {
"title": "Long-Context Needle RAG",
"tier": "tier1_critical",
"severity_weight": 2.5,
"count": 24,
},
"compliance_citation": {
"title": "Compliance & Citation Audit",
"tier": "tier1_critical",
"severity_weight": 4.0,
"count": 24,
},
"structured_json_api": {
"title": "Structured JSON API Contract",
"tier": "tier1_critical",
"severity_weight": 3.5,
"count": 24,
},
"agent_tool_use": {
"title": "Agent Tool-Use & Preconditions",
"tier": "tier1_critical",
"severity_weight": 4.5,
"count": 24,
},
"multiturn_stateful": {
"title": "Multi-Turn State & Memory",
"tier": "tier1_critical",
"severity_weight": 3.0,
"count": 24,
},
}
FAULT_OWNER_MAP: dict[FailureMode, str] = {
"PASS": "None (Verified)",
"RETRIEVAL_MISS": "Index / Chunking / Hybrid Retriever",
"CONTEXT_UTILIZATION_ERROR": "Reranker Ordering / Context Window Budget",
"GROUNDEDNESS_HALLUCINATION": "Generator Faithfulness / CRAG Citation Gate",
"INSTRUCTION_SCHEMA_VIOLATION": "Constrained FSM Decoding / Prompt Delimiters",
"TOOL_SELECTION_ARG_ERROR": "Tool Schema / Precondition Policy Guard",
"MULTITURN_STATE_DRIFT": "Episodic Memory / Explicit State Checkpointer",
}
class ToolCallTrace(BaseModel):
"""Strict schema for a single tool invocation observed in an agent trajectory."""
model_config = ConfigDict(extra="forbid", strict=True)
tool_name: str
arguments: dict[str, Any]
class EvalSampleRecord(BaseModel):
"""Strict evaluation trace for a single Golden Dataset test case and candidate output."""
model_config = ConfigDict(extra="forbid", strict=True)
sample_id: str
model_version: str
slice_id: SliceId
tier: Literal["tier1_critical", "tier2_standard"]
severity_weight: float = Field(..., gt=0.0)
query_text: str
requires_retrieval: bool = False
gold_chunk_id: str | None = None
gold_context_facts: list[str] = Field(default_factory=list)
retrieved_chunk_ids: list[str] = Field(default_factory=list)
gold_chunk_position: int | None = None
context_utilization_ok: bool = True
require_citation_tag: bool = False
schema_name: str | None = None
raw_output: str
expected_tool: str | None = None
required_prereq_tool: str | None = None
tool_trace: list[ToolCallTrace] = Field(default_factory=list)
expected_state_constraints: dict[str, str] = Field(default_factory=dict)
observed_state_constraints: dict[str, str] = Field(default_factory=dict)
supported_claim_ratio: float = Field(..., ge=0.0, le=1.0)
has_contradiction: bool = False
semantic_nuance_judge_votes: list[int] = Field(default_factory=list)
is_synthetic_proxy: bool = True
class CandidateTraceClassification(BaseModel):
"""MECE causal root-cause classification for a single evaluation sample."""
model_config = ConfigDict(extra="forbid", strict=True)
sample_id: str
slice_id: SliceId
tier: Literal["tier1_critical", "tier2_standard"]
severity_weight: float = Field(..., gt=0.0)
passed: bool
primary_failure_mode: FailureMode
secondary_flags: list[FailureMode] = Field(default_factory=list)
gold_in_ctx: bool
fault_owner: str
expected_risk_loss: float = Field(..., ge=0.0)
class SliceComparisonStats(BaseModel):
"""Statistical comparison between baseline and candidate models on a single slice."""
model_config = ConfigDict(extra="forbid", strict=True)
slice_id: SliceId
title: str
tier: Literal["tier1_critical", "tier2_standard"]
n_samples: int = Field(..., gt=0)
severity_weight: float = Field(..., gt=0.0)
base_pass_rate: float = Field(..., ge=0.0, le=1.0)
cand_pass_rate: float = Field(..., ge=0.0, le=1.0)
delta_pp: float
ci_low_pp: float
ci_high_pp: float
mcnemar_b_regressions: int = Field(..., ge=0)
mcnemar_c_improvements: int = Field(..., ge=0)
mcnemar_chi2_cc: float = Field(..., ge=0.0)
mcnemar_p_value: float = Field(..., ge=0.0, le=1.0)
base_expected_risk: float = Field(..., ge=0.0)
cand_expected_risk: float = Field(..., ge=0.0)
class SimpsonReversalResult(BaseModel):
"""Exact verification of Simpson's Paradox under traffic-mix drift."""
model_config = ConfigDict(extra="forbid", strict=True)
easy_rate_v1: float
easy_rate_v2: float
critical_rate_v1: float
critical_rate_v2: float
easy_weight_v1: float
easy_weight_v2: float
aggregate_v1: float
aggregate_v2: float
aggregate_delta_pp: float
easy_delta_pp: float
critical_delta_pp: float
paradox_triggered: bool
def check_sample_schema_valid(sample: EvalSampleRecord) -> bool:
"""Validate structured JSON contract deterministically without silent fallback."""
if sample.schema_name is None:
return True
import json
from jsonschema import ValidationError as JsonSchemaValidationError
from jsonschema import validate as jsonschema_validate
raw = sample.raw_output.strip()
if raw.startswith("```"):
return False
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return False
schema: dict[str, Any] = {
"type": "object",
"additionalProperties": False,
"required": ["decision", "risk_tier", "ticket_id", "confidence"],
"properties": {
"decision": {"type": "string", "enum": ["APPROVE", "REVIEW", "REJECT"]},
"risk_tier": {"type": "string", "enum": ["LOW", "MEDIUM", "HIGH"]},
"ticket_id": {"type": "string", "pattern": "^TCK-[0-9]{4}$"},
"confidence": {"type": "number", "minimum": 0.0, "maximum": 1.0},
},
}
try:
jsonschema_validate(instance=parsed, schema=schema)
except JsonSchemaValidationError:
return False
return True
def check_sample_tool_valid(sample: EvalSampleRecord) -> bool:
"""Validate agent tool selection, argument schema, and prerequisite ordering."""
if sample.expected_tool is None:
return True
if not sample.tool_trace:
return False
tool_names = [step.tool_name for step in sample.tool_trace]
if sample.required_prereq_tool is not None:
if sample.required_prereq_tool not in tool_names:
return False
if sample.expected_tool not in tool_names:
return False
if tool_names.index(sample.required_prereq_tool) > tool_names.index(sample.expected_tool):
return False
matching = [step for step in sample.tool_trace if step.tool_name == sample.expected_tool]
if not matching:
return False
last_call = matching[-1]
args = last_call.arguments
account_id = args.get("account_id")
amount_usd = args.get("amount_usd")
idempotency_key = args.get("idempotency_key")
if not isinstance(account_id, str) or not account_id.startswith("ACC-"):
return False
if not isinstance(amount_usd, (int, float)) or isinstance(amount_usd, bool):
return False
if float(amount_usd) <= 0.0 or float(amount_usd) > 5000.0:
return False
if not isinstance(idempotency_key, str) or len(idempotency_key) < 8:
return False
return True
def check_sample_state_retained(sample: EvalSampleRecord) -> bool:
"""Check whether all multi-turn constraints remain intact in observed state."""
if not sample.expected_state_constraints:
return True
for key, val in sample.expected_state_constraints.items():
if sample.observed_state_constraints.get(key) != val:
return False
return True
def check_sample_citation_and_facts_valid(sample: EvalSampleRecord) -> bool:
"""Deterministic check for required citation bracket and exact numeric/policy facts."""
if sample.require_citation_tag and sample.gold_chunk_id is not None:
if f"[{sample.gold_chunk_id}]" not in sample.raw_output:
return False
for fact in sample.gold_context_facts:
if fact not in sample.raw_output:
return False
return True
def classify_sample_failure_mode(sample: EvalSampleRecord) -> CandidateTraceClassification:
"""Assign exactly one MECE primary root-cause failure mode via causal priority tree."""
gold_in_ctx = (
True
if not sample.requires_retrieval
else (sample.gold_chunk_id is not None and sample.gold_chunk_id in sample.retrieved_chunk_ids)
)
flags: list[FailureMode] = []
if sample.requires_retrieval and not gold_in_ctx:
flags.append("RETRIEVAL_MISS")
if not check_sample_schema_valid(sample):
flags.append("INSTRUCTION_SCHEMA_VIOLATION")
if not check_sample_tool_valid(sample):
flags.append("TOOL_SELECTION_ARG_ERROR")
if not check_sample_state_retained(sample):
flags.append("MULTITURN_STATE_DRIFT")
if sample.requires_retrieval and gold_in_ctx and not sample.context_utilization_ok:
flags.append("CONTEXT_UTILIZATION_ERROR")
if (
sample.has_contradiction
or sample.supported_claim_ratio < 1.0
or (gold_in_ctx and not check_sample_citation_and_facts_valid(sample))
):
flags.append("GROUNDEDNESS_HALLUCINATION")
if not flags:
primary: FailureMode = "PASS"
passed = True
secondary: list[FailureMode] = []
else:
primary = flags[0]
passed = False
secondary = flags[1:]
return CandidateTraceClassification(
sample_id=sample.sample_id,
slice_id=sample.slice_id,
tier=sample.tier,
severity_weight=sample.severity_weight,
passed=passed,
primary_failure_mode=primary,
secondary_flags=secondary,
gold_in_ctx=gold_in_ctx,
fault_owner=FAULT_OWNER_MAP[primary],
expected_risk_loss=0.0 if passed else sample.severity_weight,
)
def compute_mcnemar_test(
base_pass: Sequence[bool], cand_pass: Sequence[bool]
) -> tuple[int, int, float, float]:
"""Compute discordant counts (b, c), continuity-corrected chi2, and exact two-sided p-value."""
if len(base_pass) != len(cand_pass):
raise ValueError("base_pass and cand_pass must have identical lengths for paired McNemar test.")
b_reg = sum(1 for bp, cp in zip(base_pass, cand_pass, strict=True) if bp and not cp)
c_imp = sum(1 for bp, cp in zip(base_pass, cand_pass, strict=True) if (not bp) and cp)
n_disc = b_reg + c_imp
if n_disc == 0:
return 0, 0, 0.0, 1.0
diff = abs(b_reg - c_imp)
chi2_cc = ((max(0.0, diff - 1.0)) ** 2) / float(n_disc)
p_val = float(binomtest(min(b_reg, c_imp), n=n_disc, p=0.5, alternative="two-sided").pvalue)
return b_reg, c_imp, round(chi2_cc, 4), round(p_val, 6)
def paired_bootstrap_delta_ci(
base_pass: Sequence[bool],
cand_pass: Sequence[bool],
n_boot: int = 2000,
seed: int = 42,
) -> tuple[float, float, float]:
"""Compute paired bootstrap 95% confidence interval for delta pass rate in percentage points."""
if len(base_pass) != len(cand_pass) or not base_pass:
raise ValueError("Paired sequences must be non-empty and equal length.")
base_arr = np.asarray(base_pass, dtype=np.float64)
cand_arr = np.asarray(cand_pass, dtype=np.float64)
diff_arr = (cand_arr - base_arr) * 100.0
n = diff_arr.shape[0]
rng = np.random.default_rng(seed)
idx = rng.integers(0, n, size=(n_boot, n))
boot_means = diff_arr[idx].mean(axis=1)
delta_mean = float(diff_arr.mean())
ci_low, ci_high = np.percentile(boot_means, [2.5, 97.5])
return round(delta_mean, 2), round(float(ci_low), 2), round(float(ci_high), 2)
def compute_cohens_kappa(rater_a: Sequence[int], rater_b: Sequence[int]) -> float:
"""Compute exact Cohen's kappa agreement coefficient for binary labels."""
if len(rater_a) != len(rater_b) or not rater_a:
raise ValueError("Rater sequences must be non-empty and equal length.")
a = np.asarray(rater_a, dtype=np.int64)
b = np.asarray(rater_b, dtype=np.int64)
p_o = float(np.mean(a == b))
p_a1 = float(np.mean(a == 1))
p_b1 = float(np.mean(b == 1))
p_e = p_a1 * p_b1 + (1.0 - p_a1) * (1.0 - p_b1)
if abs(1.0 - p_e) < 1e-12:
return 1.0 if p_o >= 1.0 - 1e-12 else 0.0
return round((p_o - p_e) / (1.0 - p_e), 4)
def dawid_skene_em(
votes: np.ndarray,
max_iter: int = 50,
tol: float = 1e-6,
prior_alpha: float = 2.0,
prior_beta: float = 0.5,
) -> tuple[np.ndarray, np.ndarray]:
"""Run MAP-regularized binary Dawid-Skene EM over (N, M) rater matrix."""
if votes.ndim != 2 or votes.shape[1] < 2:
raise ValueError("votes must be a 2D (N, M) matrix with at least 2 raters.")
if votes.shape[0] == 0:
return np.empty(0, dtype=np.float64), np.empty(0, dtype=np.int64)
# Warm-start from smoothed majority vote to avoid washing out rare failures during E-step.
maj = (votes.mean(axis=1) >= 0.5).astype(np.float64)
post_1 = np.where(maj == 1.0, 0.90, 0.10)
pi_1 = float(np.clip(post_1.mean(), 0.02, 0.98))
for _ in range(max_iter):
prev_post = post_1.copy()
w1 = post_1[:, None]
w0 = (1.0 - post_1)[:, None]
sens = np.clip(
((w1 * votes).sum(axis=0) + prior_alpha) / (w1.sum() + prior_alpha + prior_beta),
0.02,
0.995,
)
spec = np.clip(
((w0 * (1.0 - votes)).sum(axis=0) + prior_alpha) / (w0.sum() + prior_alpha + prior_beta),
0.02,
0.995,
)
pi_1 = float(np.clip(post_1.mean(), 0.02, 0.98))
log_l1 = math.log(pi_1) + np.sum(
votes * np.log(sens[None, :]) + (1.0 - votes) * np.log(1.0 - sens[None, :]),
axis=1,
)
log_l0 = math.log(1.0 - pi_1) + np.sum(
votes * np.log(1.0 - spec[None, :]) + (1.0 - votes) * np.log(spec[None, :]),
axis=1,
)
diff = np.clip(log_l0 - log_l1, -40.0, 40.0)
post_1 = 1.0 / (1.0 + np.exp(diff))
if float(np.max(np.abs(post_1 - prev_post))) < tol:
break
consensus = (post_1 >= 0.5).astype(np.int64)
return np.asarray(post_1, dtype=np.float64), consensus
def demonstrate_simpsons_paradox_traffic_shift(
easy_rate_v1: float = 0.94,
easy_rate_v2: float = 0.92,
critical_rate_v1: float = 0.78,
critical_rate_v2: float = 0.64,
easy_weight_v1: float = 0.30,
easy_weight_v2: float = 0.80,
) -> SimpsonReversalResult:
"""Prove exact Simpson's reversal where every slice drops yet global average increases."""
agg_v1 = easy_weight_v1 * easy_rate_v1 + (1.0 - easy_weight_v1) * critical_rate_v1
agg_v2 = easy_weight_v2 * easy_rate_v2 + (1.0 - easy_weight_v2) * critical_rate_v2
easy_delta = (easy_rate_v2 - easy_rate_v1) * 100.0
crit_delta = (critical_rate_v2 - critical_rate_v1) * 100.0
agg_delta = (agg_v2 - agg_v1) * 100.0
triggered = easy_delta < 0.0 and crit_delta < 0.0 and agg_delta > 0.0
return SimpsonReversalResult(
easy_rate_v1=round(easy_rate_v1, 4),
easy_rate_v2=round(easy_rate_v2, 4),
critical_rate_v1=round(critical_rate_v1, 4),
critical_rate_v2=round(critical_rate_v2, 4),
easy_weight_v1=round(easy_weight_v1, 4),
easy_weight_v2=round(easy_weight_v2, 4),
aggregate_v1=round(agg_v1, 4),
aggregate_v2=round(agg_v2, 4),
aggregate_delta_pp=round(agg_delta, 2),
easy_delta_pp=round(easy_delta, 2),
critical_delta_pp=round(crit_delta, 2),
paradox_triggered=triggered,
)
def _build_judge_votes(
true_pass: bool, rng: np.random.Generator, subtle_fail: bool
) -> list[int]:
"""Generate 3 heterogeneous PoLL judge votes (1 weak single judge + 2 calibrated panel judges)."""
if true_pass:
probs = [0.90, 0.95, 0.96]
elif subtle_fail:
probs = [0.48, 0.16, 0.10] # Weak naive judge #1 misses ~48% of subtle semantic fails
else:
probs = [0.12, 0.10, 0.08]
return [1 if float(rng.random()) < p else 0 for p in probs]
def build_stratified_eval_suites(seed: int = 42) -> dict[str, list[EvalSampleRecord]]:
"""Build deterministic 240-sample paired golden suites for v1, v2 (Mirage), and v3 (Remediated).
Note: All outputs, traces, and judge votes are controlled offline synthetic evaluation proxies
designed to faithfully reproduce enterprise failure modes without external API dependencies.
"""
rng = np.random.default_rng(seed)
# Exact paired failure indices per slice so McNemar tests capture true regressions/fixes
configs: dict[SliceId, dict[str, dict[int, FailureMode]]] = {
"easy_paraphrase": {
"v1": {
**{i: "RETRIEVAL_MISS" for i in range(18)},
**{i: "GROUNDEDNESS_HALLUCINATION" for i in range(18, 29)},
},
"v2": {0: "RETRIEVAL_MISS", 1: "RETRIEVAL_MISS"},
"v3": {
0: "RETRIEVAL_MISS",
1: "RETRIEVAL_MISS",
2: "RETRIEVAL_MISS",
18: "GROUNDEDNESS_HALLUCINATION",
},
},
"long_context_rag": {
"v1": {
0: "RETRIEVAL_MISS",
1: "CONTEXT_UTILIZATION_ERROR",
2: "CONTEXT_UTILIZATION_ERROR",
3: "CONTEXT_UTILIZATION_ERROR",
},
"v2": {
0: "RETRIEVAL_MISS",
**{i: "CONTEXT_UTILIZATION_ERROR" for i in range(1, 7)},
},
"v3": {0: "RETRIEVAL_MISS"},
},
"compliance_citation": {
"v1": {0: "GROUNDEDNESS_HALLUCINATION", 1: "GROUNDEDNESS_HALLUCINATION"},
"v2": {
0: "RETRIEVAL_MISS",
1: "RETRIEVAL_MISS",
**{i: "GROUNDEDNESS_HALLUCINATION" for i in range(2, 7)},
},
"v3": {2: "GROUNDEDNESS_HALLUCINATION"},
},
"structured_json_api": {
"v1": {i: "INSTRUCTION_SCHEMA_VIOLATION" for i in range(3)},
"v2": {i: "INSTRUCTION_SCHEMA_VIOLATION" for i in range(7)},
"v3": {},
},
"agent_tool_use": {
"v1": {i: "TOOL_SELECTION_ARG_ERROR" for i in range(3)},
"v2": {i: "TOOL_SELECTION_ARG_ERROR" for i in range(8)},
"v3": {0: "TOOL_SELECTION_ARG_ERROR"},
},
"multiturn_stateful": {
"v1": {i: "MULTITURN_STATE_DRIFT" for i in range(4)},
"v2": {i: "MULTITURN_STATE_DRIFT" for i in range(7)},
"v3": {0: "MULTITURN_STATE_DRIFT"},
},
}
suites: dict[str, list[EvalSampleRecord]] = {
"v1_baseline": [],
"v2_aggregate_mirage": [],
"v3_remediated": [],
}
version_map = {"v1": "v1_baseline", "v2": "v2_aggregate_mirage", "v3": "v3_remediated"}
global_idx = 0
for slice_id in SLICE_ORDER:
meta = SLICE_METADATA[slice_id]
n_slice = int(meta["count"])
tier: Literal["tier1_critical", "tier2_standard"] = meta["tier"]
weight = float(meta["severity_weight"])
for local_i in range(n_slice):
global_idx += 1
sample_id = f"q_{global_idx:03d}"
gold_chunk = f"doc_{(local_i % 18) + 1:02d}_s{(local_i % 4) + 1}"
sla_val = f"{95 + (local_i % 5)}.{local_i % 10}%"
for short_ver, full_ver in version_map.items():
mode = configs[slice_id][short_ver].get(local_i, "PASS")
record = _construct_sample_record(
sample_id=sample_id,
model_version=full_ver,
slice_id=slice_id,
tier=tier,
severity_weight=weight,
local_i=local_i,
gold_chunk=gold_chunk,
sla_val=sla_val,
target_mode=mode,
rng=rng,
)
suites[full_ver].append(record)
return suites
def _construct_sample_record(
sample_id: str,
model_version: str,
slice_id: SliceId,
tier: Literal["tier1_critical", "tier2_standard"],
severity_weight: float,
local_i: int,
gold_chunk: str,
sla_val: str,
target_mode: FailureMode,
rng: np.random.Generator,
) -> EvalSampleRecord:
"""Create a realistic EvalSampleRecord whose raw trace reproduces target_mode cleanly."""
decoy_chunks = [
f"decoy_a_{local_i:02d}",
f"decoy_b_{local_i:02d}",
f"decoy_c_{local_i:02d}",
f"decoy_d_{local_i:02d}",
]
if slice_id in ("easy_paraphrase", "long_context_rag", "compliance_citation"):
req_ret = True
req_cit = slice_id == "compliance_citation"
facts = [sla_val] if slice_id in ("compliance_citation", "long_context_rag") else []
if target_mode == "RETRIEVAL_MISS":
retrieved = decoy_chunks + [f"decoy_e_{local_i:02d}"]
gold_pos = None
ctx_ok = True
supp_ratio = 0.0
contradict = False
raw_out = f"Policy limit is 50% [decoy_a_{local_i:02d}]."
elif target_mode == "CONTEXT_UTILIZATION_ERROR":
retrieved = [
decoy_chunks[0],
decoy_chunks[1],
gold_chunk,
decoy_chunks[2],
decoy_chunks[3],
]
gold_pos = 2 # Lost-in-the-middle slot!
ctx_ok = False
supp_ratio = 0.5
contradict = False
# Passes syntactic citation tag check when subtle (local_i % 2 == 0) so Judge catches it
raw_out = (
f"Distractor context suggests legacy timeout while {sla_val} applies [{gold_chunk}]."
if local_i % 2 == 0
else f"Distractor context overrides timeout [{gold_chunk}]."
)
elif target_mode == "GROUNDEDNESS_HALLUCINATION":
retrieved = [gold_chunk] + decoy_chunks
gold_pos = 0
ctx_ok = True
supp_ratio = 0.45
contradict = True
if slice_id == "compliance_citation" and local_i % 3 == 0:
# Subtle semantic hallucination (citation present & number present, contradicts clause)
raw_out = f"Guaranteed SLA {sla_val} waives all audit holds [{gold_chunk}]."
else:
# Deterministic catch: missing gold citation or wrong fabricated SLA number
raw_out = "Guaranteed SLA 99.99% applies without citation [POL-999]."
else:
retrieved = [gold_chunk] + decoy_chunks
gold_pos = 0
ctx_ok = True
supp_ratio = 1.0
contradict = False
raw_out = f"Verified SLA target is {sla_val} per runbook [{gold_chunk}]."
votes = _build_judge_votes(
true_pass=(target_mode == "PASS"),
rng=rng,
subtle_fail=(target_mode in ("CONTEXT_UTILIZATION_ERROR", "GROUNDEDNESS_HALLUCINATION")),
)
return EvalSampleRecord(
sample_id=sample_id,
model_version=model_version,
slice_id=slice_id,
tier=tier,
severity_weight=severity_weight,
query_text=f"Audit {slice_id} query {sample_id} for {gold_chunk}",
requires_retrieval=req_ret,
gold_chunk_id=gold_chunk,
gold_context_facts=facts,
retrieved_chunk_ids=retrieved,
gold_chunk_position=gold_pos,
context_utilization_ok=ctx_ok,
require_citation_tag=req_cit,
raw_output=raw_out,
supported_claim_ratio=supp_ratio,
has_contradiction=contradict,
semantic_nuance_judge_votes=votes,
)
if slice_id == "structured_json_api":
tck = f"TCK-{1000 + local_i:04d}"
if target_mode == "INSTRUCTION_SCHEMA_VIOLATION":
if local_i % 3 == 0:
raw_out = (
f'```json\n{{"decision": "APPROVE", "risk_tier": "LOW", '
f'"ticket_id": "{tck}", "confidence": 0.92}}\n```'
)
elif local_i % 3 == 1:
raw_out = (
f'{{"decision": "APPROVE", "risk_tier": "UNKNOWN", '
f'"ticket_id": "{tck}", "confidence": 0.92}}'
)
else:
raw_out = (
f'{{"decision": "REVIEW", "risk_tier": "HIGH", '
f'"ticket_id": "{tck}", "confidence": 0.85, "extra_field": true}}'
)
else:
raw_out = (
f'{{"decision": "APPROVE", "risk_tier": "LOW", '
f'"ticket_id": "{tck}", "confidence": 0.94}}'
)
return EvalSampleRecord(
sample_id=sample_id,
model_version=model_version,
slice_id=slice_id,
tier=tier,
severity_weight=severity_weight,
query_text=f"Emit strict JSON decision payload for {tck}",
schema_name="RiskDecisionPayload",
raw_output=raw_out,
supported_claim_ratio=1.0,
semantic_nuance_judge_votes=_build_judge_votes(target_mode == "PASS", rng, False),
)
if slice_id == "agent_tool_use":
acc = f"ACC-{100 + local_i}"
idem = f"idem-{sample_id}"
if target_mode == "TOOL_SELECTION_ARG_ERROR":
if local_i % 3 == 0:
# Missing prerequisite verify_account_ownership before issue_refund
trace = [
ToolCallTrace(
tool_name="issue_refund",
arguments={"account_id": acc, "amount_usd": 120.0, "idempotency_key": idem},
)
]
elif local_i % 3 == 1:
# Invalid negative/boolean arg or malformed account_id
trace = [
ToolCallTrace(tool_name="verify_account_ownership", arguments={"account_id": acc}),
ToolCallTrace(
tool_name="issue_refund",
arguments={
"account_id": "BAD_ACC",
"amount_usd": -50.0,
"idempotency_key": "short",
},
),
]
else:
# Wrong tool selected
trace = [
ToolCallTrace(tool_name="verify_account_ownership", arguments={"account_id": acc}),
ToolCallTrace(tool_name="delete_user_profile", arguments={"account_id": acc}),
]
else:
trace = [
ToolCallTrace(tool_name="verify_account_ownership", arguments={"account_id": acc}),
ToolCallTrace(
tool_name="issue_refund",
arguments={"account_id": acc, "amount_usd": 120.0, "idempotency_key": idem},
),
]
return EvalSampleRecord(
sample_id=sample_id,
model_version=model_version,
slice_id=slice_id,
tier=tier,
severity_weight=severity_weight,
query_text=f"Verify account {acc} then issue $120 refund",
raw_output=f"Executed tool sequence for {acc}",
expected_tool="issue_refund",
required_prereq_tool="verify_account_ownership",
tool_trace=trace,
supported_claim_ratio=1.0,
semantic_nuance_judge_votes=_build_judge_votes(target_mode == "PASS", rng, False),
)
# multiturn_stateful
expected_state = {"region": "ap-southeast-1", "budget_cap": "500", "compliance": "SOC2"}
if target_mode == "MULTITURN_STATE_DRIFT":
observed_state = {"region": "us-east-1", "budget_cap": "unlimited", "compliance": "SOC2"}
raw_out = "Deploying cluster in us-east-1 with unlimited budget under SOC2."
else:
observed_state = dict(expected_state)
raw_out = "Deploying cluster in ap-southeast-1 with budget_cap=500 under SOC2."
return EvalSampleRecord(
sample_id=sample_id,
model_version=model_version,
slice_id=slice_id,
tier=tier,
severity_weight=severity_weight,
query_text=f"Turn 5 deploy preserving region/budget/SOC2 constraints ({sample_id})",
raw_output=raw_out,
expected_state_constraints=expected_state,
observed_state_constraints=observed_state,
supported_claim_ratio=1.0,
semantic_nuance_judge_votes=_build_judge_votes(target_mode == "PASS", rng, False),
)
def compute_conditional_fault_attribution(
records: Sequence[EvalSampleRecord],
) -> dict[str, Any]:
"""Compute MECE failure breakdown, conditional fault probabilities, and risk contribution."""
classifications = [classify_sample_failure_mode(r) for r in records]
n_total = len(records)
passed_count = sum(1 for c in classifications if c.passed)
failed_count = n_total - passed_count
total_risk = sum(c.expected_risk_loss for c in classifications)
ret_samples = [
(r, c) for r, c in zip(records, classifications, strict=True) if r.requires_retrieval
]
n_ret = max(1, len(ret_samples))
n_ret_miss = sum(1 for _, c in ret_samples if c.primary_failure_mode == "RETRIEVAL_MISS")
gold_in_ctx_pairs = [(r, c) for r, c in ret_samples if c.gold_in_ctx]
n_gold = max(1, len(gold_in_ctx_pairs))
n_ctx_err = sum(
1 for _, c in gold_in_ctx_pairs if c.primary_failure_mode == "CONTEXT_UTILIZATION_ERROR"
)
n_hal_given_gold = sum(
1 for _, c in gold_in_ctx_pairs if c.primary_failure_mode == "GROUNDEDNESS_HALLUCINATION"
)
schema_samples = [c for r, c in zip(records, classifications, strict=True) if r.schema_name is not None]
tool_samples = [c for r, c in zip(records, classifications, strict=True) if r.expected_tool is not None]
state_samples = [
c for r, c in zip(records, classifications, strict=True) if r.expected_state_constraints
]
mode_breakdown: dict[str, dict[str, Any]] = {}
for fm in FAILURE_MODE_ORDER:
matched = [c for c in classifications if c.primary_failure_mode == fm]
risk_sum = sum(c.expected_risk_loss for c in matched)
mode_breakdown[fm] = {
"count": len(matched),
"share_of_all_samples": round(len(matched) / max(1, n_total), 4),
"share_of_failures": round(len(matched) / max(1, failed_count), 4),
"total_risk_loss": round(risk_sum, 2),
"share_of_risk": round(risk_sum / max(1e-9, total_risk), 4) if total_risk > 0 else 0.0,
"fault_owner": FAULT_OWNER_MAP[fm],
}
tier1_cls = [c for c in classifications if c.tier == "tier1_critical"]
tier1_pass = sum(1 for c in tier1_cls if c.passed)
return {
"n_samples": n_total,
"overall_pass_rate": round(passed_count / max(1, n_total), 4),
"tier1_critical_pass_rate": round(tier1_pass / max(1, len(tier1_cls)), 4),
"expected_production_risk": round(total_risk / max(1, n_total), 4),
"total_severity_weighted_risk": round(total_risk, 2),
"failed_count": failed_count,
"conditional_probabilities": {
"p_retrieval_miss": round(n_ret_miss / n_ret, 4),
"p_context_util_given_gold_in_ctx": round(n_ctx_err / n_gold, 4),
"p_hallucination_given_gold_in_ctx": round(n_hal_given_gold / n_gold, 4),
"p_gen_fail_given_gold_in_ctx": round((n_ctx_err + n_hal_given_gold) / n_gold, 4),
"p_schema_violation_on_api": round(
sum(1 for c in schema_samples if c.primary_failure_mode == "INSTRUCTION_SCHEMA_VIOLATION")
/ max(1, len(schema_samples)),
4,
),
"p_tool_error_on_agent": round(
sum(1 for c in tool_samples if c.primary_failure_mode == "TOOL_SELECTION_ARG_ERROR")
/ max(1, len(tool_samples)),
4,
),
"p_state_drift_on_multiturn": round(
sum(1 for c in state_samples if c.primary_failure_mode == "MULTITURN_STATE_DRIFT")
/ max(1, len(state_samples)),
4,
),
},
"failure_mode_breakdown": mode_breakdown,
}
def compare_models_by_slice(
base_records: Sequence[EvalSampleRecord],
cand_records: Sequence[EvalSampleRecord],
n_boot: int = 2000,
seed: int = 42,
) -> list[SliceComparisonStats]:
"""Compare two paired model evaluation suites across all 6 stratified slices."""
base_cls = [classify_sample_failure_mode(r) for r in base_records]
cand_cls = [classify_sample_failure_mode(r) for r in cand_records]
results: list[SliceComparisonStats] = []
for slice_id in SLICE_ORDER:
b_slice = [c for c in base_cls if c.slice_id == slice_id]
c_slice = [c for c in cand_cls if c.slice_id == slice_id]
b_pass = [c.passed for c in b_slice]
c_pass = [c.passed for c in c_slice]
delta_mean, ci_low, ci_high = paired_bootstrap_delta_ci(
b_pass, c_pass, n_boot=n_boot, seed=seed
)
b_reg, c_imp, chi2_cc, p_val = compute_mcnemar_test(b_pass, c_pass)
meta = SLICE_METADATA[slice_id]
tier: Literal["tier1_critical", "tier2_standard"] = meta["tier"]
results.append(
SliceComparisonStats(
slice_id=slice_id,
title=str(meta["title"]),
tier=tier,
n_samples=len(b_slice),
severity_weight=float(meta["severity_weight"]),
base_pass_rate=round(sum(b_pass) / len(b_pass), 4),
cand_pass_rate=round(sum(c_pass) / len(c_pass), 4),
delta_pp=delta_mean,
ci_low_pp=ci_low,
ci_high_pp=ci_high,
mcnemar_b_regressions=b_reg,
mcnemar_c_improvements=c_imp,
mcnemar_chi2_cc=chi2_cc,
mcnemar_p_value=p_val,
base_expected_risk=round(sum(c.expected_risk_loss for c in b_slice) / len(b_slice), 4),
cand_expected_risk=round(sum(c.expected_risk_loss for c in c_slice) / len(c_slice), 4),
)
)
return results
"""WB-Ch25 Module 2: Deterministic Assertion Waterfall, Calibrated Judge Panel & CI/CD Slice Gates."""
from __future__ import annotations
import re
import time
from collections.abc import Sequence
from typing import Any
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from failure_mode_eval_lab.failure_taxonomy_and_metrics import (
FAILURE_MODE_ORDER,
SLICE_ORDER,
EvalSampleRecord,
SliceComparisonStats,
build_stratified_eval_suites,
check_sample_citation_and_facts_valid,
check_sample_schema_valid,
check_sample_state_retained,
check_sample_tool_valid,
classify_sample_failure_mode,
compare_models_by_slice,
compute_cohens_kappa,
compute_conditional_fault_attribution,
dawid_skene_em,
demonstrate_simpsons_paradox_traffic_shift,
)
class CIGatePolicy(BaseModel):
"""Strict CI/CD non-regression policy across stratified slices and production risk."""
model_config = ConfigDict(extra="forbid", strict=True)
max_slice_regression_pp: float = Field(default=3.0, ge=0.0, le=20.0)
tier1_floor_pass_rate: float = Field(default=0.78, ge=0.5, le=1.0)
max_expected_risk_ratio: float = Field(default=1.05, ge=0.5, le=2.0)
min_overall_delta_pp: float = Field(default=-1.0, ge=-10.0, le=10.0)
mcnemar_alpha: float = Field(default=0.05, gt=0.0, le=0.25)
class DeterministicAssertionResult(BaseModel):
"""Output of fast (<1ms, $0) deterministic programmatic checks for one sample."""
model_config = ConfigDict(extra="forbid", strict=True)
sample_id: str
det_passed: bool
failed_checks: list[str]
elapsed_ms: float = Field(..., ge=0.0)
class SliceGateVerdict(BaseModel):
"""Per-slice pass/fail verdict under the Slice-Level Non-Regression CI Gate."""
model_config = ConfigDict(extra="forbid", strict=True)
slice_id: str
tier: str
delta_pp: float
cand_pass_rate: float
mcnemar_p_value: float
passed_gate: bool
failure_reasons: list[str]
class CIGateEvaluationReport(BaseModel):
"""Complete release decision comparing Naive Aggregate Gate vs Slice Non-Regression Gate."""
model_config = ConfigDict(extra="forbid", strict=True)
candidate_version: str
baseline_version: str
base_overall_pass_rate: float
cand_overall_pass_rate: float
overall_delta_pp: float
base_expected_risk: float
cand_expected_risk: float
expected_risk_ratio: float
naive_aggregate_gate_passed: bool
slice_non_regression_gate_passed: bool
blocked_slices: list[str]
blocking_reasons: list[str]
slice_verdicts: list[SliceGateVerdict]
def run_deterministic_assertions(sample: EvalSampleRecord) -> DeterministicAssertionResult:
"""Execute fast programmatic checks (retrieval gold, JSON schema, tool trace, state, citations)."""
t0 = time.perf_counter_ns()
failed: list[str] = []
if sample.requires_retrieval:
if sample.gold_chunk_id is None or sample.gold_chunk_id not in sample.retrieved_chunk_ids:
failed.append("retrieval_gold_miss")
elif not check_sample_citation_and_facts_valid(sample):
failed.append("citation_or_exact_fact_mismatch")
cited_ids = re.findall(r"\[([A-Z]+-\d+)\]", sample.raw_output)
if any(cid not in sample.retrieved_chunk_ids for cid in cited_ids):
failed.append("forbidden_fabricated_citation")
if sample.schema_name is not None and not check_sample_schema_valid(sample):
failed.append("strict_json_schema_violation")
if sample.expected_tool is not None and not check_sample_tool_valid(sample):
failed.append("tool_selection_prereq_or_args_violation")
if sample.expected_state_constraints and not check_sample_state_retained(sample):
failed.append("multiturn_state_constraint_lost")
elapsed_ms = (time.perf_counter_ns() - t0) / 1_000_000.0
return DeterministicAssertionResult(
sample_id=sample.sample_id,
det_passed=(len(failed) == 0),
failed_checks=failed,
elapsed_ms=round(elapsed_ms, 4),
)
def run_assertion_waterfall_benchmark(
records: Sequence[EvalSampleRecord],
) -> dict[str, Any]:
"""Run Layer-1 deterministic checks first, then route only semantic RAG survivors to Judge."""
det_results = [run_deterministic_assertions(r) for r in records]
cls_results = [classify_sample_failure_mode(r) for r in records]
total_n = len(records)
true_labels = np.array([1 if c.passed else 0 for c in cls_results], dtype=np.int64)
det_pass_flags = [d.det_passed for d in det_results]
n_true_failures = int(np.sum(true_labels == 0))
n_det_caught_failures = sum(
1 for d, c in zip(det_results, cls_results, strict=True) if (not d.det_passed) and (not c.passed)
)
det_catch_rate = n_det_caught_failures / max(1, n_true_failures)
# Layer-2 Judge routing:
# Structural/tool/state slices need 0 LLM judge calls; failed retrieval/citation samples fail fast.
# Only RAG samples surviving Layer-1 enter Layer-2 semantic nuance judge panel.
judge_routed_indices = [
idx
for idx, (r, d) in enumerate(zip(records, det_results, strict=True))
if d.det_passed and r.requires_retrieval
]
tier1_judge_routed_indices = [
idx for idx in judge_routed_indices if records[idx].tier == "tier1_critical"
]
# Calibrated 3-Judge Dawid-Skene EM panel fitted strictly on Layer-2 routed survivors
num_judges = 3
single_call_cost_usd = 0.0040
if judge_routed_indices:
routed_rag_votes = np.array(
[records[i].semantic_nuance_judge_votes for i in judge_routed_indices], dtype=np.int64
)
routed_rag_true = np.array([true_labels[i] for i in judge_routed_indices], dtype=np.int64)
naive_single_judge_preds = routed_rag_votes[:, 0]
naive_j1_j2_kappa = compute_cohens_kappa(
routed_rag_votes[:, 0].tolist(), routed_rag_votes[:, 1].tolist()
)
naive_vs_true_kappa = compute_cohens_kappa(
naive_single_judge_preds.tolist(), routed_rag_true.tolist()
)
naive_rag_acc = float(np.mean(naive_single_judge_preds == routed_rag_true))
_, ds_consensus = dawid_skene_em(routed_rag_votes)
ds_vs_true_kappa = compute_cohens_kappa(ds_consensus.tolist(), routed_rag_true.tolist())
ds_rag_acc = float(np.mean(ds_consensus == routed_rag_true))
else:
ds_consensus = np.empty(0, dtype=np.int64)
naive_j1_j2_kappa = 1.0
naive_vs_true_kappa = 1.0
naive_rag_acc = 1.0
ds_vs_true_kappa = 1.0
ds_rag_acc = 1.0
# Full Waterfall final prediction:
# Fail immediately if Layer 1 failed; else use Dawid-Skene consensus on RAG survivors; else pass.
routed_pos_map = {orig_idx: pos for pos, orig_idx in enumerate(judge_routed_indices)}
waterfall_preds = np.ones(total_n, dtype=np.int64)
for idx in range(total_n):
if not det_pass_flags[idx]:
waterfall_preds[idx] = 0
elif idx in routed_pos_map:
waterfall_preds[idx] = int(ds_consensus[routed_pos_map[idx]])
else:
waterfall_preds[idx] = 1
waterfall_acc = float(np.mean(waterfall_preds == true_labels))
mean_det_ms = sum(d.elapsed_ms for d in det_results) / max(1, total_n)
# Explicit 3x 3-judge API cost & call accounting:
# $0.004 per single judge call -> $0.012 per 3-judge Dawid-Skene panel item.
routed_full_rag_samples = len(judge_routed_indices)
routed_tier1_samples = len(tier1_judge_routed_indices)
naive_all_single_judge_calls = total_n
naive_all_single_judge_cost_usd = round(naive_all_single_judge_calls * single_call_cost_usd, 4)
naive_all_3judge_calls = total_n * num_judges
naive_all_3judge_cost_usd = round(naive_all_3judge_calls * single_call_cost_usd, 4)
waterfall_full_rag_3judge_calls = routed_full_rag_samples * num_judges
waterfall_full_rag_cost_usd = round(waterfall_full_rag_3judge_calls * single_call_cost_usd, 4)
waterfall_tier1_3judge_calls = routed_tier1_samples * num_judges
waterfall_tier1_routed_cost_usd = round(waterfall_tier1_3judge_calls * single_call_cost_usd, 4)
cost_red_vs_1j = 1.0 - waterfall_tier1_routed_cost_usd / max(
1e-9, naive_all_single_judge_cost_usd
)
cost_red_vs_3j = 1.0 - waterfall_tier1_routed_cost_usd / max(1e-9, naive_all_3judge_cost_usd)
return {
"n_samples": total_n,
"num_judges": num_judges,
"single_judge_call_cost_usd": single_call_cost_usd,
"true_failures": n_true_failures,
"det_caught_failures": n_det_caught_failures,
"deterministic_failure_catch_rate": round(det_catch_rate, 4),
"mean_deterministic_latency_ms": round(mean_det_ms, 4),
"deterministic_api_cost_usd": 0.0,
"naive_all_single_judge_calls": naive_all_single_judge_calls,
"naive_all_single_judge_cost_usd": naive_all_single_judge_cost_usd,
"naive_all_3judge_calls": naive_all_3judge_calls,
"naive_all_3judge_cost_usd": naive_all_3judge_cost_usd,
"routed_full_rag_samples": routed_full_rag_samples,
"waterfall_full_rag_3judge_calls": waterfall_full_rag_3judge_calls,
"waterfall_full_rag_cost_usd": waterfall_full_rag_cost_usd,
"routed_tier1_samples": routed_tier1_samples,
"waterfall_tier1_3judge_calls": waterfall_tier1_3judge_calls,
"waterfall_tier1_routed_cost_usd": waterfall_tier1_routed_cost_usd,
"sample_reduction_full_rag": round(1.0 - routed_full_rag_samples / max(1, total_n), 4),
"sample_reduction_tier1_routed": round(1.0 - routed_tier1_samples / max(1, total_n), 4),
"cost_reduction_tier1_vs_naive_single_judge": round(cost_red_vs_1j, 4),
"cost_reduction_tier1_vs_naive_3judge": round(cost_red_vs_3j, 4),
"naive_judge_inter_rater_kappa": naive_j1_j2_kappa,
"naive_judge_vs_true_kappa": naive_vs_true_kappa,
"naive_judge_rag_accuracy": round(naive_rag_acc, 4),
"dawid_skene_vs_true_kappa": ds_vs_true_kappa,
"dawid_skene_rag_accuracy": round(ds_rag_acc, 4),
"waterfall_end_to_end_accuracy": round(waterfall_acc, 4),
}
def evaluate_ci_release_gate(
base_records: Sequence[EvalSampleRecord],
cand_records: Sequence[EvalSampleRecord],
candidate_version: str,
baseline_version: str = "v1_baseline",
policy: CIGatePolicy | None = None,
n_boot: int = 2000,
seed: int = 42,
) -> CIGateEvaluationReport:
"""Evaluate candidate release against baseline using both Naive Aggregate and Slice CI Gates."""
active_policy = policy or CIGatePolicy()
base_attr = compute_conditional_fault_attribution(base_records)
cand_attr = compute_conditional_fault_attribution(cand_records)
slice_stats: list[SliceComparisonStats] = compare_models_by_slice(
base_records, cand_records, n_boot=n_boot, seed=seed
)
base_overall = float(base_attr["overall_pass_rate"])
cand_overall = float(cand_attr["overall_pass_rate"])
overall_delta_pp = round((cand_overall - base_overall) * 100.0, 2)
base_risk = float(base_attr["expected_production_risk"])
cand_risk = float(cand_attr["expected_production_risk"])
risk_ratio = round(cand_risk / max(1e-9, base_risk), 4)
naive_gate_passed = overall_delta_pp >= active_policy.min_overall_delta_pp
verdicts: list[SliceGateVerdict] = []
blocked_slices: list[str] = []
blocking_reasons: list[str] = []
for st in slice_stats:
reasons: list[str] = []
if st.delta_pp < -active_policy.max_slice_regression_pp:
reasons.append(
f"delta {st.delta_pp:+.1f}pp < -{active_policy.max_slice_regression_pp:.1f}pp budget"
)
if st.tier == "tier1_critical" and st.cand_pass_rate < active_policy.tier1_floor_pass_rate:
reasons.append(
f"pass_rate {st.cand_pass_rate * 100:.1f}% < Tier-1 floor "
f"{active_policy.tier1_floor_pass_rate * 100:.1f}%"
)
if st.delta_pp < 0.0 and st.mcnemar_p_value < active_policy.mcnemar_alpha:
reasons.append(
f"statistically significant regression (McNemar p={st.mcnemar_p_value:.4f} "
f"< alpha={active_policy.mcnemar_alpha:.3f})"
)
passed_slice = len(reasons) == 0
if not passed_slice:
blocked_slices.append(st.slice_id)
blocking_reasons.append(f"{st.slice_id}: " + "; ".join(reasons))
verdicts.append(
SliceGateVerdict(
slice_id=st.slice_id,
tier=st.tier,
delta_pp=st.delta_pp,
cand_pass_rate=st.cand_pass_rate,
mcnemar_p_value=st.mcnemar_p_value,
passed_gate=passed_slice,
failure_reasons=reasons,
)
)
if risk_ratio > active_policy.max_expected_risk_ratio:
blocking_reasons.append(
f"expected_risk_ratio {risk_ratio:.3f}x > {active_policy.max_expected_risk_ratio:.2f}x budget"
)
slice_gate_passed = (
naive_gate_passed
and len(blocked_slices) == 0
and risk_ratio <= active_policy.max_expected_risk_ratio
)
return CIGateEvaluationReport(
candidate_version=candidate_version,
baseline_version=baseline_version,
base_overall_pass_rate=base_overall,
cand_overall_pass_rate=cand_overall,
overall_delta_pp=overall_delta_pp,
base_expected_risk=base_risk,
cand_expected_risk=cand_risk,
expected_risk_ratio=risk_ratio,
naive_aggregate_gate_passed=naive_gate_passed,
slice_non_regression_gate_passed=slice_gate_passed,
blocked_slices=blocked_slices,
blocking_reasons=blocking_reasons,
slice_verdicts=verdicts,
)
def build_remediation_playbook(attribution: dict[str, Any]) -> list[dict[str, Any]]:
"""Map observed MECE failure modes to concrete engineering remediations prioritized by risk."""
actions: dict[str, tuple[str, str]] = {
"RETRIEVAL_MISS": (
"Index / Chunking / Hybrid Retriever",
"Add Contextual Retrieval headers + Hybrid BM25/Dense RRF(k=60) + GraphRAG PPR",
),
"CONTEXT_UTILIZATION_ERROR": (
"Reranker Ordering / Context Rot Cap",
"Enforce Cross-Encoder Top-5 edge placement & cap context budget to 20-40% signal window",
),
"GROUNDEDNESS_HALLUCINATION": (
"Generator / CRAG Citation Gate",
"Enforce CRAG abstention gate (<0.38) + Claim-Level Groundedness Auditor",
),
"INSTRUCTION_SCHEMA_VIOLATION": (
"Constrained Decoding / Schema Guard",
"Switch to FSM Grammar / JSON-Schema decoding + Pydantic v2 extra='forbid'",
),
"TOOL_SELECTION_ARG_ERROR": (
"Agent Tool Policy / Sandboxed Dry-Run",
"Enforce read-before-write precondition DAG + typed tool argument validator",
),
"MULTITURN_STATE_DRIFT": (
"Episodic Memory / Explicit Checkpointer",
"Persist typed slot-state invariant store outside rolling chat transcript",
),
}
breakdown = attribution["failure_mode_breakdown"]
rows: list[dict[str, Any]] = []
for fm in FAILURE_MODE_ORDER:
info = breakdown[fm]
owner, fix = actions[fm]
rows.append(
{
"failure_mode": fm,
"count": info["count"],
"risk_loss": info["total_risk_loss"],
"share_of_risk_pct": round(float(info["share_of_risk"]) * 100.0, 1),
"owner": owner,
"remediation": fix,
}
)
rows.sort(key=lambda x: (-float(x["risk_loss"]), -int(x["count"])))
return rows
def run_full_ch25_wb25_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run complete WB-Ch25 Article #5 benchmark and assemble standardized workbench_panels."""
n_boot = 300 if quick else 2000
suites = build_stratified_eval_suites(seed=seed)
v1_records = suites["v1_baseline"]
v2_records = suites["v2_aggregate_mirage"]
v3_records = suites["v3_remediated"]
v1_attr = compute_conditional_fault_attribution(v1_records)
v2_attr = compute_conditional_fault_attribution(v2_records)
v3_attr = compute_conditional_fault_attribution(v3_records)
v1_vs_v2_slices = compare_models_by_slice(v1_records, v2_records, n_boot=n_boot, seed=seed)
v1_vs_v3_slices = compare_models_by_slice(v1_records, v3_records, n_boot=n_boot, seed=seed)
simpson = demonstrate_simpsons_paradox_traffic_shift()
waterfall_v2 = run_assertion_waterfall_benchmark(v2_records)
waterfall_v3 = run_assertion_waterfall_benchmark(v3_records)
policy = CIGatePolicy()
gate_v2 = evaluate_ci_release_gate(
v1_records,
v2_records,
candidate_version="v2_aggregate_mirage",
policy=policy,
n_boot=n_boot,
seed=seed,
)
gate_v3 = evaluate_ci_release_gate(
v1_records,
v3_records,
candidate_version="v3_remediated",
policy=policy,
n_boot=n_boot,
seed=seed,
)
playbook_v2 = build_remediation_playbook(v2_attr)
def _pct(v: float) -> str:
return f"{v * 100.0:.1f}%"
v2_slice_map = {s.slice_id: s for s in v1_vs_v2_slices}
v3_slice_map = {s.slice_id: s for s in v1_vs_v3_slices}
comp_v2 = v2_slice_map["compliance_citation"]
tool_v2 = v2_slice_map["agent_tool_use"]
easy_v2 = v2_slice_map["easy_paraphrase"]
v2_cond = v2_attr["conditional_probabilities"]
v2_break = v2_attr["failure_mode_breakdown"]
v1_tier1 = _pct(v1_attr["tier1_critical_pass_rate"])
v2_tier1 = _pct(v2_attr["tier1_critical_pass_rate"])
v1_overall = _pct(v1_attr["overall_pass_rate"])
v2_overall = _pct(v2_attr["overall_pass_rate"])
v3_overall = _pct(v3_attr["overall_pass_rate"])
risk_drop_pct = (
1.0 - v3_attr["expected_production_risk"] / v2_attr["expected_production_risk"]
) * 100.0
det_catch_pct = _pct(waterfall_v2["deterministic_failure_catch_rate"])
naive_acc_pct = _pct(waterfall_v2["naive_judge_rag_accuracy"])
ds_acc_pct = _pct(waterfall_v2["dawid_skene_rag_accuracy"])
e2e_acc_pct = _pct(waterfall_v2["waterfall_end_to_end_accuracy"])
tier1_vs_1j_pct = f"{waterfall_v2['cost_reduction_tier1_vs_naive_single_judge'] * 100.0:.2f}%"
tier1_vs_3j_pct = f"{waterfall_v2['cost_reduction_tier1_vs_naive_3judge'] * 100.0:.2f}%"
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_aggregate_mirage_vs_tier1",
"label": "Aggregate Mirage vs Tier-1 Critical (v1 -> v2)",
"value": f"{v2_overall} (+{gate_v2.overall_delta_pp:.1f}pp)",
"unit": f"(Tier-1: {v1_tier1} -> {v2_tier1})",
"status": "warn",
"detail": (
f"Easy slice +22.5pp masks -20.8pp drops in compliance_citation and "
f"agent_tool_use; Expected Risk jumps "
f"+{(gate_v2.expected_risk_ratio - 1.0) * 100:.1f}%."
),
},
{
"id": "kpi_worst_tier1_regression",
"label": "Max Critical Slice Drop (Compliance / Tool)",
"value": f"{comp_v2.delta_pp:+.1f}pp",
"unit": f"(McNemar p={comp_v2.mcnemar_p_value:.4f})",
"status": "warn",
"detail": (
f"Compliance ({_pct(comp_v2.base_pass_rate)}->"
f"{_pct(comp_v2.cand_pass_rate)}) and Agent Tool "
f"({_pct(tool_v2.base_pass_rate)}->{_pct(tool_v2.cand_pass_rate)}) "
"collapse in v2."
),
},
{
"id": "kpi_conditional_gen_fault",
"label": "P(Gen/CtxFail | GoldInCtx) vs P(RetMiss)",
"value": _pct(v2_cond["p_gen_fail_given_gold_in_ctx"]),
"unit": f"(RetMiss: {_pct(v2_cond['p_retrieval_miss'])})",
"status": "ok",
"detail": (
"Causal attribution separates Index misses from Context Utilization & "
"Groundedness failures when gold evidence was already retrieved."
),
},
{
"id": "kpi_deterministic_catch_rate",
"label": "Deterministic Waterfall Catch Rate ($0)",
"value": det_catch_pct,
"unit": (
f"({waterfall_v2['det_caught_failures']}/"
f"{waterfall_v2['true_failures']} fails, <0.2ms)"
),
"status": "ok",
"detail": (
"JSON Schema, Tool Preconditions, State Slots & Citations catch "
f"{waterfall_v2['det_caught_failures']}/{waterfall_v2['true_failures']} "
"failures before LLM Judge."
),
},
{
"id": "kpi_dawid_skene_kappa",
"label": "Calibrated Panel Kappa (Dawid-Skene vs Naive)",
"value": f"{waterfall_v2['dawid_skene_vs_true_kappa']:.3f}",
"unit": f"(vs Naive {waterfall_v2['naive_judge_vs_true_kappa']:.3f})",
"status": "ok",
"detail": (
"3-Judge Dawid-Skene EM on Layer-2 survivors boosts RAG accuracy from "
f"{naive_acc_pct} to {ds_acc_pct}; Tier-1 3-judge cost "
f"${waterfall_v2['waterfall_tier1_routed_cost_usd']:.3f} "
f"(-{tier1_vs_1j_pct} vs 1J / -{tier1_vs_3j_pct} vs 3J)."
),
},
{
"id": "kpi_remediated_ci_gate",
"label": "v3 Remediated Overall & Risk Reduction",
"value": f"{v3_overall} (PASS)",
"unit": (
f"(Risk {v2_attr['expected_production_risk']:.3f} -> "
f"{v3_attr['expected_production_risk']:.3f})"
),
"status": "ok",
"detail": (
f"Slice Non-Regression Gate BLOCKS v2 ({len(gate_v2.blocked_slices)} "
f"Tier-1 slices) and APPROVES v3 (-{risk_drop_pct:.1f}% risk)."
),
},
],
"bars": [
{
"id": "bar_simpson_slice_divergence",
"title": "Aggregate Mirage (v2 vs v1): Slice-Level Delta Pass Rate (pp)",
"metric_label": "Delta vs v1 (pp)",
"items": [
{
"label": s.slice_id,
"value": s.delta_pp,
"display": (
f"{s.title}: {s.delta_pp:+.1f}pp "
f"({_pct(s.base_pass_rate)} -> {_pct(s.cand_pass_rate)})"
),
"css_class": "is-fast" if s.delta_pp >= 0.0 else "is-slow",
}
for s in v1_vs_v2_slices
],
},
{
"id": "bar_six_failure_modes_risk",
"title": "6 MECE Failure Modes in v2: Share of Severity-Weighted Risk (%)",
"metric_label": "Risk Share (%)",
"items": [
{
"label": fm.lower(),
"value": round(float(v2_break[fm]["share_of_risk"]) * 100.0, 1),
"display": (
f"{fm}: {float(v2_break[fm]['share_of_risk']) * 100:.1f}% "
f"({v2_break[fm]['count']} cases)"
),
"css_class": "is-slow"
if float(v2_break[fm]["share_of_risk"]) >= 0.20
else ("is-mid" if float(v2_break[fm]["share_of_risk"]) >= 0.12 else "is-fast"),
}
for fm in FAILURE_MODE_ORDER
],
},
{
"id": "bar_release_risk_comparison",
"title": "Expected Production Risk per Request: v1 vs v2 Mirage vs v3 Remediated",
"metric_label": "Expected Risk Loss",
"items": [
{
"label": "v1_baseline",
"value": v1_attr["expected_production_risk"],
"display": (
f"v1 Baseline ({v1_overall} pass): "
f"{v1_attr['expected_production_risk']:.3f}"
),
"css_class": "is-mid",
},
{
"label": "v2_aggregate_mirage",
"value": v2_attr["expected_production_risk"],
"display": (
f"v2 Aggregate Mirage ({v2_overall} pass): "
f"{v2_attr['expected_production_risk']:.3f} (+55.4%)"
),
"css_class": "is-slow",
},
{
"label": "v3_remediated",
"value": v3_attr["expected_production_risk"],
"display": (
f"v3 Remediated ({v3_overall} pass): "
f"{v3_attr['expected_production_risk']:.3f} (-{risk_drop_pct:.1f}% vs v2)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_waterfall_det_vs_judge",
"title": "Assertion Waterfall Audit: Failure Catch & Agreement Quality (%)",
"metric_label": "Rate (%)",
"items": [
{
"label": "det_catch_rate",
"value": round(
float(waterfall_v2["deterministic_failure_catch_rate"]) * 100.0, 1
),
"display": f"Deterministic Layer-1 Failure Catch ($0): {det_catch_pct}",
"css_class": "is-fast",
},
{
"label": "naive_judge_acc",
"value": round(float(waterfall_v2["naive_judge_rag_accuracy"]) * 100.0, 1),
"display": f"Naive Single LLM Judge RAG Accuracy: {naive_acc_pct}",
"css_class": "is-slow",
},
{
"label": "dawid_skene_acc",
"value": round(float(waterfall_v2["dawid_skene_rag_accuracy"]) * 100.0, 1),
"display": f"Calibrated 3-Judge Dawid-Skene RAG Acc: {ds_acc_pct}",
"css_class": "is-mid",
},
{
"label": "waterfall_e2e_acc",
"value": round(
float(waterfall_v2["waterfall_end_to_end_accuracy"]) * 100.0, 1
),
"display": f"End-to-End Assertion Waterfall Accuracy: {e2e_acc_pct}",
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_slice_comparison_v1_v2_v3",
"title": "Stratified Golden Evaluation: v1 Baseline vs v2 Mirage vs v3 Remediated (N=240)",
"columns": [
"Eval Slice (N, Severity w)",
"v1 -> v2 (Delta / 95% CI)",
"McNemar p (v1 vs v2)",
"v3 Remediated (Delta vs v1)",
],
"rows": [
[
(
f"{v2_slice_map[sid].title} "
f"(n={v2_slice_map[sid].n_samples}, "
f"w={v2_slice_map[sid].severity_weight})"
),
(
f"{_pct(v2_slice_map[sid].base_pass_rate)} -> "
f"{_pct(v2_slice_map[sid].cand_pass_rate)} "
f"({v2_slice_map[sid].delta_pp:+.1f}pp "
f"[{v2_slice_map[sid].ci_low_pp:+.1f}, "
f"{v2_slice_map[sid].ci_high_pp:+.1f}])"
),
(
f"p={v2_slice_map[sid].mcnemar_p_value:.4f} "
f"(b={v2_slice_map[sid].mcnemar_b_regressions}, "
f"c={v2_slice_map[sid].mcnemar_c_improvements})"
),
(
f"{_pct(v3_slice_map[sid].cand_pass_rate)} "
f"({v3_slice_map[sid].delta_pp:+.1f}pp)"
),
]
for sid in SLICE_ORDER
]
+ [
[
"OVERALL AGGREGATE (N=240)",
f"{v1_overall} -> {v2_overall} (+{gate_v2.overall_delta_pp:.1f}pp MIRAGE)",
(
f"Risk {v1_attr['expected_production_risk']:.3f} -> "
f"{v2_attr['expected_production_risk']:.3f}"
),
(
f"{v3_overall} (+{gate_v3.overall_delta_pp:.1f}pp, "
f"Risk {v3_attr['expected_production_risk']:.3f})"
),
]
],
},
{
"id": "tbl_six_failure_modes_attribution",
"title": "6-Mode MECE Taxonomy & Causal Fault Attribution (Model v2 Mirage)",
"columns": [
"Failure Mode (MECE)",
"Count / Share of Fails",
"Severity Risk Loss (%)",
"Primary Engineering Owner",
],
"rows": [
[
fm,
(
f"{v2_break[fm]['count']} "
f"({float(v2_break[fm]['share_of_failures']) * 100:.1f}%)"
),
(
f"{v2_break[fm]['total_risk_loss']:.1f} "
f"({float(v2_break[fm]['share_of_risk']) * 100:.1f}%)"
),
str(v2_break[fm]["fault_owner"]),
]
for fm in FAILURE_MODE_ORDER
],
},
{
"id": "tbl_waterfall_and_judge_calibration",
"title": "Assertion Waterfall (Deterministic First) vs Always-LLM-Judge Audit (v2)",
"columns": [
"Evaluation Architecture",
"Failure Detection / Accuracy",
"Judge Calls & API Cost",
"Reliability / Agreement",
],
"rows": [
[
"Layer 1: Deterministic Assertions Only",
(
f"Catches {waterfall_v2['det_caught_failures']}/"
f"{waterfall_v2['true_failures']} ({det_catch_pct})"
),
(
"0 LLM calls ($0.00, "
f"{waterfall_v2['mean_deterministic_latency_ms']:.3f} ms/sample)"
),
"100% deterministic (0% false blame)",
],
[
"Naive Single Always-LLM-Judge",
f"Survivor RAG Acc {naive_acc_pct}",
(
f"{waterfall_v2['naive_all_single_judge_calls']} calls "
f"(${waterfall_v2['naive_all_single_judge_cost_usd']:.3f} | "
f"3-Judge all: {waterfall_v2['naive_all_3judge_calls']} calls = "
f"${waterfall_v2['naive_all_3judge_cost_usd']:.3f})"
),
(
f"kappa(J1,J2)={waterfall_v2['naive_judge_inter_rater_kappa']:.3f}, "
f"kappa(J1,True)={waterfall_v2['naive_judge_vs_true_kappa']:.3f}"
),
],
[
"Assertion Waterfall (Det -> Dawid-Skene RAG)",
f"Survivor RAG {ds_acc_pct} | E2E {e2e_acc_pct}",
(
f"Full RAG: {waterfall_v2['routed_full_rag_samples']}x3="
f"{waterfall_v2['waterfall_full_rag_3judge_calls']} calls "
f"(${waterfall_v2['waterfall_full_rag_cost_usd']:.3f}) | "
f"Tier-1: {waterfall_v2['routed_tier1_samples']}x3="
f"{waterfall_v2['waterfall_tier1_3judge_calls']} calls "
f"(${waterfall_v2['waterfall_tier1_routed_cost_usd']:.3f}, "
f"-{tier1_vs_1j_pct} vs 1J / -{tier1_vs_3j_pct} vs 3J)"
),
f"Dawid-Skene kappa(EM,True)={waterfall_v2['dawid_skene_vs_true_kappa']:.3f}",
],
],
},
{
"id": "tbl_ci_gates_and_playbook",
"title": "CI/CD Release Gate Decisions & Top Production Remediation Priorities",
"columns": [
"Candidate Release / Gate",
"Naive Aggregate Gate",
"Slice Non-Regression Gate",
"Primary Diagnostic / Action",
],
"rows": [
[
"v2_aggregate_mirage (vs v1)",
"PASS (+2.9pp overall)" if gate_v2.naive_aggregate_gate_passed else "FAIL",
"BLOCKED" if not gate_v2.slice_non_regression_gate_passed else "PASS",
(
f"Blocked {len(gate_v2.blocked_slices)} Tier-1 slices; "
f"risk ratio {gate_v2.expected_risk_ratio:.2f}x > 1.05x"
),
],
[
"v3_remediated (vs v1)",
"PASS (+15.4pp overall)" if gate_v3.naive_aggregate_gate_passed else "FAIL",
"APPROVED" if gate_v3.slice_non_regression_gate_passed else "BLOCKED",
(
"0 Tier-1 regressions; expected risk reduced to "
f"{gate_v3.cand_expected_risk:.3f} "
f"({gate_v3.expected_risk_ratio:.2f}x)"
),
],
[
f"Top Priority Fix #1: {playbook_v2[0]['failure_mode']}",
f"Risk {playbook_v2[0]['risk_loss']:.1f} ({playbook_v2[0]['share_of_risk_pct']}%)",
str(playbook_v2[0]["owner"]),
str(playbook_v2[0]["remediation"]),
],
[
f"Top Priority Fix #2: {playbook_v2[1]['failure_mode']}",
f"Risk {playbook_v2[1]['risk_loss']:.1f} ({playbook_v2[1]['share_of_risk_pct']}%)",
str(playbook_v2[1]["owner"]),
str(playbook_v2[1]["remediation"]),
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"n_samples": len(v1_records),
"n_boot": n_boot,
"synthetic_proxy_notice": (
"Offline deterministic synthetic evaluation suites & noisy judge panels "
"reproducing production failure modes without external LLM APIs."
),
"policy": policy.model_dump(),
},
"simpsons_paradox_traffic_shift": simpson.model_dump(),
"releases": {
"v1_baseline": v1_attr,
"v2_aggregate_mirage": v2_attr,
"v3_remediated": v3_attr,
},
"slice_comparisons": {
"v1_vs_v2": [s.model_dump() for s in v1_vs_v2_slices],
"v1_vs_v3": [s.model_dump() for s in v1_vs_v3_slices],
},
"assertion_waterfall": {
"v2_aggregate_mirage": waterfall_v2,
"v3_remediated": waterfall_v3,
},
"ci_gates": {
"v2_aggregate_mirage": gate_v2.model_dump(),
"v3_remediated": gate_v3.model_dump(),
},
"remediation_playbook_v2": playbook_v2,
"workbench_panels": workbench_panels,
"easy_slice_highlight": easy_v2.model_dump(),
}
"""End-to-end CLI benchmark runner for WB-Ch25 (`T1-P5-U03`: Evaluation by Failure Mode)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import failure_mode_eval_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from failure_mode_eval_lab.golden_eval_and_ci_gates import ( # noqa: E402
run_full_ch25_wb25_benchmark,
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for WB-Ch25 failure-mode benchmark execution."""
parser = argparse.ArgumentParser(
description=(
"Run WB-Ch25 (Article #5): Simpson's Paradox Aggregate Mirage, "
"6-Mode MECE Taxonomy, Deterministic Assertion Waterfall & CI Slice Gates."
)
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter bootstrap resample count for fast CI verification (<1s CPU).",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch25_wb25_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute WB-Ch25 benchmark, print telemetry summary, and write JSON artifact."""
args = parse_args(argv)
payload = run_full_ch25_wb25_benchmark(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
v1 = payload["releases"]["v1_baseline"]
v2 = payload["releases"]["v2_aggregate_mirage"]
v3 = payload["releases"]["v3_remediated"]
sim = payload["simpsons_paradox_traffic_shift"]
wf = payload["assertion_waterfall"]["v2_aggregate_mirage"]
g2 = payload["ci_gates"]["v2_aggregate_mirage"]
g3 = payload["ci_gates"]["v3_remediated"]
print("=== Ch 25 + WB-Ch25: LLM, RAG & Agent Evaluation by Failure Mode (Article #5) ===")
print(
f"[#5.1 Aggregate Mirage] v1={v1['overall_pass_rate'] * 100:.1f}% -> "
f"v2={v2['overall_pass_rate'] * 100:.1f}% (+{g2['overall_delta_pp']:.1f}pp) | "
f"Tier-1 Critical: {v1['tier1_critical_pass_rate'] * 100:.1f}% -> "
f"{v2['tier1_critical_pass_rate'] * 100:.1f}% | "
f"Risk={v1['expected_production_risk']:.3f} -> {v2['expected_production_risk']:.3f} | "
f"Simpson Shift Triggered={sim['paradox_triggered']} "
f"(Agg {sim['aggregate_delta_pp']:+.1f}pp while Easy {sim['easy_delta_pp']:+.1f}pp, "
f"Crit {sim['critical_delta_pp']:+.1f}pp)"
)
cond = v2["conditional_probabilities"]
print(
f"[#5.2 6-Mode Attribution] P(RetMiss)={cond['p_retrieval_miss'] * 100:.1f}% | "
f"P(CtxUtil|Gold)={cond['p_context_util_given_gold_in_ctx'] * 100:.1f}% | "
f"P(Halluc|Gold)={cond['p_hallucination_given_gold_in_ctx'] * 100:.1f}% | "
f"P(SchemaErr)={cond['p_schema_violation_on_api'] * 100:.1f}% | "
f"P(ToolErr)={cond['p_tool_error_on_agent'] * 100:.1f}% | "
f"P(StateDrift)={cond['p_state_drift_on_multiturn'] * 100:.1f}%"
)
print(
f"[#5.3 Waterfall & CI Gate] DetCatch={wf['deterministic_failure_catch_rate'] * 100:.1f}% "
f"({wf['det_caught_failures']}/{wf['true_failures']}, "
f"{wf['mean_deterministic_latency_ms']:.3f}ms) | "
f"Tier-1 3J={wf['routed_tier1_samples']}x3={wf['waterfall_tier1_3judge_calls']} calls "
f"(${wf['waterfall_tier1_routed_cost_usd']:.3f}, "
f"-{wf['cost_reduction_tier1_vs_naive_single_judge'] * 100:.2f}% vs 1J / "
f"-{wf['cost_reduction_tier1_vs_naive_3judge'] * 100:.2f}% vs 3J) | "
f"Judge Kappa {wf['naive_judge_vs_true_kappa']:.3f} -> "
f"DS {wf['dawid_skene_vs_true_kappa']:.3f} | "
f"v2 Gate: Naive={g2['naive_aggregate_gate_passed']} vs "
f"Slice={g2['slice_non_regression_gate_passed']} (blocked={len(g2['blocked_slices'])}) | "
f"v3={v3['overall_pass_rate'] * 100:.1f}% (Risk={v3['expected_production_risk']:.3f}, "
f"SliceGate={g3['slice_non_regression_gate_passed']})"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""20 deterministic CPU-only tests for WB-Ch25 (`failure_mode_eval_lab`, Unit T1-P5-U03)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from failure_mode_eval_lab import (
FAILURE_MODE_ORDER,
SLICE_ORDER,
CIGatePolicy,
EvalSampleRecord,
ToolCallTrace,
build_remediation_playbook,
build_stratified_eval_suites,
classify_sample_failure_mode,
compare_models_by_slice,
compute_cohens_kappa,
compute_conditional_fault_attribution,
compute_mcnemar_test,
dawid_skene_em,
demonstrate_simpsons_paradox_traffic_shift,
evaluate_ci_release_gate,
paired_bootstrap_delta_ci,
run_assertion_waterfall_benchmark,
run_deterministic_assertions,
run_full_ch25_wb25_benchmark,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
BANNED_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
@pytest.fixture(scope="module")
def shared_suites() -> dict[str, list[EvalSampleRecord]]:
"""Build deterministic 240-sample paired suites once per test module."""
return build_stratified_eval_suites(seed=42)
@pytest.fixture(scope="module")
def shared_benchmark() -> dict[str, object]:
"""Run full WB-Ch25 benchmark in quick bootstrap mode once per test module."""
return run_full_ch25_wb25_benchmark(seed=42, quick=True)
def test_01_ast_no_unsafe_deserializers() -> None:
"""AST security gate: strictly ban pickle/joblib/dill/marshal across src/ and scripts/."""
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 3
for path in py_files:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_pkg = alias.name.split(".")[0]
assert root_pkg not in BANNED_DESERIALIZERS, f"Banned import {root_pkg} in {path}"
elif isinstance(node, ast.ImportFrom) and node.module:
root_pkg = node.module.split(".")[0]
assert root_pkg not in BANNED_DESERIALIZERS, f"Banned import {root_pkg} in {path}"
def test_02_pydantic_v2_strict_contracts_forbid_extra_fields() -> None:
"""All Pydantic v2 configs and trace schemas strictly forbid unknown fields and invalid bounds."""
with pytest.raises(ValidationError):
CIGatePolicy(unknown_budget=5.0) # type: ignore[call-arg]
with pytest.raises(ValidationError):
CIGatePolicy(tier1_floor_pass_rate=1.2)
with pytest.raises(ValidationError):
ToolCallTrace(tool_name="issue_refund", arguments={}, extra_attr=True) # type: ignore[call-arg]
with pytest.raises(ValidationError):
EvalSampleRecord(
sample_id="q_err",
model_version="v1",
slice_id="easy_paraphrase",
tier="tier2_standard",
severity_weight=1.0,
query_text="hello",
raw_output="world",
supported_claim_ratio=1.5,
)
def test_03_stratified_suite_size_and_slice_integrity(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Verify 240 paired golden samples across all 6 slices for v1, v2, and v3."""
assert set(shared_suites.keys()) == {"v1_baseline", "v2_aggregate_mirage", "v3_remediated"}
for version_recs in shared_suites.values():
assert len(version_recs) == 240
slice_counts = {sid: sum(1 for r in version_recs if r.slice_id == sid) for sid in SLICE_ORDER}
assert slice_counts == {
"easy_paraphrase": 120,
"long_context_rag": 24,
"compliance_citation": 24,
"structured_json_api": 24,
"agent_tool_use": 24,
"multiturn_stateful": 24,
}
ids_v1 = [r.sample_id for r in shared_suites["v1_baseline"]]
ids_v2 = [r.sample_id for r in shared_suites["v2_aggregate_mirage"]]
assert ids_v1 == ids_v2
def test_04_simpsons_paradox_aggregate_mirage_and_traffic_shift(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Prove both Volume-Masking Aggregate Mirage (v1->v2) and pure Simpson Traffic Shift reversal."""
v1_attr = compute_conditional_fault_attribution(shared_suites["v1_baseline"])
v2_attr = compute_conditional_fault_attribution(shared_suites["v2_aggregate_mirage"])
# Global score rises while Tier-1 critical accuracy collapses and Expected Risk surges
assert v2_attr["overall_pass_rate"] > v1_attr["overall_pass_rate"] + 0.02
assert v2_attr["tier1_critical_pass_rate"] < v1_attr["tier1_critical_pass_rate"] - 0.14
assert v2_attr["expected_production_risk"] > v1_attr["expected_production_risk"] * 1.5
# Pure Simpson reversal: every slice drops, yet traffic shift increases global score
sim = demonstrate_simpsons_paradox_traffic_shift()
assert sim.paradox_triggered is True
assert sim.easy_delta_pp < 0.0
assert sim.critical_delta_pp < 0.0
assert sim.aggregate_delta_pp > 0.0
def test_05_mece_priority_causal_attribution_prevents_double_counting() -> None:
"""A sample missing gold retrieval AND failing groundedness is attributed solely to RETRIEVAL_MISS."""
record = EvalSampleRecord(
sample_id="q_mece_1",
model_version="test",
slice_id="compliance_citation",
tier="tier1_critical",
severity_weight=4.0,
query_text="Audit SLA hold",
requires_retrieval=True,
gold_chunk_id="doc_01_s1",
gold_context_facts=["99.1%"],
retrieved_chunk_ids=["decoy_1", "decoy_2"],
context_utilization_ok=False,
require_citation_tag=True,
raw_output="Hallucinated 50% [POL-999]",
supported_claim_ratio=0.2,
has_contradiction=True,
)
cls = classify_sample_failure_mode(record)
assert cls.passed is False
assert cls.gold_in_ctx is False
assert cls.primary_failure_mode == "RETRIEVAL_MISS"
assert "CONTEXT_UTILIZATION_ERROR" not in cls.secondary_flags
assert "GROUNDEDNESS_HALLUCINATION" in cls.secondary_flags
assert "Index" in cls.fault_owner
def test_06_all_six_canonical_failure_modes_are_detected_distinctly() -> None:
"""Each of the 6 canonical failure modes triggers independently with the right causal owner."""
samples = [
EvalSampleRecord(
sample_id="f1",
model_version="t",
slice_id="easy_paraphrase",
tier="tier2_standard",
severity_weight=1.0,
query_text="q",
requires_retrieval=True,
gold_chunk_id="doc_1",
retrieved_chunk_ids=["decoy_1"],
raw_output="ans",
supported_claim_ratio=1.0,
),
EvalSampleRecord(
sample_id="f2",
model_version="t",
slice_id="long_context_rag",
tier="tier1_critical",
severity_weight=2.5,
query_text="q",
requires_retrieval=True,
gold_chunk_id="doc_1",
gold_context_facts=["99.0%"],
retrieved_chunk_ids=["d0", "d1", "doc_1", "d2", "d3"],
gold_chunk_position=2,
context_utilization_ok=False,
raw_output="99.0% [doc_1]",
supported_claim_ratio=1.0,
),
EvalSampleRecord(
sample_id="f3",
model_version="t",
slice_id="compliance_citation",
tier="tier1_critical",
severity_weight=4.0,
query_text="q",
requires_retrieval=True,
gold_chunk_id="doc_1",
gold_context_facts=["99.0%"],
retrieved_chunk_ids=["doc_1"],
require_citation_tag=True,
raw_output="99.0% waives hold [doc_1]",
supported_claim_ratio=0.4,
has_contradiction=True,
),
EvalSampleRecord(
sample_id="f4",
model_version="t",
slice_id="structured_json_api",
tier="tier1_critical",
severity_weight=3.5,
query_text="q",
schema_name="RiskDecisionPayload",
raw_output='```json\n{"decision": "APPROVE"}\n```',
supported_claim_ratio=1.0,
),
EvalSampleRecord(
sample_id="f5",
model_version="t",
slice_id="agent_tool_use",
tier="tier1_critical",
severity_weight=4.5,
query_text="q",
raw_output="refund",
expected_tool="issue_refund",
required_prereq_tool="verify_account_ownership",
tool_trace=[
ToolCallTrace(
tool_name="issue_refund",
arguments={"account_id": "ACC-1", "amount_usd": 50.0, "idempotency_key": "idem-123456"},
)
],
supported_claim_ratio=1.0,
),
EvalSampleRecord(
sample_id="f6",
model_version="t",
slice_id="multiturn_stateful",
tier="tier1_critical",
severity_weight=3.0,
query_text="q",
raw_output="deploy us-east-1",
expected_state_constraints={"region": "ap-southeast-1"},
observed_state_constraints={"region": "us-east-1"},
supported_claim_ratio=1.0,
),
]
modes = [classify_sample_failure_mode(s).primary_failure_mode for s in samples]
assert modes == list(FAILURE_MODE_ORDER)
def test_07_conditional_fault_attribution_probabilities_on_v2(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Verify exact MECE partition and conditional fault probabilities P(GenFail | GoldInCtx)."""
v2_recs = shared_suites["v2_aggregate_mirage"]
attr = compute_conditional_fault_attribution(v2_recs)
breakdown = attr["failure_mode_breakdown"]
total_failed_classified = sum(int(breakdown[fm]["count"]) for fm in FAILURE_MODE_ORDER)
assert total_failed_classified == attr["failed_count"]
assert abs(sum(float(breakdown[fm]["share_of_risk"]) for fm in FAILURE_MODE_ORDER) - 1.0) < 1e-3
cond = attr["conditional_probabilities"]
assert 0.0 < cond["p_retrieval_miss"] < 0.10
assert cond["p_gen_fail_given_gold_in_ctx"] > cond["p_retrieval_miss"]
assert abs(cond["p_tool_error_on_agent"] - (8.0 / 24.0)) < 1e-3
def test_08_mcnemar_exact_and_paired_bootstrap_ci(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Validate McNemar discordant statistics and paired bootstrap CI across all 6 slices."""
comps = compare_models_by_slice(
shared_suites["v1_baseline"], shared_suites["v2_aggregate_mirage"], n_boot=500, seed=42
)
comp_map = {c.slice_id: c for c in comps}
assert comp_map["easy_paraphrase"].delta_pp > 20.0
assert comp_map["easy_paraphrase"].mcnemar_p_value < 0.001
assert comp_map["compliance_citation"].delta_pp < -15.0
assert comp_map["compliance_citation"].ci_high_pp < 0.0
assert comp_map["compliance_citation"].mcnemar_p_value < 0.07
assert comp_map["agent_tool_use"].delta_pp < -15.0
assert comp_map["agent_tool_use"].mcnemar_b_regressions == 5
assert comp_map["agent_tool_use"].ci_low_pp < comp_map["agent_tool_use"].delta_pp
@given(
n=st.integers(min_value=12, max_value=60),
flip_seed=st.integers(min_value=1, max_value=500),
)
@settings(max_examples=25)
def test_09_hypothesis_invariants_mcnemar_kappa_bootstrap(n: int, flip_seed: int) -> None:
"""Property-based invariants for McNemar p-values, paired bootstrap CI ordering, and kappa bounds."""
rng = np.random.default_rng(flip_seed)
base = [bool(x) for x in rng.integers(0, 2, size=n)]
cand = [bool(x) for x in rng.integers(0, 2, size=n)]
b, c, chi2_cc, p_val = compute_mcnemar_test(base, cand)
assert b >= 0 and c >= 0
assert chi2_cc >= 0.0
assert 0.0 <= p_val <= 1.0
delta, ci_lo, ci_hi = paired_bootstrap_delta_ci(base, cand, n_boot=200, seed=flip_seed)
assert ci_lo - 1e-6 <= delta <= ci_hi + 1e-6
kappa_self = compute_cohens_kappa([int(x) for x in base], [int(x) for x in base])
assert kappa_self == 1.0
def test_10_deterministic_assertions_catch_json_tool_state_and_citations() -> None:
"""Layer-1 deterministic assertions execute sub-millisecond at $0 and flag exact defect types."""
bad_json = EvalSampleRecord(
sample_id="d1",
model_version="v2",
slice_id="structured_json_api",
tier="tier1_critical",
severity_weight=3.5,
query_text="Emit JSON",
schema_name="RiskDecisionPayload",
raw_output=(
'{"decision": "INVALID_ENUM", "risk_tier": "LOW", '
'"ticket_id": "TCK-0001", "confidence": 0.9}'
),
supported_claim_ratio=1.0,
)
res_json = run_deterministic_assertions(bad_json)
assert res_json.det_passed is False
assert "strict_json_schema_violation" in res_json.failed_checks
assert res_json.elapsed_ms < 25.0
bad_tool = EvalSampleRecord(
sample_id="d2",
model_version="v2",
slice_id="agent_tool_use",
tier="tier1_critical",
severity_weight=4.5,
query_text="Refund",
raw_output="done",
expected_tool="issue_refund",
required_prereq_tool="verify_account_ownership",
tool_trace=[
ToolCallTrace(
tool_name="issue_refund",
arguments={"account_id": "ACC-9", "amount_usd": 100.0, "idempotency_key": "idem-abcd1234"},
),
ToolCallTrace(tool_name="verify_account_ownership", arguments={"account_id": "ACC-9"}),
],
supported_claim_ratio=1.0,
)
res_tool = run_deterministic_assertions(bad_tool)
assert res_tool.det_passed is False
assert "tool_selection_prereq_or_args_violation" in res_tool.failed_checks
def test_11_assertion_waterfall_saves_judge_calls_and_catches_majority_at_zero_cost(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Assertion Waterfall catches >=80% at $0 and distinguishes routed samples vs 3x 3-judge calls."""
wf = run_assertion_waterfall_benchmark(shared_suites["v2_aggregate_mirage"])
assert wf["deterministic_api_cost_usd"] == 0.0
assert wf["mean_deterministic_latency_ms"] < 1.0
assert wf["deterministic_failure_catch_rate"] >= 0.80
assert wf["num_judges"] == 3
assert wf["naive_all_single_judge_calls"] == 240
assert wf["naive_all_single_judge_cost_usd"] == 0.96
assert wf["naive_all_3judge_calls"] == 720
assert wf["naive_all_3judge_cost_usd"] == 2.88
assert wf["routed_full_rag_samples"] == 157
assert wf["waterfall_full_rag_3judge_calls"] == 471
assert wf["waterfall_full_rag_cost_usd"] == 1.884
# Full-RAG 3-judge ($1.884) costs more than naive single-judge ($0.960), proving Tier-1 routing is key.
assert wf["waterfall_full_rag_cost_usd"] > wf["naive_all_single_judge_cost_usd"]
assert wf["routed_tier1_samples"] == 39
assert wf["waterfall_tier1_3judge_calls"] == 117
assert wf["waterfall_tier1_routed_cost_usd"] == 0.468
assert wf["waterfall_tier1_routed_cost_usd"] < wf["naive_all_single_judge_cost_usd"]
assert wf["cost_reduction_tier1_vs_naive_single_judge"] == 0.5125
assert wf["cost_reduction_tier1_vs_naive_3judge"] == 0.8375
assert wf["waterfall_end_to_end_accuracy"] > wf["naive_judge_rag_accuracy"]
def test_12_dawid_skene_calibration_lifts_kappa_over_naive_single_judge(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Dawid-Skene EM fitted strictly on Layer-2 survivors beats single noisy judge on accuracy and kappa."""
wf = run_assertion_waterfall_benchmark(shared_suites["v2_aggregate_mirage"])
assert wf["dawid_skene_rag_accuracy"] > wf["naive_judge_rag_accuracy"] + 0.03
assert wf["dawid_skene_vs_true_kappa"] > wf["naive_judge_vs_true_kappa"] + 0.15
# Verify v3 survivors (100% pass) do not suffer boundary collapse under MAP-regularized EM
wf_v3 = run_assertion_waterfall_benchmark(shared_suites["v3_remediated"])
assert wf_v3["dawid_skene_rag_accuracy"] >= 0.98
# Direct synthetic Dawid-Skene sanity check with 1 inverted/noisy rater + 2 good raters
truth = np.array([1, 1, 1, 1, 0, 0, 0, 0] * 10, dtype=np.int64)
r1 = truth.copy()
r2 = truth.copy()
r3 = 1 - truth # adversarial flipped rater
r1[0] = 0
r2[4] = 1
votes = np.column_stack([r1, r2, r3])
_, consensus = dawid_skene_em(votes)
assert float(np.mean(consensus == truth)) >= 0.95
def test_13_ci_gate_naive_passes_mirage_but_slice_gate_blocks_v2(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Naive Aggregate Gate falsely approves v2 Mirage, while Slice Non-Regression Gate blocks it."""
report_v2 = evaluate_ci_release_gate(
shared_suites["v1_baseline"],
shared_suites["v2_aggregate_mirage"],
candidate_version="v2_aggregate_mirage",
n_boot=400,
seed=42,
)
assert report_v2.naive_aggregate_gate_passed is True
assert report_v2.slice_non_regression_gate_passed is False
assert len(report_v2.blocked_slices) == 5
assert "compliance_citation" in report_v2.blocked_slices
assert "agent_tool_use" in report_v2.blocked_slices
assert report_v2.expected_risk_ratio > 1.50
def test_14_ci_gate_approves_remediated_v3_and_slashes_risk(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Targeted Remediation Release v3 passes both Naive and Slice Non-Regression CI Gates."""
report_v3 = evaluate_ci_release_gate(
shared_suites["v1_baseline"],
shared_suites["v3_remediated"],
candidate_version="v3_remediated",
n_boot=400,
seed=42,
)
assert report_v3.naive_aggregate_gate_passed is True
assert report_v3.slice_non_regression_gate_passed is True
assert report_v3.blocked_slices == []
assert report_v3.cand_overall_pass_rate >= 0.95
assert report_v3.expected_risk_ratio < 0.30
def test_15_remediation_playbook_prioritizes_highest_risk_modes(
shared_suites: dict[str, list[EvalSampleRecord]],
) -> None:
"""Playbook ranks failure modes strictly descending by severity-weighted production risk."""
v2_attr = compute_conditional_fault_attribution(shared_suites["v2_aggregate_mirage"])
playbook = build_remediation_playbook(v2_attr)
assert len(playbook) == 6
risks = [float(item["risk_loss"]) for item in playbook]
assert risks == sorted(risks, reverse=True)
assert playbook[0]["failure_mode"] == "TOOL_SELECTION_ARG_ERROR"
assert playbook[1]["failure_mode"] in ("GROUNDEDNESS_HALLUCINATION", "INSTRUCTION_SCHEMA_VIOLATION")
def test_16_full_benchmark_determinism() -> None:
"""Running the full benchmark twice with seed=42 yields identical metrics across runs."""
r1 = run_full_ch25_wb25_benchmark(seed=42, quick=True)
r2 = run_full_ch25_wb25_benchmark(seed=42, quick=True)
assert r1["releases"] == r2["releases"]
assert r1["ci_gates"] == r2["ci_gates"]
assert r1["slice_comparisons"] == r2["slice_comparisons"]
def test_17_error_handling_for_mismatched_paired_sequences() -> None:
"""Statistical comparison functions raise explicit ValueError on invalid or mismatched inputs."""
with pytest.raises(ValueError):
compute_mcnemar_test([True, False], [True])
with pytest.raises(ValueError):
paired_bootstrap_delta_ci([], [])
with pytest.raises(ValueError):
compute_cohens_kappa([1, 0], [1])
with pytest.raises(ValueError):
dawid_skene_em(np.ones((5, 1), dtype=np.int64))
def test_18_cli_artifact_and_workbench_panels_schema(
tmp_path: Path, shared_benchmark: dict[str, object]
) -> None:
"""CLI execution produces valid JSON containing 6 KPIs, 4 bars, and 4 tables."""
out_file = tmp_path / "ch25_quick_check.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Article #5" in proc.stdout
loaded = json.loads(out_file.read_text(encoding="utf-8"))
panels = loaded["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
assert isinstance(shared_benchmark["workbench_panels"], dict)
def test_19_generic_fabricated_citation_verification() -> None:
"""Any [TAG-123] citation absent from retrieved_chunk_ids is caught, while retrieved IDs pass."""
fabricated = EvalSampleRecord(
sample_id="cit_1",
model_version="v2",
slice_id="compliance_citation",
tier="tier1_critical",
severity_weight=4.0,
query_text="Verify policy SLA",
requires_retrieval=True,
gold_chunk_id="SEC-101",
gold_context_facts=["99.5%"],
retrieved_chunk_ids=["SEC-101", "DOC-202"],
require_citation_tag=True,
raw_output="SLA is 99.5% per [SEC-101] and fabricated [REG-404].",
supported_claim_ratio=0.5,
)
res_fab = run_deterministic_assertions(fabricated)
assert res_fab.det_passed is False
assert "forbidden_fabricated_citation" in res_fab.failed_checks
grounded = fabricated.model_copy(
update={
"sample_id": "cit_2",
"raw_output": "SLA is 99.5% per [SEC-101] and [DOC-202].",
"supported_claim_ratio": 1.0,
}
)
res_ok = run_deterministic_assertions(grounded)
assert res_ok.det_passed is True
assert res_ok.failed_checks == []
def test_20_mcnemar_alpha_governs_borderline_ci_gate_verdict() -> None:
"""Tightening or loosening CIGatePolicy.mcnemar_alpha flips a borderline slice gate verdict."""
base_records: list[EvalSampleRecord] = []
cand_records: list[EvalSampleRecord] = []
for idx in range(240):
# Baseline has 10 existing failures (idx >= 230) so base_expected_risk > 0.
base_fail = idx >= 230
base_records.append(
EvalSampleRecord(
sample_id=f"c_{idx:03d}",
model_version="v1",
slice_id="compliance_citation",
tier="tier1_critical",
severity_weight=4.0,
query_text="Audit SLA",
requires_retrieval=True,
gold_chunk_id="doc_01_s1",
gold_context_facts=["99.0%"],
retrieved_chunk_ids=["doc_01_s1"],
require_citation_tag=True,
raw_output="SLA 99.0% [doc_01_s1]." if not base_fail else "Unverified override [doc_01_s1].",
supported_claim_ratio=1.0 if not base_fail else 0.0,
has_contradiction=base_fail,
)
)
# 6 regressions out of 240 -> delta = -2.5pp (within -3.0pp budget), pass_rate = 93.3% (>=78%),
# exact McNemar p = 2 * 0.5^6 = 0.03125
cand_fail = base_fail or (idx < 6)
cand_records.append(
EvalSampleRecord(
sample_id=f"c_{idx:03d}",
model_version="v2",
slice_id="compliance_citation",
tier="tier1_critical",
severity_weight=4.0,
query_text="Audit SLA",
requires_retrieval=True,
gold_chunk_id="doc_01_s1",
gold_context_facts=["99.0%"],
retrieved_chunk_ids=["doc_01_s1"],
require_citation_tag=True,
raw_output="SLA 99.0% [doc_01_s1]." if not cand_fail else "Unverified override [doc_01_s1].",
supported_claim_ratio=1.0 if not cand_fail else 0.0,
has_contradiction=cand_fail,
)
)
# Add 1 passing record per remaining slice so compare_models_by_slice covers SLICE_ORDER
for slice_id in SLICE_ORDER:
if slice_id == "compliance_citation":
continue
rec = EvalSampleRecord(
sample_id=f"pad_{slice_id}",
model_version="v1",
slice_id=slice_id,
tier="tier2_standard" if slice_id == "easy_paraphrase" else "tier1_critical",
severity_weight=1.0,
query_text="ok",
raw_output="ok",
supported_claim_ratio=1.0,
)
base_records.append(rec)
cand_records.append(rec.model_copy(update={"model_version": "v2"}))
loose_alpha_policy = CIGatePolicy(
max_slice_regression_pp=3.0,
tier1_floor_pass_rate=0.78,
max_expected_risk_ratio=1.8,
min_overall_delta_pp=-5.0,
mcnemar_alpha=0.01,
)
strict_alpha_policy = loose_alpha_policy.model_copy(update={"mcnemar_alpha": 0.05})
rep_loose = evaluate_ci_release_gate(
base_records, cand_records, candidate_version="cand", policy=loose_alpha_policy, n_boot=200
)
rep_strict = evaluate_ci_release_gate(
base_records, cand_records, candidate_version="cand", policy=strict_alpha_policy, n_boot=200
)
assert rep_loose.slice_non_regression_gate_passed is True
assert rep_loose.blocked_slices == []
assert rep_strict.slice_non_regression_gate_passed is False
assert rep_strict.blocked_slices == ["compliance_citation"]
assert any("mcnemar" in reason.lower() for reason in rep_strict.blocking_reasons)
WB-Ch25 (N = 240), mô hình v2 nâng điểm trung bình toàn cục từ 81.2% lên 84.2% (+2.9pp) nhờ phân khúc easy_paraphrase (50% tập dữ liệu) tăng +22.5pp, trong khi cả 5/5 phân khúc Tier-1 trọng yếu sụt -12.5pp đến -20.8pp và Rủi ro Sản xuất Kỳ vọng tăng +55.4% (0.346 -> 0.537). Kết luận nào ĐÚNG?+22.5pp trên 120 câu dễ che lấp -20.8pp ở nhóm tuân thủ & gọi công cụ (Tier-1 rơi 86.7% -> 70.0%), và dịch chuyển tỷ trọng dễ 30% -> 80% đảo chiều dấu biến thiên tổng hợp (+3.6pp dù hai lát cắt đều giảm -2.0pp và -14.0pp).
MECE (classify_sample_failure_mode), một truy vấn RAG không tìm thấy đoạn văn đúng trong Top-\(k\) (gold_chunk_id vắng mặt) và đồng thời bộ sinh tự bịa ra mã chính sách [POL-999]. Vì sao cây ưu tiên nhân quả phải gán nhãn lỗi chính là RETRIEVAL_MISS thay vì GROUNDEDNESS_HALLUCINATION?MECE theo cây ưu tiên thượng nguồn \(\to\) hạ nguồn đảm bảo tổng số ca lỗi cộng lại khớp 100% (38/38 ca trên v2) và tách rạch ròi trách nhiệm giữa Retriever (P(RetMiss) = 3.0%) và Generator/Context khi đã có chứng cứ (P(GenFail | GoldInCtx) = 6.8%).
CONTEXT_UTILIZATION_ERROR (FM-2) và RETRIEVAL_MISS (FM-1) trên phân khúc long_context_rag trong WB-Ch25, nhận định nào ĐÚNG?RETRIEVAL_MISS (GoldInCtx = False), CONTEXT_UTILIZATION_ERROR xảy ra khi GoldInCtx = True nhưng mô hình bỏ qua bằng chứng nằm giữa cửa sổ hoặc bị nhiễu. Khắc phục bằng Cross-Encoder đẩy chứng cứ lên hai đầu ngữ cảnh và giữ mật độ tín hiệu trong ngưỡng 20%–40%.
6 chế độ lỗi trên phiên bản v2_aggregate_mirage của WB-Ch25, ba chế độ lỗi tác vụ cấu trúc & Agent (FM-4, FM-5, FM-6) đóng góp tổng cộng bao nhiêu phần trăm Rủi ro Sản xuất Kỳ vọng và lỗi nào đứng đầu bảng rủi ro?v2, TOOL_SELECTION_ARG_ERROR (8 ca, w=4.5 \(\to 36.0\) rủi ro, 27.9%), INSTRUCTION_SCHEMA_VIOLATION (7 ca, w=3.5 \(\to 24.5\), 19.0%) và MULTITURN_STATE_DRIFT (7 ca, w=3.0 \(\to 21.0\), 16.3%) cộng lại chiếm 63.2% tổng rủi ro.
v1 và v2 trên cùng một tập N = 24 mẫu ghép cặp ở lát cắt compliance_citation (b = 5 ca v1 đúng nhưng v2 sai; c = 0 ca v1 sai nhưng v2 đúng), vì sao nên dùng Kiểm định Chính xác McNemar và Paired Bootstrap 95% CI thay vì t-test độc lập?v1 và v2 tương quan dương; McNemar kiểm định chính xác trên (b=5, c=0) (p = 0.0625) và Paired Bootstrap tái mẫu theo từng cặp (v1_i, v2_i) cho CI [-37.5, -4.2] pp sắc nét.
Deterministic Assertions First) trong golden_eval_and_ci_gates.py trên bộ dữ liệu v2 (38 ca lỗi trên 240 mẫu), khẳng định nào CHÍNH XÁC?Article #5: mọi lỗi có thể kiểm chứng bằng chương trình (JSON, tool trace, state slots, trích dẫn không nằm trong retrieved_chunk_ids) phải chặn ngay ở tầng tất định < 0.2 ms ($0), để lại đúng 5 ca lỗi ngữ nghĩa tinh vi cho giám khảo (86.8% catch rate).
$0.004/lượt đơn) với Assertion Waterfall + Hội đồng 3 Giám khảo Dawid-Skene EM ($0.012/mẫu khi định tuyến các ca RAG sống sót qua Tầng 1), kết quả thực nghiệm WB-Ch25 chỉ ra điều gì?3 × $0.004 = $0.012/mẫu, định tuyến cả 157 ca RAG sống sót (471 lượt = $1.884) đắt hơn 1-judge ($0.960); chỉ định tuyến 39 ca Tier-1 (117 lượt = $0.468) mới tiết kiệm -51.25% vs 1-judge và -83.75% vs 3-judge ($2.880), trong khi Dawid–Skene EM trên 157 ca sống sót nâng \(\kappa\) từ 0.044 -> 0.587.
CI/CD trên phiên bản v2_aggregate_mirage và v3_remediated trong WB-Ch25 (ngân sách tụt tối đa -3.0pp, sàn Tier-1 >= 78.0%, tỷ lệ rủi ro tối đa 1.05x), phát biểu nào ĐÚNG?SliceNonRegressionGate bảo vệ sản xuất bằng cách chặn đứng v2 dù điểm tổng hợp tăng +2.9pp, còn Playbook nhắm trúng nguyên nhân gốc đưa v3 lên 96.7% tổng thể (96.7% Tier-1, rủi ro 0.075, 0 lát cắt vi phạm).
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 — Chứng minh Ảo ảnh Điểm Tổng hợp và Nghịch lý Simpson 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính điểm tổng hợp có trọng số \(\text{Agg}(w) = w \cdot r_{\text{easy}} + (1 - w) \cdot r_{\text{crit}}\) và Rủi ro Sản xuất Kỳ vọng \(\frac{1}{N}\sum w_i \mathbb{I}[\text{fail}_i]\) cho v1 và v2 trên 240 mẫu.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi demonstrate_simpsons_paradox_traffic_shift() trong failure_taxonomy_and_metrics.py (Test 04) để kiểm tra đảo chiều dấu khi tỷ trọng dễ tăng từ 30% -> 80%.
Tiêu chí Đáp án & Số đối chứng
Tại mix = 50% (N=240), v1 -> v2 tăng tổng thể 81.2% -> 84.2% (+2.9pp) nhưng Tier-1 sụt 86.7% -> 70.0% và Expected Risk tăng +55.4% (0.346 -> 0.537). Dưới dịch chuyển lưu lượng 30% -> 80%, ngay cả khi easy giảm -2.0pp (94% -> 92%) và critical giảm -14.0pp (78% -> 64%), điểm tổng hợp vẫn nhảy ảo +3.6pp (82.8% -> 86.4%).
Bài tập 2 — Thiết kế Cây Ưu tiên 6 Chế độ Lỗi MECE và Quy kết Có điều kiện 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích thứ tự ưu tiên RETRIEVAL_MISS -> SCHEMA -> TOOL -> STATE -> CONTEXT_UTILIZATION -> GROUNDEDNESS và tính \(P(\text{RetMiss})\) vs \(P(\text{GenFail} \mid \text{GoldInCtx})\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra hàm classify_sample_failure_mode và compute_conditional_fault_attribution trong Tests 05–07.
Tiêu chí Đáp án & Số đối chứng
Thứ tự ưu tiên nhân quả đảm bảo phân hoạch MECE (sum(count_m) = 38 lỗi của v2, không đếm trùng). Trên v2, P(RetMiss) = 3.0% (5/168) còn P(GenFail | GoldInCtx) = 6.8% (11/163: 3.7% Context Util + 3.1% Hallucination), tách rõ trách nhiệm giữa Index/Retriever và Generator/Reranker.
Bài tập 3 — Kiểm định Chính xác McNemar và Paired Bootstrap 95% CI Theo Lát cắt 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lập bảng ngẫu nhiên ghép cặp \(2 \times 2\) cho compliance_citation (b=5, c=0) và easy_paraphrase (b=0, c=27). Viết công thức p-value nhị thức chính xác hai phía, chi2 hiệu chỉnh liên tục và quy tắc mcnemar_alpha.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy compare_models_by_slice với n_boot = 2000 và kiểm tra bất biến Hypothesis trong Tests 08–09, 20.
Tiêu chí Đáp án & Số đối chứng
Trên compliance_citation (n=24), (b=5, c=0) cho chi2_cc = (5-1)^2 / 5 = 3.20 và p = 2 * 0.5^5 = 0.0625, với Paired Bootstrap 95% CI là [-37.5, -4.2] pp (toàn bộ khoảng tin cậy nằm dưới 0). Trên easy_paraphrase, (b=0, c=27) cho p < 0.0001 ([+15.0, +30.0] pp). Khi \(\Delta_s < 0\) và p < mcnemar_alpha (Test 20), cổng CI chặn phát hành ngay cả trong ngưỡng dung sai delta_pp.
Bài tập 4 — Xây dựng Thác Assertion Waterfall và Hiệu chuẩn Giám khảo Dawid-Skene EM 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân biệt các kiểm chứng chạy ở Tầng 1 (jsonschema, DAG tiên quyết công cụ, ràng buộc state slots, xác minh [TAG-123] trong retrieved_chunk_ids) với các ca ngữ nghĩa ở Tầng 2 (Dawid–Skene EM trên tập sống sót).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_deterministic_assertions và run_assertion_waterfall_benchmark trong Tests 10–12, 19.
Tiêu chí Đáp án & Số đối chứng
Tầng 1 chạy trung bình ~0.16 ms/mẫu ($0), bắt ngay 33/38 lỗi (86.8%) của v2. Với 3 × $0.004 = $0.012/mẫu cho hội đồng 3 giám khảo, định tuyến cả 157 ca RAG sống sót tốn 471 lượt ($1.884), còn định tuyến rủi ro 39 ca Tier-1 tốn 117 lượt ($0.468, -51.25% vs 1-judge $0.960 và -83.75% vs 3-judge $2.880). Dawid–Skene EM khớp thuần trên 157 ca sống sót nâng kappa từ 0.044 -> 0.587 (RAG: 87.3% -> 97.5%, E2E = 98.3%).
Bài tập 5 — Thiết kế Cổng CI/CD Non-Regression và Cẩm nang Sửa lỗi Playbook 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh tiêu chí NaiveAggregateGate với SliceNonRegressionGate (max_slice_regression_pp = 3.0, tier1_floor = 78%, max_risk_ratio = 1.05, mcnemar_alpha = 0.05).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra evaluate_ci_release_gate và build_remediation_playbook trên v2 và v3 (Tests 13–15, 20).
Tiêu chí Đáp án & Số đối chứng
NaiveAggregateGate duyệt sai v2 (+2.9pp), trong khi SliceNonRegressionGate chặn v2 vì 5/5 lát cắt Tier-1 vi phạm và tỷ lệ rủi ro 1.55x > 1.05x. Xếp hạng rủi ro chỉ ra TOOL_SELECTION_ARG_ERROR (27.9%) và INSTRUCTION_SCHEMA_VIOLATION (19.0%) cần sửa trước; áp dụng Playbook đưa v3 lên 96.7% (Risk = 0.075, 0 vi phạm).
Bài tập 6 — Kiểm chứng Toàn trình WB-Ch25 và Xuất JSON Workbench Panels 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xác nhận cấu trúc Pydantic v2 (extra="forbid", strict=True) và cổng quét AST cấm tuyệt đối pickle/joblib trên toàn bộ mã nguồn.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ uv lock --check, ruff check, mypy src, pytest -p no:cacheprovider -v (20/20), và scripts/run_lab_demo.py --seed 42 (Tests 01, 16–18).
Tiêu chí Đáp án & Số đối chứng
Toàn bộ 20/20 bài kiểm thử pytest đạt xanh (0 skipped), ruff và mypy đạt 0 lỗi, uv.lock khớp chuẩn 32 gói, và artifacts/ch25_wb25_results.json xuất đầy đủ 6 KPI, 4 biểu đồ cột và 4 bảng chuẩn hóa trong workbench_panels.