Chương 05 — Kiểm định, Kiểm thử Hộp đen/Hộp trắng (EP/BVA/MC/DC), Đột biến AST, Hypothesis, Xác minh Hoare/Ký hiệu & TDD (pytest/unittest/nox)
Từ Ảo giác 100% Line Coverage (25.64% Mutation Score -> 100.0% trên 39 AST mutants), 3-Value BVA & MC/DC (N+1=4 véc-tơ) đến Hypothesis Shrinking (14 bước), Hoare wp/Loop Invariant (4/4) & Thực thi Ký hiệu tìm lỗi 8.52 ms.
Unit ID:
T2-P1-U05
Track & Part: Track 2 (EDAI) — Part 1: Software, Backend & Container Engineering Foundations (part-01-software-systems-foundations)
Truy xuất Giáo trình Gốc (R27&AIDE 1 R26): Bài 5 Fundamentals of Engineering — Validation & Verification (Paradigms for ensuring software quality,Software testing techniques: black-box (Equivalence Partitioning, Boundary Value Analysis, etc.), white-box, mutation testing,Verification: Hoare logic, symbolic execution,Test-driven Development (TDD),pytest, unittest,test coverage & tox) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md
Bàn Thực hành Song hành (WB-Ch05):labs/ch05-verification-testing-tdd-workbench/(verification_tdd_lab)
Tình huống Mở đầu: Năm Thảm họa Kiểm định Khi "Màu Xanh 100% Coverage" Đánh Lừa Kỹ sư#
Trên bảng điều khiển CI, mọi dòng báo cáo đều xanh rực: 100% line coverage, toàn bộ bài kiểm thử đơn vị chạy xong trong 0.4s, các đối tượng MagicMock xác nhận đúng số lần gọi hàm. Nhưng chỉ vài giờ sau khi phát hành dịch vụ suy luận và tính cước AI lên môi trường sản xuất, hệ thống sụp đổ theo đúng năm kịch bản kinh điển của ngành kỹ nghệ phần mềm:
- Ảo giác
100%Độ bao phủ Dòng (Line Coverage) Đánh Rơi Lỗi Biên1Đơn vị: Bộ kiểm thử khói chỉ chạy các điểm đại diện giữa khoảng (units=50, 250, 2000) và kiểm tra lỏng lẻoassert net_cents > 0. Thực nghiệm trênWB-Ch05cho thấy bộ test đó chạm tới100.0%tổng số dòng thực thi, nhưng khi bộ máy đột biếnASTcấy39đột biến đơn bậc (<thành<=,+thành-, hằng số lệch1), bộ test chỉ diệt được10/39(25.64%Mutation Score)! Một lỗi lệch dấu đơn giảnunits > 100thay vìunits >= 100âm thầm tính sai cước mọi khách hàng đặt đúng100đơn vị (10000cents thay vì9300cents). - Thảm họa Khẳng định Thiếu Ràng buộc Biên (
Ariane 5 Flight 501, 1996 — Thiệt hại370 triệu USD&CrowdStrike Channel File 291, 2024 —8.5MMáy Windows BSOD): Năm 1996, tên lửa Ariane 5 tự hủy sau37giây vì tái sử dụng mô-đun chuyển đổifloat64 -> int16của Ariane 4 mà không giữ kiểm tra tràn số (tiền điều kiện Hoare chỉ đúng với quỹ đạo Ariane 4 nhưng sụp đổ trên Ariane 5). Gần ba thập kỷ sau, ngày19/07/2024, bản cập nhậtChannel File 291của CrowdStrike kích hoạt lỗi đọc ngoài mảng trong nhâncsagent.sysdo tệp định nghĩa yêu cầu21trường đầu vào trong khi mã cảm biến chỉ cung cấp20khe, bỏ lọt bởi bộ kiểm thử thiếu ca biên âm tính và thiếu kiểm chứng bất biến tĩnh lúc biên dịch. - Mã Chết Không Kiểm thử & Cờ Tái Chế (
Knight Capital Group, 2012 — Mất440 triệu USDtrong45Phút): Đoạn mã cũ Power Peg bị tắt tính năng từ năm 2003 và bị xóa sạch unit test, nhưng vẫn nằm nguyên trên máy chủ sản xuất. Khi kỹ sư tái sử dụng cờ bit cũ cho chương trình mới và triển khai sót1/8máy chủ SMARS, cỗ máy lạc hậu kia bắn hơn4 triệulệnh giao dịch lỗi (397 triệucổ phiếu) trong45phút không có bộ ngắt mạch. - Lỗ hổng Đường Hẹp Mù Trước Kiểm thử Ngẫu nhiên (
Random Fuzzing): Một điều kiện kết hợp hẹptier == "enterprise" and promo_bps == 10000kích hoạtZeroDivisionErrorcó xác suất trúng chỉ \(1 / (3 \times 10001) \approx 3.33 \times 10^{-5}\) mỗi lần lấy mẫu ngẫu nhiên. TrongWB-Ch05,2,000mẫu thử ngẫu nhiên đồng nhất đạt đúng0lần trúng, trong khi bộ Thực thi Ký hiệu (Symbolic Execution) giải hệ điều kiện đường đi \(\Pi\) tìm ra ngay4chứng nhân gây sập trong8.52 msvà tỉa sạch4nhánh bất khả thiUNSAT. - Rò rỉ Trạng thái Lô & Kiểm thử Mock Mong manh (
London Over-Mocking): API/v1/batch-scorenối tiếp biến tích lũy giảm giá ngầm giữa các phần tử trong cùng một lô khiến kết quả của đơn hàngBphụ thuộc vào việc nó đứng trước hay sau đơn hàngA. Unit test kiểu London chỉ mock kho dữ liệu và kiểmassert_called_once()hoàn toàn mù tịt trước lỗi trạng thái lô và sai lệch hợp đồngPydantic v2, trong khi kiểm thử biến đổi hoán vị (Metamorphic Permutation) vớiHypothesisvạch trần sai phạm ngay trong50ví dụ đầu tiên và tự động thu gọn phản ví dụ về dạng tối giản.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 05 và bàn thực hành WB-Ch05 (verification_tdd_lab), kỹ sư Dữ liệu & AI có đủ năng lực để:
- Phân định Rạch ròi Hệ hình Đảm bảo Chất lượng: Phân biệt Verification vs Validation (Boehm), phân tích tĩnh vs phân tích động, Testing Pyramid vs Testing Trophy, Contract Testing (
Pydantic v2+ OpenAPI) và Metamorphic Testing cho hệ thống ML/LLM không có oracle chân trị tuyệt đối. - Làm chủ Thiết kế Ca Kiểm thử Hộp đen (
EP,BVA,Decision Table,State Transition,Pairwise) & Hộp trắng (CFG,C0/C1,MC/DC): Vận dụng 3-Value BVA bắt lỗi lệch biên±1, thiết lập bảng chân trị tìm tập tối thiểu \(N + 1\) véc-tơ độc lập chuẩn hàng không FAA DO-178CMC/DC(tránh bẫy đoản mạch short-circuit), và đánh giá giới hạn bùng nổ đường đi \(C_\infty\). - Xây dựng & Vận hành Động cơ Kiểm thử Đột biến
AST(Mutation Testing) & Kiểm thử Thuộc tính (Hypothesis): Tính toán chính xác Điểm Đột biến \(M = K / (T - E)\), xử lý đột biến tương đương (Equivalent Mutants), ứng dụng các bất biến đại số (khứ hồi, lũy đẳng, đơn điệu, hoán vị lô, đối chứng vi sai) kèm cơ chế thu gọn nội tại trên luồng lựa chọn (Conjecture Choice-Stream Shrinking) vàRuleBasedStateMachine. - Chứng minh Đúng đắn Chương trình Bằng Logic Hoare (
wp, \(I\), \(V\)) & Thực thi Ký hiệu (Symbolic Execution): Dẫn xuất tiền điều kiện yếu nhất \(\text{wp}(C, Q)\) bằng phép thế ngược, chứng minh4nghĩa vụ vòng lặp (Khởi tạo, Duy trì, Thoát, Hàm hạng giảm ngặt \(V \ge 0\)), và giải điều kiện đường đi \(\Pi\) (Fourier–Motzkin / SMT Z3) để tỉa nhánhUNSATvà tổng hợp phản ví dụ đường hẹp. - Thực hành Kiến trúc
TDDHiện đại Vớipytest,unittest,Test Doubles&nox/uv: Phối hợp trường phái Chicago (Fakes & trạng thái) và London (Protocols & Spies), phân biệt rành mạch5loại Test Doubles (Dummy, Stub, Spy, Mock, Fake), sử dụng thành thạopytestfixtures (yield),@pytest.mark.parametrize,monkeypatch, tương thíchunittest.TestCase, kiểm thửFastAPIquahttpx.ASGITransport, và đóng gói cổng CI đa phiên bảnnoxfile.py+uv.lockđạt chuẩn16/16 pytest,0lỗiruff&mypy --strict.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P1-U05, R27 + AIDE 1 R26)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R27 & AIDE 1 R26) |
Nâng cấp Chuẩn SOTA 2026 (ch-05) |
Mục trong Chương 05 | Tạo tác & Kiểm thử (verification_tdd_lab) |
|---|---|---|---|
1. Paradigms for ensuring software quality (R27) |
Verification ("system right") vs Validation ("right system"); Tĩnh vs Động; Testing Pyramid vs Testing Trophy; Contract Testing (Pydantic v2) & Metamorphic Testing giải bài toán Test Oracle Problem cho ML/LLM |
Trụ cột 1 (§1.1) + Trụ cột 2 (§2.1) + Mermaid 1 | target_api_and_domain.py (QuoteRequest, /v1/quote, /v1/batch-score), Tests 07, 11 |
2. Black-box testing (EP, BVA, etc.) (R27) |
Equivalence Partitioning (EP), 2-Value vs 3-Value BVA, Bảng Quyết định (Decision Tables), Chuyển đổi Trạng thái (0/1-switch & sneak path), Kiểm thử Tổ hợp Từng cặp (Pairwise \(t\)-wise) |
Trụ cột 1 (§1.2) + Trụ cột 3 (Playbook A) + Widget 1 | testing_engines.py (generate_ep_bva_vectors), bắt lỗi units > 100 tại units=100, Tests 01, 02 |
3. White-box coverage & Mutation testing (R27) |
CFG, phủ dòng (\(C_0\)), nhánh (\(C_1\)), điều kiện, đường đi (\(C_\infty\)), FAA DO-178C MC/DC (\(N+1\) cặp độc lập); Đột biến AST (ROR/AOR/LCR/CRP), \(M = K/(T-E)\), đột biến tương đương, mutmut, Google diff-mutation (2021) & Meta ACH (2025) |
Trụ cột 1 (§1.3, §1.4) + Trụ cột 2 (§2.2) + Trụ cột 3 (Case 4 + Specimen) + Mermaid 2 + Widget 1, 2 | testing_engines.py (solve_mcdc_a_and_b_or_c, run_ast_mutation_benchmark), Tests 03, 04 |
4. Property-Based Testing (Hypothesis) (Syllabus SOTA) |
Bất biến đại số (khứ hồi, lũy đẳng, đơn điệu, hoán vị lô, đối chứng); @given & @st.composite; Internal Choice-Stream Shrinking (MacIver & Donaldson, ECOOP 2020); RuleBasedStateMachine |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.2) + Trụ cột 3 (Playbook B) + Widget 2 | testing_engines.py (shrink_counterexample, quote_request_strategy), @given tests, Tests 05–08 |
5. Verification: Hoare logic & Symbolic execution (R27) |
Bộ ba Hoare \(\{P\}\ C\ \{Q\}\) & \([P]\ C\ [Q]\), tiên đề gán, quy tắc vòng lặp (Bất biến \(I\) & Hàm hạng \(V \ge 0\)), Weakest Precondition \(\text{wp}(C, Q)\); Symbolic Execution \((\sigma, \Pi)\), tỉa nhánh UNSAT, giải ràng buộc Fourier–Motzkin / Z3 & bùng nổ đường đi |
Trụ cột 1 (§1.6, §1.7) + Trụ cột 2 (§2.3) + Trụ cột 3 (Cases 1, 5 + Playbook C) + Mermaid 3 + Widget 3 | formal_verifier.py (compute_wp_assignment_chain, verify_hoare_loop_sum_and_wp, explore_symbolic_paths), Tests 09, 10 |
6. TDD, Mocking, pytest, unittest & tox/nox (R27, AIDE 1 R26) |
Red -> Green -> Refactor; Chicago vs London; 5 Test Doubles (Dummy, Stub, Spy, Mock, Fake); DI qua Protocol; pytest fixtures (yield), parametrize, monkeypatch, markers; unittest.TestCase; FastAPI ASGITransport; noxfile.py & uv.lock |
Trụ cột 1 (§1.8, §1.9) + Trụ cột 4 (§4.1–§4.3) + Mermaid 1 | target_api_and_domain.py (InMemoryQuoteRepo, FixedClock, RecordingAuditSpy), noxfile.py, Tests 01, 11–14 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 05 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 05 & verification_tdd_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(P, Q, I\) | Vị từ (Predicate) | Tiền điều kiện \(P\), hậu điều kiện \(Q\), và bất biến vòng lặp \(I\) trong bộ ba Hoare \(\{P\}\ C\ \{Q\}\) | Không nhầm \(P\) (precondition) với phân hoạch \(P_i\) của EP |
| \(\text{wp}(C, Q)\) | Toán tử vị từ | Tiền điều kiện yếu nhất (Weakest Precondition) của lệnh \(C\) đối với hậu điều kiện \(Q\) | — |
| \(V\) | \(\mathbb{Z}_{\ge 0}\) | Hàm hạng kết thúc vòng lặp (Loop Variant), giảm ngặt qua mỗi bước (\(V_{\text{after}} < V_{\text{before}}\)) | Không nhầm với tập đỉnh \(V\) trong CFG \(G=(V,E)\) |
| \(\sigma, \Pi\) | Ánh xạ & Hội vị từ | Trạng thái ký hiệu \(\sigma: \text{Var} \to \text{Expr}\) và Điều kiện đường đi (Path Condition) \(\Pi\) | \(\Pi\) là hội các điều kiện rẽ nhánh dọc đường thực thi |
| \(N\) | \(\mathbb{N}_+\) | Số điều kiện nguyên tử (atomic conditions) trong một quyết định MC/DC (cần tối thiểu \(N+1\) véc-tơ) |
Phân biệt với \(n\) (cận lặp trong bài toán vòng lặp Hoare) |
| \(T, K, E, M\) | \(\mathbb{N}_{\ge 0}, [0, 1]\) | Tổng đột biến \(T\), số đột biến bị tiêu diệt \(K\), đột biến tương đương \(E\), điểm đột biến \(M = K / (T - E)\) | Loại trừ \(E\) khỏi mẫu số khi đánh giá độ nhạy bộ kiểm thử |
| \(a, b\) | \(\mathbb{Z}\) / \(\mathbb{R}\) | Cận dưới \(a\) và cận trên \(b\) của miền đầu vào trong BVA (2-value vs 3-value: \(\{a-1, a, a+1\}\)) |
— |
Trụ cột 1 — Nguyên lý Gốc: Hệ hình Chất lượng, EP/BVA/MC/DC, Đột biến AST, Hypothesis, Hoare wp, Thực thi Ký hiệu & TDD#
1.1 Đảm bảo Chất lượng: Verification vs. Validation, Kim tự tháp vs. Cúp Kiểm thử & Bài toán Test Oracle#
Barry Boehm (1981) đặt nền móng cho toàn bộ ngành đảm bảo chất lượng phần mềm qua hai câu hỏi bất biến mà không công cụ nào được phép trộn lẫn:
- Verification (Xác minh — "Are we building the system right?"): Đánh giá tính đúng đắn nội tại của phần mềm đối chiếu với đặc tả kỹ thuật, ràng buộc kiểu, tiền/hậu điều kiện và bất biến mã nguồn. Bao gồm cả phân tích tĩnh (static verification:
ruff,mypy --strict, kiểm tra lược đồ lúc biên dịch, chứng minh Hoare, suy diễn ký hiệu) lẫn kiểm thử động (dynamic verification:pytest,unittest, kiểm thử hợp đồng API, kiểm thử đột biến). - Validation (Kiểm định / Xác nhận — "Are we building the right system?"): Đánh giá xem hệ thống đã triển khai có giải quyết đúng nhu cầu nghiệp vụ, trải nghiệm người dùng và ràng buộc vận hành thực tế hay chưa (kiểm thử chấp nhận E2E, kiểm định A/B hay canary, đánh giá độ hiệu chuẩn xác suất và ma trận chi phí kinh doanh cho mô hình ML).
Một dịch vụ đạt 100% Verification vẫn có thể thất bại hoàn toàn về mặt Validation nếu đặc tả ban đầu tính sai công thức chiết khấu thương mại; ngược lại, một hệ thống khớp đúng nghiệp vụ (Validation) ở lưu lượng nhỏ vẫn sụp đổ sản xuất nếu vi phạm tính bất biến đồng thời hoặc lỗi biên bộ nhớ (Verification).
Về phân bổ tầng kiểm thử, hai mô hình kinh điển định hình chi phí phản hồi trong CI:
| Mô hình Phân tầng | Tỷ trọng Các lớp | Thời gian Phản hồi & Chi phí Bảo trì | Bẫy Sập Khi Áp dụng Sai |
|---|---|---|---|
| Testing Pyramid (Mike Cohn, 2009) | Đáy rộng Unit Tests (~70%) \(\to\) Integration / Contract (~20%) \(\to\) đỉnh hẹp E2E (~10%) |
Đơn vị chạy dưới 1 ms/test, cô lập hoàn toàn, độ ổn định cao |
Rơi vào phản mẫu Ice-Cream Cone (chạy E2E nặng nề mất 45 phút) hoặc unit test mock quá đà khiến API thật vỡ hợp đồng |
| Testing Trophy (Kent C. Dodds) | Đế Static Analysis (mypy/ruff) \(\to\) Unit \(\to\) Integration Phình to (FastAPI + Fake/DB cục bộ) \(\to\) đỉnh nhỏ E2E |
Đạt tỷ lệ bắt lỗi thực tế trên thời gian CI tốt nhất cho WebAPI & dịch vụ dữ liệu | Gắn thẳng vào cơ sở dữ liệu staging dùng chung làm test chập chờn (flaky); giải pháp chuẩn là dùng httpx.ASGITransport + In-Memory Fake / Testcontainers |
| Contract & Metamorphic Testing | Lược đồ dây Pydantic v2 / OpenAPI + Quan hệ Biến đổi (Metamorphic Relations) |
Chặn gãy schema giữa producer–consumer và kiểm định ML/LLM không cần ground-truth tĩnh | Thiếu kiểm tra tương thích ngược lược đồ hoặc chọn sai quan hệ bất biến cho mô hình xác suất |
Bài toán Test Oracle Problem trong Hệ thống ML/LLM: Với thuật toán sắp xếp hay định giá tiền tệ, ta luôn có một Test Oracle xác định biết trước đầu ra đúng \(y^* = f(x)\) cho mọi \(x\). Nhưng với mô hình phân loại gian lận, hệ thống gợi ý hoặc dịch vụ RAG/LLM, trên đầu vào mới chưa gắn nhãn, không tồn tại giá trị đúng tuyệt đối để viết assert model.predict(x) == 0.7341. Kiểm thử Biến đổi (Metamorphic Testing, Chen 1998; Xie et al., 2011; Chen et al., ACM CSUR 2018) giải quyết bế tắc này bằng cách kiểm tra Quan hệ Biến đổi (Metamorphic Relation — MR) giữa cặp đầu vào gốc \(x\) và đầu vào biến đổi \(x' = T(x)\):
- Bất biến Hoán vị Lô (Permutation Invariance): Đảo thứ tự danh sách yêu cầu trong
POST /v1/batch-scorekhông được làm thay đổi điểm số của từng phần tử: \(\text{score}([a, b]) = \text{reverse}(\text{score}([b, a]))\). - Bất biến Đơn điệu (Monotonicity): Tăng chất lượng SLA hoặc giảm tỷ lệ rủi ro đầu vào không được làm tăng xác suất bị từ chối của mô hình đơn điệu.
- Kiểm thử Vi sai (Differential Testing): Đối chiếu nhân suy luận lượng tử hóa/tối ưu (
fp16/ batch kernel) với bản tham chiếufloat64chuẩn xác trong sai số \(|\hat{y}_{\text{fast}} - \hat{y}_{\text{ref}}| \le \varepsilon\).
1.2 Kiểm thử Hộp đen (Black-Box Testing): EP, BVA (2-giá trị vs 3-giá trị), Bảng Quyết định & Tổ hợp Pairwise#
Kiểm thử hộp đen suy diễn tập véc-tơ kiểm thử hoàn toàn từ đặc tả đầu vào–đầu ra, độc lập với cấu trúc rẽ nhánh bên trong.
- Phân hoạch Tương đương (
Equivalence Partitioning—EP): Chia miền đầu vào \(D\) thành các lớp tương đương rời nhau \(P_1, P_2, \dots, P_m\) sao cho mọi phần tử trong cùng một phân hoạch kích hoạt cùng một hành vi quy định. Bắt buộc bao phủ cả phân hoạch hợp lệ (ví dụunitsthuộc[1, 99],[100, 999],[1000, 10000]) lẫn phân hoạch không hợp lệ (units <= 0,units >= 10001,promo_bps < 0,tierlạ,NaN). Chỉ chọn1đại diện mỗi phân hoạch giúp tránh vét cạn \(O(|D|)\), nhưng lại mù hoàn toàn trước lỗi ngay trên đường ranh giới. -
Phân tích Giá trị Biên (
Boundary Value Analysis—BVA:2-giá trịvs.3-giá trị): Thực nghiệm kỹ nghệ chỉ ra đa số lỗi lập trình (<nhầm thành<=,>nhầm thành>=, sai lệch chỉ số mảng±1) tụ tập tại mép các phân hoạch \([a, b]\) với bước lượng tử nhỏ nhất \(\varepsilon\) (\(\varepsilon = 1\) cho số nguyên, \(\varepsilon = 0.01\) cho tiền tệ hoặc0.001cho ngưỡng điểm):2-Value BVA: Lấy 2 điểm tại mỗi biên \(\{a - \varepsilon, a\}\) và \(\{b, b + \varepsilon\}\) (tổng4điểm cho đoạn \([a, b]\)). Đủ để bắt lỗi nhầm dấu đóng/mở (< avs<= atại \(a\)), nhưng vẫn có thể bỏ sót lỗi dịch ngưỡng kiểuunits >= a + 1nếu không đối chiếu thêm phía trong!3-Value BVA(Biên Nghiêm ngặt): Lấy trọn3điểm quanh mỗi biên \(\{a - \varepsilon, a, a + \varepsilon\}\) và \(\{b - \varepsilon, b, b + \varepsilon\}\). TrênWB-Ch05, tậpbva_3_value_units = [0, 1, 2, 99, 100, 101, 999, 1000, 1001, 9999, 10000, 10001]bắt gọn lỗi của hàm cũlegacy_buggy_quote_centsviếtelif units > 100thay vìelif units >= 100tại điểm biênunits = 100(9300cents so với10000cents).
-
Bảng Quyết định (Decision Tables) & Kiểm thử Chuyển đổi Trạng thái (State Transition Testing):
- Decision Tables: Ma trận hóa \(k\) điều kiện nghiệp vụ (tối đa \(2^k\) cột, rút gọn bằng ký hiệu không quan tâm
-) sang tập hành động kỳ vọng (ví dụ kết hợptier,promo_bps,sla_score,dry_run). - State Transition Testing: Mô hình hóa máy hữu hạn trạng thái \((S, \Sigma, \delta, s_0)\) — kiểm tra 0-switch (mọi cung chuyển hợp lệ đơn lẻ), 1-switch (mọi cặp chuyển kế tiếp hợp lệ), và đường lén lút (Sneak Paths) (ví dụ gọi hoàn tiền lên hóa đơn đã
CANCELLEDhoặc hết hạnEXPIRED).
- Decision Tables: Ma trận hóa \(k\) điều kiện nghiệp vụ (tối đa \(2^k\) cột, rút gọn bằng ký hiệu không quan tâm
-
Kiểm thử Tổ hợp Từng cặp (Pairwise / \(t\)-wise Combinatorial Testing): Với \(n\) tham số cấu hình độc lập mỗi tham số có \(v\) giá trị (ví dụ
tier\(\times\)region\(\times\)currency\(\times\)payment_mode\(\times\)auth_type\(\times\)compression), thử vét cạn đòi hỏi \(v^n\) ca (với \(v=4, n=6\) là \(4^6 = 4,096\) ca). Nghiên cứu thực nghiệm kinh điển của NIST (Kuhn et al.) chứng minh khoảng 70%–90% lỗi cấu hình thực tế phát sinh từ tương tác của nhiều nhất \(2\) tham số (t = 2). Thuật toánPairwise(IPO/PICT) phủ mọi cặp giá trị của bất kỳ hai tham số nào chỉ với:\[|T_{\text{pairwise}}| = \Theta(v^2 \log n)\]giảm từ
4,096ca xuống khoảng16–24ca kiểm thử mà vẫn giữ nguyên độ nhạy phát hiện tương tác lỗi!
1.3 Kiểm thử Hộp trắng (White-Box Testing): Đồ thị Luồng Điều khiển (CFG) & Tiêu chuẩn FAA DO-178C MC/DC#
Kiểm thử hộp trắng biểu diễn hàm dưới dạng Đồ thị Luồng Điều khiển (Control-Flow Graph — CFG) có hướng \(G = (V, E)\), trong đó \(V\) là tập khối lệnh cơ bản (basic blocks) và \(E\) là tập cạnh chuyển nhánh có điều kiện:
| Tiêu chuẩn Phủ Cấu trúc | Định nghĩa Hình thức trên \(G=(V, E)\) | Độ phức tạp / Số Ca Kiểm thử | Lỗ hổng Mù Không Phát hiện Được |
|---|---|---|---|
| Statement Coverage (\(C_0\)) | Mọi đỉnh thực thi \(v \in V\) được đi qua \(\ge 1\) lần | \(O(\|V\|)\) | Bỏ sót hoàn toàn nhánh else ngầm định (khi chỉ có if err: ...), bỏ qua phép đoản mạch trong biểu thức ghép, và không chứng minh assert có kiểm giá trị đúng hay không |
| Branch / Decision Coverage (\(C_1\)) | Mọi cạnh \(e \in E\) (cả kết quả True và False của mọi quyết định) được đi qua \(\ge 1\) lần |
\(O(\|E\|)\) | Mạnh hơn \(C_0\), nhưng vẫn mù trước lỗi logic nội bộ trong biểu thức tổ hợp nhiều điều kiện (ví dụ nhầm A and (B or C) thành A and B) |
| Condition Coverage | Mọi điều kiện nguyên tử \(c_i\) đạt cả True và False ít nhất 1 lần |
Có thể chỉ 2 véc-tơ |
Không bao hàm \(C_1\)! Ví dụ với A or B, hai ca (T, F) -> T và (F, T) -> T đạt 100% Condition Coverage nhưng quyết định chưa bao giờ đánh giá ra False! |
| MC/DC (Modified Condition/Decision Coverage) | Thỏa mãn Entry/Exit + Decision + Condition + mỗi điều kiện nguyên tử \(c_i\) được chứng minh có tác động độc lập lên kết quả quyết định \(D\) | Tuyến tính: tối thiểu \(N + 1\) véc-tơ cho \(N\) điều kiện (thay vì \(2^N\)) | Đòi hỏi cẩn trọng với cơ chế đánh giá đoản mạch (short-circuit) trong Python/C; không kiểm tra lỗi giá trị số học nếu thiếu assertion |
| Path Coverage (\(C_\infty\)) | Thực thi mọi đường đi khả thi từ điểm vào đến điểm ra của CFG | Cấp số nhân \(2^k\) (hoặc \(\infty\) khi có vòng lặp) | Bùng nổ tổ hợp; thực tế giới hạn qua độ phức tạp Cyclomatic McCabe \(V(G) = \|E\| - \|V\| + 2P\) (Basis Path Testing) |
Toán học Cặp Độc lập MC/DC (FAA DO-178C DAL-A)#
Trong chứng nhận phần mềm hàng không cấp cao nhất DO-178C Level A (FAA), với một biểu thức quyết định \(D(c_1, c_2, \dots, c_N)\) gồm \(N\) điều kiện nguyên tử, bộ kiểm thử đạt chuẩn Unique-Cause MC/DC khi và chỉ khi tồn tại một cặp độc lập (independence pair) \((u, v) \in \{0, 1\}^N \times \{0, 1\}^N\) cho mỗi \(i \in \{1, \dots, N\}\) thỏa mãn đồng thời 3 tiên đề:
- \(u_i \neq v_i\) (chỉ điều kiện mục tiêu \(c_i\) đảo trạng thái
True\(\leftrightarrow\)False), - \(\forall j \neq i,\ u_j = v_j\) (mọi điều kiện khác giữ nguyên không đổi; biến thể Masking MC/DC cho phép \(u_j \neq v_j\) nếu \(c_j\) bị che khuất không tác động vào cổng logic của \(c_i\)), và
- \(D(u) \neq D(v)\) (kết quả toàn bộ quyết định \(D\) bắt buộc đảo chiều theo \(c_i\)).
Dẫn xuất Chính xác trên Cổng SLA evaluate_sla_gate (WB-Ch05): \(D(A, B, C) = A \land (B \lor C)\) với \(N = 3\) (\(2^3 = 8\) hàng chân trị):
- Cặp Độc lập cho \(A\) (
sla_ok): Chọn \(u = (F, F, T) \to F\) và \(v = (T, F, T) \to T\) (\(B=F, C=T\) giữ nguyên). - Cặp Độc lập cho \(B\) (
is_enterprise): Chọn \(u = (T, F, F) \to F\) và \(v = (T, T, F) \to T\) (\(A=T, C=F\) giữ nguyên). - Cặp Độc lập cho \(C\) (
volume_qualified): Chọn \(u = (T, F, F) \to F\) và \(v = (T, F, T) \to T\) (\(A=T, B=F\) giữ nguyên).
Hợp của ba cặp trên thu về chính xác \(N + 1 = 4\) véc-tơ tối thiểu:
Hãy kiểm tra bẫy đoản mạch (short-circuit) của Python: trong \(v = (T, F, T)\) của cặp \(C\), Python đánh giá A=True, kế đến B=False, do đó buộc phải đi vào đánh giá C=True chứ không bỏ qua C! Còn trong \((T, T, F)\), vì B=True, toán tử or của Python sẽ đoản mạch bỏ qua C, nhưng đó chính là cặp kiểm thử cho \(B\) (không dùng để chứng minh \(C\)). Nhờ vậy cả 3 điều kiện đều thực sự tham gia và chứng minh tính tất yếu trong mã nguồn.
1.4 Kiểm thử Đột biến (Mutation Testing): Công thức \(M = K/(T-E)\), Toán tử AST & Định lý Đột biến Tương đương#
Phủ dòng và phủ nhánh chỉ trả lời "CPU có chạy qua dòng này không?", tuyệt đối không trả lời "Nếu lập trình viên gõ nhầm toán tử hoặc sai dấu so sánh, bộ test có thất bại hay không?". Kiểm thử đột biến (DeMillo, Lipton & Sayward, 1978; Jia & Harman, IEEE TSE 2011) đặt trên hai giả thiết nền tảng:
- Giả thiết Lập trình viên Thành thạo (Competent Programmer Hypothesis): Lỗi thực tế trong sản xuất thường gần với chương trình đúng về mặt cú pháp (lệch
1toán tử, sai dấu biên, nhầmand/or). - Hiệu ứng Ghép nối (Coupling Effect): Một bộ test đủ nhạy để diệt hầu hết đột biến đơn bậc (first-order mutants) cũng có khả năng phát hiện hầu hết lỗi phức tạp bậc cao.
Các Toán tử Đột biến AST Chuẩn (ast.NodeTransformer & mutmut)#
Động cơ đột biến biến đổi cây cú pháp trừu tượng AST để sinh \(T\) bản thể đột biến \(M_1, M_2, \dots, M_T\), mỗi bản mang đúng 1 thay đổi cú pháp đơn:
ROR(Relational Operator Replacement):<\(\leftrightarrow\)<=,>\(\leftrightarrow\)>=,==\(\leftrightarrow\)!=.AOR(Arithmetic Operator Replacement):+\(\leftrightarrow\)-,*\(\leftrightarrow\)//,/\(\leftrightarrow\)*.LCR(Logical Connector Replacement):and\(\leftrightarrow\)or.CRP(Constant Replacement): dịch hằng số nguyên \(c \to c \pm 1\), \(c \to 0\), hoặc đảo booleanTrue\(\leftrightarrow\)False.RVR/SDL(Return Value / Statement Deletion): đổi giá trị trả về hoặc xóa một phép gán/câu lệnh.
Công thức Điểm Đột biến & Vấn đề Đột biến Tương đương (Equivalent Mutants)#
trong đó:
- \(K\) (Killed): số đột biến khiến ít nhất một ca kiểm thử thất bại (
AssertionErrorhoặc ngoại lệ ngoài dự kiến). - \(T\) (Total): tổng số đột biến hợp lệ biên dịch được.
- \(E\) (Equivalent Mutants): số đột biến khác cú pháp nhưng đồng nhất về ngữ nghĩa hàm học trên 100% đầu vào hợp lệ (\(\forall x \in D,\ P_{\text{mut}}(x) = P_{\text{orig}}(x)\)). Ví dụ kinh điển: đột biến
while i != n:thànhwhile i < n:khiikhởi tạo ở0và tăng1mỗi bước hướng tớin >= 0. Theo Định lý Rice trong lý thuyết khả tính, bài toán quyết định tổng quát xem một đột biến bất kỳ có tương đương hay không là bất khả quyết định (undecidable)! Do đó trong kỹ nghệ thực tế, các hệ thống SOTA dùng đơn giản hóa tĩnh (loại bỏ các phép biến đổi vô nghĩa trên log/comment) kết hợp đánh giá con người hoặc bộ lọc ARID tại thời điểm code review.
Thực nghiệm đối chứng trong WB-Ch05 (run_ast_mutation_benchmark) phơi bày sự mong manh của chỉ số Line Coverage:
- Bộ smoke test đi qua hết mọi nhánh hợp lệ và ngoại lệ của
compute_pricing_coređạt100.0%độ bao phủ dòng đo bằngtrace.Trace. - Tuy nhiên, trên
39đột biếnAST(ROR:12,AOR:7,LCR:4,CRP:16), bộ smoke test chỉ giết được10/39(25.64%)! Riêng nhóm hằng sốCRPchỉ bị giết1/16(6.2%) và nhóm so sánhRORchỉ bị giết4/12(33.3%). - Khi thay bằng bộ kiểm thử gia cố (
3-Value BVA+MC/DC+ khẳng định số học chính xác), điểm đột biến nhảy vọt từ25.64%lên100.0%(39/39).
1.5 Kiểm thử Dựa trên Thuộc tính (Property-Based Testing — Hypothesis) & Cơ chế Thu gọn Nội tại (Internal Shrinking)#
Thay vì tự gõ vài ví dụ rời rạc \(f(x_i) = y_i\), kiểm thử thuộc tính (QuickCheck, Claessen & Hughes 2000; Hypothesis, MacIver & Hatfield-Dodds JOSS 2019) kiểm chứng mệnh đề phổ quát trên không gian sinh \(\mathcal{G}\):
Năm họ bất biến vàng cho hệ thống phần mềm và dữ liệu/AI gồm:
- Khứ hồi (Round-Trip):
QuoteRequest.model_validate_json(req.model_dump_json()) == req. - Lũy đẳng (Idempotence):
f(f(x)) == f(x)(chạy chuẩn hóa hai lần hoặc phát lạiPUT/Idempotency-Keykhông làm lệch trạng thái). - Đơn điệu (Monotonicity): Tăng số lượng
unitstừ \(u\) lên \(u + 1\) giữ nguyên giá tổng gộpsubtotal(u + 1) > subtotal(u)và không bao giờ tạo giá âm. - Giao hoán / Bất biến Hoán vị (Commutativity / Batch Permutation):
compute_batch_score([a, b]) == list(reversed(compute_batch_score([b, a]))). - Tương đương Oracle Tham chiếu (Differential Equivalence): Thuật toán vector hóa/song song khớp với hàm tham chiếu đơn giản trong sai số \(\varepsilon\).
Tại sao QuickCheck Shrinking Bị Gãy & Cách Hypothesis (Conjecture Engine) Giải Quyết#
Khi tìm thấy một phản ví dụ phức tạp ngẫu nhiên (ví dụ units=4821, tier="enterprise", promo_bps=10000), ta cần thu gọn (shrinking) nó về trường hợp nhỏ nhất còn giữ lỗi (units=1, promo_bps=10000) để kỹ sư đọc hiểu ngay trong 2 giây.
- Hạn chế của QuickCheck External Shrinking: Sinh ra giá trị
axong mới áp hàmshrink(a)bên ngoài. Nếu dữ liệu đầu vào có ràng buộc ghép phức tạp (như@st.compositetạo hai trường phụ thuộc nhaudiscount <= price), hàm shrink ngoài dễ cắt gọt thành đối tượng vi phạm điều kiện tiên quyết, làm nổ test giả hoặc mất sạch cấu trúc khi ghép qua.map()/.flatmap(). - Đột phá Internal Choice-Stream Shrinking (MacIver & Donaldson, ECOOP 2020): Động cơ Conjecture của
Hypothesistách biệt không gian tìm kiếm: mọi giá trị phức hợp (JSON, Pydantic, đồ thị, chuỗi lệnh API) đều được giải mã (parse) từ một dãy lựa chọn nguyên thủy phẳng (byte/choice stream). Khi bài test thất bại, Hypothesis thu gọn trực tiếp trên dãy byte lựa chọn bằng thuật toán delta-debugging, xóa đoạn, nhị phân về0, và hoán vị khối nhỏ, rồi giải mã lại qua chính generator@st.composite! Nhờ đó 100% bất biến cấu trúc của dữ liệu đầu vào được bảo toàn tuyệt đối trong suốt quá trình thu gọn, kết hợp lưu vết phản ví dụ vào.hypothesis/examplesvà chạy tất định hoàn toàn khi bật@settings(derandomize=True). Ngoài ra,hypothesis.stateful.RuleBasedStateMachinecho phép mô hình hóa máy trạng thái API (@rule/@invariant) để thu gọn chuỗi nhiều yêu cầu HTTP liên tiếp gây rò rỉ hoặc kẹt trạng thái.
1.6 Xác minh Hình thức I: Logic Hoare (Hoare Triples), Tiền điều kiện Yếu nhất (wp) & Bất biến Vòng lặp (\(I, V\))#
C. A. R. Hoare (1969) biến chứng minh chương trình thành hệ suy diễn hình thức xoay quanh Bộ ba Hoare (Hoare Triple):
- Đúng đắn Bộ phận (Partial Correctness \(\models \{P\}\ C\ \{Q\}\)): Nếu trạng thái bộ nhớ trước khi chạy lệnh \(C\) thỏa vị từ tiền điều kiện \(P\) và \(C\) dừng lại, thì trạng thái sau khi chạy thỏa hậu điều kiện \(Q\).
- Đúng đắn Toàn phần (Total Correctness \(\models [P]\ C\ [Q]\)): Đúng đắn bộ phận cộng thêm chứng minh \(C\) chắc chắn kết thúc (không treo vòng lặp vô hạn).
Sáu Quy tắc Suy diễn Hoare & Phép tính Tiền điều kiện Yếu nhất \(\text{wp}(C, Q)\) (Dijkstra, 1975)#
- Tiên đề Bỏ qua (
Skip): \(\{P\}\ \texttt{skip}\ \{P\}\), tức \(\text{wp}(\texttt{skip}, Q) = Q\). -
Tiên đề Gán (
Assignment Axiom— Phép thế Ngược):\[\{Q[E / x]\}\ x := E\ \{Q\} \qquad \Longleftrightarrow \qquad \text{wp}(x := E, Q) = Q[E / x]\]trong đó \(Q[E/x]\) là thay mọi xuất hiện tự do của biến \(x\) trong \(Q\) bằng biểu thức \(E\).
Ví dụ Chuỗi Gán (
WB-Ch05): Tính \(\text{wp}(x := x + 1;\ y := x \times 2,\ y \le 20)\) theo chiều ngược từ cuối lên:- Sau \(y := x \times 2\): thế \(y \mapsto x \times 2\) được \(x \times 2 \le 20\).
-
Sau \(x := x + 1\): thế \(x \mapsto x + 1\) được \((x + 1) \times 2 \le 20 \iff x \le 9\)!
Khi đó bộ ba \(\{P\}\ C\ \{Q\}\) đúng khi và chỉ khi Điều kiện Xác minh (
Verification Condition— VC) \(P \implies \text{wp}(C, Q)\) là hằng đúng.
-
Quy tắc Ghép Tuần tự (
Sequential Composition):\[\frac{\{P\}\ C_1\ \{R\} \quad \{R\}\ C_2\ \{Q\}}{\{P\}\ C_1;\ C_2\ \{Q\}}, \qquad \text{wp}(C_1; C_2, Q) = \text{wp}(C_1, \text{wp}(C_2, Q))\] -
Quy tắc Rẽ nhánh Có điều kiện (
Conditional):\[\frac{\{P \land B\}\ C_1\ \{Q\} \quad \{P \land \neg B\}\ C_2\ \{Q\}}{\{P\}\ \texttt{if } B \texttt{ then } C_1 \texttt{ else } C_2\ \{Q\}}\]\[\text{wp}(\texttt{if } B \texttt{ then } C_1 \texttt{ else } C_2, Q) = (B \implies \text{wp}(C_1, Q)) \land (\neg B \implies \text{wp}(C_2, Q))\] -
Quy tắc Hệ quả (
Rule of Consequence): Cho phép làm mạnh tiền điều kiện (\(P' \implies P\)) và làm yếu hậu điều kiện (\(Q \implies Q'\)). -
Quy tắc Vòng lặp
while(Bất biến \(I\) & Hàm hạng Kết thúc \(V \ge 0\)):\[\frac{\{I \land B\}\ C\ \{I\}}{\{I\}\ \texttt{while } B \texttt{ do } C\ \{I \land \neg B\}}\]Để chứng minh tính đúng đắn toàn phần cho một vòng lặp
while B do C, kỹ sư phải chứng minh đủ4nghĩa vụ (proof obligations):- (1) Khởi tạo (Initialization): \(P \implies I\) (bất biến \(I\) đúng ngay trước lần lặp đầu tiên).
- (2) Duy trì (Maintenance / Inductive Step): \(\{I \land B\}\ C\ \{I\}\) (nếu \(I\) đúng và điều kiện lặp \(B\) còn đúng thì thân vòng lặp \(C\) giữ nguyên \(I\)).
- (3) Thoát (Exit): \((I \land \neg B) \implies Q\) (khi vòng lặp dừng do \(\neg B\), kết hợp \(I\) suy ra được hậu điều kiện \(Q\)).
- (4) Kết thúc (Termination Variant \(V \in \mathbb{Z}_{\ge 0}\)): Tồn tại hàm hạng \(V\) sao cho \((I \land B) \implies (V > 0)\) và mỗi bước lặp làm \(V\) giảm ngặt (\(V_{\text{after}} < V_{\text{before}}\)). Vì số nguyên không âm không thể giảm vô hạn lần, vòng lặp bắt buộc phải dừng!
Chứng minh Trực tiếp Trên Hạt nhân Cộng dồn (WB-Ch05 verify_hoare_loop_sum_and_wp):
Xét chương trình {P: n >= 0} acc := 0; i := 0; while (i < n) do (acc := acc + i; i := i + 1) {Q: acc == n*(n-1)//2} với \(I \equiv (0 \le i \le n) \land (\text{acc} = \frac{i(i-1)}{2})\) và \(V = n - i\):
- Khởi tạo: Tại \(i=0, \text{acc}=0\) với \(n \ge 0\): \(0 \le 0 \le n\) và \(0 = \frac{0(-1)}{2}\) \(\implies\) Đúng!
- Duy trì: Giả sử \(I \land (i < n)\). Sau thân vòng lặp \(i' = i + 1, \text{acc}' = \text{acc} + i\): vì \(i < n\) nên \(0 \le i + 1 \le n\), và \(\text{acc}' = \frac{i(i-1)}{2} + i = \frac{(i+1)i}{2}\) \(\implies\) \(I\) giữ nguyên!
- Thoát: Khi \(I \land \neg(i < n)\), ta có \(0 \le i \le n \land i \ge n \implies i = n\), suy ra \(\text{acc} = \frac{n(n-1)}{2} = Q\)!
- Hàm hạng: Với \(i < n\), \(V_{\text{before}} = n - i > 0\) và \(V_{\text{after}} = n - (i + 1) = V_{\text{before}} - 1 < V_{\text{before}}\).
- Ngược lại, nếu viết nhầm điều kiện lặp thành
i <= n(off-by-one), khi \(i = n\), bước lặp chạy thêm 1 vòng đẩy \(i' = n + 1 > n\) và \(V_{\text{after}} = -1 < 0\), lập tức bị bác bỏ tại Nghĩa vụ Duy trì và Hàm hạng (counterexample: {obligation: 2, n: 0, i: 0, next_i: 1})!
1.7 Xác minh Hình thức II: Thực thi Ký hiệu (Symbolic Execution) & Giới hạn Bùng nổ Đường đi#
Logic Hoare mạnh mẽ nhưng đòi hỏi viết tay bất biến \(I\) cho mỗi vòng lặp. Thực thi Ký hiệu (Symbolic Execution, James C. King, CACM 1976) tự động hóa việc tìm lỗi sâu bằng cách thay giá trị cụ thể bằng biểu tượng đại số (\(\text{units} = \alpha_0, \text{tier\_code} = \alpha_1, \text{promo\_bps} = \alpha_2\)):
- Trạng thái Ký hiệu \((\sigma, \Pi)\):
- \(\sigma: \text{Var} \to \text{SymbolicExpr}(\alpha_i)\) lưu biểu thức ký hiệu hiện thời của từng biến (ví dụ
denom = 10000 - alpha_2). - Điều kiện Đường đi (Path Condition \(\Pi\)): Hội các ràng buộc đại số tích lũy dọc theo mọi nhánh
if/elseđã đi qua, khởi tạo từ tiền miền hợp lệ \(\Pi_0\).
- \(\sigma: \text{Var} \to \text{SymbolicExpr}(\alpha_i)\) lưu biểu thức ký hiệu hiện thời của từng biến (ví dụ
- Phân nhánh & Tỉa Nhánh Vô nghiệm (
UNSAT Pruning): Khi gặpif B:, trình thực thi tách thành hai thế giới song song và gọi bộ giải ràng buộc (Z3 SMT hoặc Fourier–Motzkin tuyến tính):- Nếu \(\Pi \land \sigma(B)\) khả thỏa (
SAT), khám phá tiếp nhánhTruevới \(\Pi_{\text{true}} = \Pi \land \sigma(B)\). - Nếu \(\Pi \land \neg \sigma(B)\) vô nghiệm (
UNSAT), nhánh đó là đường đi bất khả thi (infeasible path) và bị cắt tỉa ngay lập tức (ví dụunits > 500đi tiếp vàounits < 200tạo hệ \(501 \le u \le 199 \implies 302 \le 0\), bị tỉa sạch không bao giờ báo lỗi giả!).
- Nếu \(\Pi \land \sigma(B)\) khả thỏa (
- Tổng hợp Phản ví dụ Tự động: Trước mỗi phép chia
x // denomhoặcassert post, chỉ cần truy vấn bộ giải:\[\Pi \land (\sigma(\text{denom}) = 0) \qquad \text{hoặc} \qquad \Pi \land \neg Q\]NếuSAT, bộ giải trả về ngay đầu vào cụ thể chính xác 100% (như{units: 1000, tier_code: 2, promo_bps: 10000}), dù xác suất gặp ngẫu nhiên chỉ là \(3.33 \times 10^{-5}\)! - Ba Rào cản Cố hữu: (1) Bùng nổ đường đi (\(2^k\) nhánh qua \(k\) câu lệnh
ifhoặc vòng lặp chưa biết cận), (2) Ràng buộc phi tuyến / hàm băm mật mã làm bộ giải SMT quá hạn, và (3) Lời gọi hệ thống / I/O ngoài — dẫn tới phương pháp lai Thực thi Hỗn hợp Concolic (Concrete + Symbolic) nhưDART,KLEE, hayCrossHairtrên Python.
1.8 TDD, Hai Trường phái Chicago vs. London & Phân loại 5 Loại Test Doubles#
Quy trình TDD (Test-Driven Development, Kent Beck) xoay quanh vòng lặp vi mô 3 nhịp Red -> Green -> Refactor:
- Red: Viết một ca kiểm thử tối thiểu mô tả đúng một hành vi mới hoặc lỗi vừa phát hiện; chạy để chắc chắn test thất bại đúng lý do (không phải lỗi cú pháp).
- Green: Viết đoạn mã đơn giản nhất vượt qua ca kiểm thử đó (không tối ưu hóa sớm).
- Refactor: Tinh gọn cấu trúc, xóa trùng lặp, rút hàm trợ giúp, chạy lại toàn bộ bộ test để bảo đảm 0 hồi quy (zero regression).
Trong thực hành công nghiệp, hai trường phái TDD dẫn tới kiến trúc bộ kiểm thử rất khác biệt:
- Trường phái Chicago (Classicist / State-Based): Kiểm thử qua giao diện công khai bằng các đối tượng thật hoặc Fake nhẹ trong bộ nhớ, khẳng định trên trạng thái cuối / giá trị trả về. Chỉ thay thế ở ranh giới hệ thống ngoài (mạng, đồng hồ, cổng thanh toán). Rất bền vững khi tái cấu trúc mã nội bộ.
- Trường phái London (Mockist / Interaction-Based): Cô lập từng lớp bằng
Mock, khẳng định trình tự và tham số lời gọi giữa các cộng tác viên. Cho phép phát triển theo hướng top-down nhanh, nhưng dễ sinh ra bộ test giòn gãy (brittle) bị vỡ mỗi khi đổi tên phương thức nội bộ dù hành vi hệ thống vẫn đúng, đồng thời che khuất sai lệch hợp đồng thật ở ranh giới tích hợp.
Để giao tiếp không mơ hồ, Gerard Meszaros (2007) chuẩn hóa thuật ngữ "Test Double" thành đúng 5 vai trò riêng biệt (đừng bao giờ gọi chung tất cả là "Mock"):
| Loại Test Double | Mục đích & Hành vi Chính xác | Ví dụ trong WB-Ch05 (target_api_and_domain.py) |
|---|---|---|
| 1. Dummy | Truyền vào cho đủ chữ ký tham số/interface nhưng không bao giờ đọc tới hoặc không gây tác dụng | NullAuditDummy (thỏa AuditSinkPort khi test luồng tính giá không quan tâm log kiểm toán) |
| 2. Stub | Trả về giá trị đóng hộp cố định (canned answer) để kiểm soát dữ liệu gián tiếp | FixedClock("2026-11-22T00:00:00Z") (khóa cứng thời gian để loại bỏ flaky timestamp) |
| 3. Spy | Chuyển tiếp/ghi lại thông tin các cuộc gọi (số lần, đối số) để kiểm tra sau khi thực thi | RecordingAuditSpy (lưu danh sách (event, request_id, net_cents) vào self.events) |
| 4. Mock | Đối tượng lập trình sẵn kỳ vọng tương tác (expectation) và tự fail test nếu gọi sai giao thức | unittest.mock.Mock(spec=...) kiểm tra assert_called_once_with(...) |
| 5. Fake | Bản cài đặt nhẹ có ngữ nghĩa hoạt động thật nhưng chạy nhanh hoàn toàn trong RAM | InMemoryQuoteRepo (dict lưu/truy vấn quote thật) hoặc httpx.ASGITransport(app=app) |
1.9 pytest, Tương thích unittest, Fixture DAG, parametrize, monkeypatch & Ma trận nox/tox/uv#
Hệ sinh thái kiểm thử Python SOTA 2026 kết hợp tính chuẩn mực của thư viện chuẩn unittest với sức mạnh mở rộng của pytest:
unittest.TestCaseInteroperability: Các bộ mã kế thừaunittest.TestCase(setUp/tearDown,assertEqual,assertRaises) đượcpytesttự động khám phá và thực thi chung trong cùng một lần chạy mà không cần chuyển đổi tức thì.- Fixture Dependency Injection & 4 Tầm vực (
Scope): Khai báo@pytest.fixture(scope="function" | "class" | "module" | "session")dựng đồ thị phụ thuộc không chu trình (DAG) cho các test yêu cầu đúng tên tham số. Dùng từ khóayieldbiến phần sauyieldthành dọn dẹp tất định (deterministic teardown) luôn chạy kể cả khi ca test thất bại. - Ma trận Tham số
@pytest.mark.parametrize: Tạo tự động nhiều ca kiểm thử độc lập từ một thân hàm (mỗi bộ tham số là một báo cáo pass/fail riêng biệt trong output củapytest). - Cơ chế Vá Tạm thời
monkeypatch& Marker Chọn lọc-m:monkeypatch.setattr(...),setenv(...),delenv(...)vá an toàn cấu hình/biến môi trường/phụ thuộc trong phạm vi đúng một test và tự động hoàn nguyên sau khi test kết thúc; kết hợp@pytest.mark.slow/@pytest.mark.contractlọc nhanh tập test khi phát triển (pytest -m "not slow"). - Ma trận Đa môi trường
nox/tox&uv.lock: Thay cho tệp INI cứng nhắc củatox,noxfile.pydùng Python thuần định nghĩa các phiên tách biệt (lintchạyruff,typecheckchạymypy --strict,testschạypytesttrên cả Python3.12và3.13,coverageép trần--cov-branch --cov-fail-under=90), khóa tái lập toàn bộ cây phụ thuộc quauv.lock.
Trụ cột 2 — Kiến trúc Hệ thống Kiểm định & Vận hành Chất lượng Trong Sản xuất#
2.1 Kiến trúc Phân tầng Quality Gates Theo Mô hình Cúp Kiểm thử (Testing Trophy)#
Trong quy trình CI/CD của nền tảng Dữ liệu & AI, kiểm định phần mềm không phải là một bước chạy đơn lẻ cuối giờ, mà là một đường ống cổng chất lượng (staged quality gates) sắp xếp theo chi phí phản hồi tăng dần:
- Ngân sách Thời gian & Độ tin cậy (
CI Budgets):- Cổng 1 + 2 + 3 (Fast Inner Loop — chạy ở mỗi commit cục bộ / pre-push): Bắt buộc hoàn tất trong
< 10 giây,0phụ thuộc mạng ngoài nhờ tiêmProtocol+InMemoryQuoteRepo(Fake) +httpx.ASGITransport, đạt độ nhạy0%flaky. - Cổng 4 (Deep Verification Gate — chạy trên mọi PR đụng tới lõi tài chính/suy luận/bảo mật): Cố định hạt giống
@settings(derandomize=True, max_examples=50..200)để mọi phản ví dụ Hypothesis tái lập 100% trên máy dev, chạy đột biến AST theo vùng diff (chiến lược Google diff-based mutation) với ngưỡngMutation Score >= 90%, và kiểm tra đường hẹp bằng trình khám phá ký hiệu tuyến tính (< 20 ms). - Cổng 5 (Multi-Env Release Matrix):
noxdựng môi trường sạch đối chiếu trênuv.lockqua các phiên bản Python mục tiêu (3.12,3.13) trước khi đóng gói container (sẽ triển khai ở chương Containerization kế tiếp).
- Cổng 1 + 2 + 3 (Fast Inner Loop — chạy ở mỗi commit cục bộ / pre-push): Bắt buộc hoàn tất trong
- Góc nhìn Principal (
SOTA 2025–2026) — CI Khép kín (Hermetic CI/CD), Hạt giống Tất định & Chuỗi cung ứngSLSA/uv.lock:- Đánh đổi Thiết kế: Chạy
uv sync --frozen(hoặc--locked) thay vìpip installđộng bảo đảm 100% bất biến cây phụ thuộc theo hàm băm SHA-256 tronguv.lock, nhưng buộc đội ngũ cập nhật lockfile có chủ đích khi nâng cấp thư viện. Tương tự, tách kiểm thử thuộc tínhHypothesisvớiderandomize=True(hoặc ghim--hypothesis-seed) kết hợp CSDL cô lập tạm thời (sqlite:///:memory:/Testcontainerscổng động) loại bỏ flaky test do dùng chung trạng thái staging. - Chế độ Lỗi Sản xuất: (1) CI chạy
pip installkhông khóa lockfile kéo nhầm bản cập nhật vá lỗi phá vỡ ABI hoặc mã độc chuỗi cung ứng giữa đêm; (2) thiếu SLSA Provenance + băm tạo tác làm không thể truy vết nhị phân chạy trên cụm K8s xuất phát từ commit/workflow nào; (3) test thuộc tính ngẫu nhiên không ghi seed làm lỗi chỉ xuất hiện thoáng qua trên CI mà không tái hiện được trên máy kỹ sư.
- Đánh đổi Thiết kế: Chạy
Principal Industrial Tip #15a — Tự động hóa Kiểm thử Hợp đồng API Bằng Schemathesis & Pact Trong CI Khép kín (2025–2026):
- Đánh đổi Giữa
Schemathesis(Property-Based API Fuzzing) và Test Ví dụ Thủ công:Schemathesisdùng trực tiếp động cơHypothesisđể biên dịch lược đồOpenAPI 3.1/JSON Schemathành hàng nghìn ca kiểm thử âm tính, biên cực trị (NaN, chuỗi rỗng, kiểu sai) và chuỗi gọi có trạng thái theoOpenAPI Links(POST -> GET -> DELETE), bắt gọn lỗi500 Internal Server Errorhoặc phản hồi lệchRFC 9457mà bộ test viết tay bỏ sót. Đánh đổi là chi phí chạy cao hơn unit test thông thường và rủi ro làm bẩn dữ liệu nếu chĩa vào môi trường dùng chung — luôn chạy trong CI khép kín quahttpx.ASGITransport+ Fake/DB tạm và cố định seed tái lập. - Đánh đổi Giữa
Pact(Consumer-Driven Contract Testing) và E2E Staging: Khi một APIFastAPIphục vụ nhiều nhóm khách (consumers), dựng toàn bộ hệ sinh thái staging để chạy E2E vừa chậm vừa chập chờn.Pactđảo chiều kiểm chứng: mỗi consumer xuất tệp hợp đồng tối thiểu (pact file) lênPact Broker; phía provider chạy xác minh hợp đồng ngay trong unit/integration CI và kiểm tra cổngcan-i-deploytrước khi phát hành. Tuy nhiên,Pactchỉ dùng để khóa hình dạng và ngữ nghĩa hợp đồng tối thiểu — tuyệt đối không nhét ràng buộc logic nội bộ vào pact file gây khóa cứng khả năng tái cấu trúc provider. - Chế độ Lỗi Sản xuất (
Failure Modes): (1) Viết tay tệpopenapi.yamltách rời mãPydantic v2làmSchemathesiskiểm định sai hợp đồng thật — luôn sinh OpenAPI trực tiếp từapp.openapi(); (2) Bỏ qua bước xác minhPacttrong pipeline PR khiến thay đổi tưởng vô hại (đổi tên trường, thu hẹp enum) đánh sập đồng loạt consumer khi lên production.
2.2 Đường ống Đột biến AST & Thu gọn Phản ví dụ Hypothesis Vạch trần Ảo giác 100% Coverage#
Sơ đồ dưới đây minh họa cách hai đường nhánh cùng đi qua 100% câu lệnh của compute_pricing_core, nhưng chỉ đường nhánh gia cố mới diệt được đột biến AST và thu gọn phản ví dụ về dạng chuẩn tối giản:
Lưu ý điểm tương tác giữa đột biến tương đương (\(E\)) và ngưỡng CI: trong một codebase lớn, đặt mù quáng ngưỡng 100% toàn kho sẽ làm đội ngũ kiệt sức vì phải viết chú thích # pragma: no mutate cho hàng loạt đột biến tương đương trên log hoặc câu lệnh lặp tương đương. Chuẩn sản xuất 2026 (học từ Google IEEE TSE 2021 và Meta ACH 2025) là lọc bỏ dòng không sinh lỗi nghiệp vụ (ARID), đo đột biến tập trung vào hạt nhân logic cốt lõi (domain kernels) với ngưỡng >= 85%–90%, và dùng chính các đột biến sống sót để dẫn đường viết thêm khẳng định (assertion) hoặc sinh ca test định hướng.
2.3 Kiến trúc Đường ống Xác minh Hình thức (Hoare wp + Symbolic Execution) Đối chứng Thử Ngẫu nhiên#
Khi logic chứa các điều kiện lồng nhau nhiều biến hoặc vòng lặp tích lũy tài chính/lượng tử hóa, kết hợp chứng minh Hoare ở cấp hạt nhân vòng lặp với Thực thi Ký hiệu trên cây rẽ nhánh loại bỏ hoàn toàn điểm mù của lấy mẫu ngẫu nhiên:
- Chống Bùng nổ Đường đi & Độ phức tạp trong Thực tế: Trong dịch vụ sản xuất, không chạy Symbolic Execution toàn bộ khung FastAPI hay thư viện ORM (sẽ nổ đường đi ngay lập tức ở tầng mạng/parsing). Hãy tách hạt nhân thuần (Functional Core, Imperative Shell) — giữ mọi phép tính giá, hạn mức, phân bổ, chuyển trạng thái nằm trong các hàm thuần không I/O, chỉ vài chục đến vài trăm dòng, để
Symbolic Executionduyệt trọn vẹn dưới10 msvàAST Mutationhoàn tất dưới1 giây.
Trụ cột 3 — Bối cảnh Công nghiệp, 5 Thất bại Thực tế & Mẫu Mã Chuẩn Thực thi (Python 3.12+)#
3.1 Năm Thảm họa Kiểm định Công nghiệp & Cách Hóa giải#
Case 1 — Ariane 5 Flight 501 (1996, 370 triệu USD): Bỏ Xác minh Tiền điều kiện Khi Tái sử dụng Mô-đun#
- Cơ chế Sự cố: Mô-đun Hệ thống Tham chiếu Quán tính (
SRI) được bê nguyên từ Ariane 4 sang Ariane 5, thực hiện ép biến vận tốc ngangfloat64sangint16([-32,768, 32,767]). Khi thiết kế cho Ariane 4, đội kỹ sư chứng minh biến này không bao giờ vượt ngưỡng32,767nên chủ động gỡ bỏ khối bắt lỗi tràn số để tiết kiệm CPU. Dưới gia tốc phóng dốc đứng của Ariane 5, biến vượt ngưỡng gây lỗi phần cứng, đánh sập đồng thời cả máy tính chính lẫn máy tính dự phòng nóng chạy cùng mã lỗi đó sau37giây. - Bài học Định lượng: Một bộ ba Hoare \(\{P_{\text{Ariane4}}\}\ C\ \{Q\}\) mất hiệu lực lập tức khi miền đầu vào mở rộng sang \(P_{\text{Ariane5}}\). Mọi mô-đun tái sử dụng bắt buộc khóa tiền điều kiện bằng hợp đồng biên tường minh (
Pydantic v2, kiểm tra miền biến +BVAtrên dải dữ liệu mới) — dự phòng phần cứng vô nghĩa trước lỗi phần mềm chung nguồn (common-mode bug).
Case 2 — Knight Capital Group (08/2012, Mất 440 triệu USD trong 45 Phút): Mã Chết Mất Test & Cờ Tái Chế#
- Cơ chế Sự cố: Chức năng giao dịch Power Peg ngừng sử dụng từ 2003, bị xóa sạch unit test nhưng vẫn giữ nguyên mã nguồn trên máy chủ suốt gần 8 năm. Năm 2012, kỹ sư tái sử dụng bit cờ cấu hình của Power Peg cho chương trình NYSE mới (
RLP). Một kịch bản triển khai âm thầm bỏ qua1trong8máy chủ SMARS; khi lệnh gắn cờ mới chảy vào máy chủ chưa cập nhật kia, nó kích hoạt đoạn mã Power Peg què quặt thiếu biến đếm hoàn tất lệnh mẹ, xả liên tục397 triệucổ phiếu lỗi gây lỗ440 triệu USD. - Phòng thủ Bắt buộc: Xóa vĩnh viễn mã chết thay vì tắt bằng cờ không có test; không bao giờ tái sử dụng định danh cờ đã nghỉ hưu; kiểm chứng tự động phiên bản phát hành trên
100%nút trước khi mở lưu lượng; gắn bộ ngắt mạch bất biến (invariant circuit breaker).
Case 3 — CrowdStrike Channel File 291 (07/2024, 8.5 triệu Máy Windows BSOD): Sai lệch Biên Đầu vào & Thiếu Fuzzing/Canary#
- Cơ chế Sự cố (Theo RCA Chính thức CrowdStrike): Bản định nghĩa IPC Template Type khai báo kỳ vọng
21trường đầu vào, trong khi bộ thông dịch nội dung nhân Windows (csagent.sys) chỉ cung cấp20khe dữ liệu. Bộ kiểm thử phát hành không có ca test nào đụng tới khe thứ21, trình kiểm định tệp nội dung không kiểm tra bất biến biên \(|\text{template\_fields}| \le |\text{sensor\_slots}|\), trình thông dịch thiếu kiểm tra giới hạn mảng lúc chạy, và cập nhật Rapid Response Content bỏ qua triển khai từng bước (canary). - Phòng thủ Bắt buộc: Kiểm tra bất biến lược đồ ngay lúc biên dịch (static validator), phòng thủ biên mảng lúc thực thi, đẩy mạnh kiểm thử mờ / thuộc tính (
Hypothesis/ fuzzing) sinh các bản mẫu chạm biên và vượt biên, kèm phát hành canary theo từng đợt nhỏ.
Case 4 — Ảo giác 100% Line Coverage & Bẫy Mock Quá đà (London Anti-Pattern)#
- Cơ chế Thực tế: Đội ngũ cài
--cov-fail-under=100trong CI nhưng lại viết test đơn giản kiểuassert resp.status_code == 200 and resp.json()["net_cents"] > 0, hoặc dùngMagicMockthay thế toàn bộ tầng định giá và chỉ kiểmmock_repo.save.assert_called_once(). Khi chuyển đổi giữa các phiên bản hoặc sửa biên>=thành>, toàn bộ test vẫn xanh nhưng hóa đơn sản xuất tính sai hàng loạt. - Bằng chứng Trong
WB-Ch05: Bộ smoke đạt100.0%dòng thực thi vẫn để sống tới29/39đột biến (25.64%kill rate), đặc biệt mù93.8%với nhóm hằng sốCRP(1/16bị diệt). Chỉ khi kết hợp 3-Value BVA +MC/DC+ In-Memory Fake + Mutation Gate>= 90%, điểm đột biến mới đạt100.0%(39/39).
Case 5 — Mù Điểm Lỗi Đường Hẹp Trước Random Fuzz & Lỗi Trạng thái Lô ML/Pricing#
- Cơ chế Thực tế: Chạy thử ngẫu nhiên
2,000mẫu trên không gian[1..10000] x {0,1,2} x [0..10000]tìm kiếm lỗi chia cho0ở điều kiệntier_code == 2 and promo_bps == 10000chỉ đạt xác suất trúng \((1 - (1 - 3.33\times 10^{-5})^{2000}) \approx 6.4\%\), thực tế trongWB-Ch05(seed=42) đạt0/2000lần trúng. Đồng thời, lỗi giữ biến giảm giá tích lũy chéo giữa các yêu cầu trong/v1/batch-scorekhông bao giờ lộ ra nếu test chỉ gửi các lô gồm 1 phần tử hoặc không đảo vị trí lô. - Phòng thủ Bắt buộc: Tách lõi tính toán thuần để chạy Thực thi Ký hiệu (tìm ra lỗi chia
0trong8.52 msvới độ chắc chắn100%) song song với Metamorphic Permutation Invariance trongHypothesis.
3.2 Mã Nguồn Chuẩn Thực thi (Pydantic v2 + AST Mutator + MC/DC + Hypothesis + Hoare wp + ASGITransport)#
Đoạn kịch bản độc lập dưới đây chạy trực tiếp 100% trên .venv Python 3.12+ (đã xác minh thoát mã 0), gói gọn đồng thời hợp đồng FastAPI + Protocol Fake, bộ sinh BVA, giải MC/DC, đột biến AST, Hypothesis (derandomize=True), và kiểm tra Hoare wp:
from __future__ import annotations
import ast
import asyncio
import copy
import itertools
from typing import Protocol
import httpx
from fastapi import FastAPI
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import BaseModel, ConfigDict, Field
PRICING_KERNEL_SRC = """
def compute_net_cents(units: int, tier: str, promo_bps: int) -> int:
base = 80 if tier == "enterprise" else (100 if tier == "growth" else 120)
vol_bps = 1500 if units >= 1000 else (700 if units >= 100 else 0)
eff_disc = min(9000, vol_bps + promo_bps)
sub = units * base
return sub - (sub * eff_disc) // 10000
""".strip()
_kernel_ns: dict[str, object] = {}
exec(compile(PRICING_KERNEL_SRC, "<pricing_kernel>", "exec"), _kernel_ns)
compute_net_cents = _kernel_ns["compute_net_cents"]
class QuoteInput(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
units: int = Field(ge=1, le=10000)
tier: str
promo_bps: int = Field(ge=0, le=10000)
class QuoteStorePort(Protocol):
def put(self, key: str, net_cents: int) -> None: ...
class InMemoryFakeStore:
def __init__(self) -> None:
self.rows: dict[str, int] = {}
def put(self, key: str, net_cents: int) -> None:
self.rows[key] = net_cents
def verify_mcdc_a_and_b_or_c() -> list[tuple[bool, bool, bool]]:
expr = lambda a, b, c: a and (b or c) # noqa: E731
space = [(a, b, c) for a in (False, True) for b in (False, True) for c in (False, True)]
pairs: dict[int, list[tuple[tuple[bool, bool, bool], tuple[bool, bool, bool]]]] = {0: [], 1: [], 2: []}
for i in range(3):
for u in space:
if not u[i]:
v = (i == 0 or u[0], i == 1 or u[1], i == 2 or u[2])
if expr(*u) != expr(*v):
pairs[i].append((u, v))
for cand in itertools.combinations(space, 4):
cset = set(cand)
if all(any(u in cset and v in cset for u, v in pairs[i]) for i in range(3)):
return list(cand)
raise AssertionError("No MC/DC cover found")
def run_mini_ast_mutation_demo() -> tuple[int, int, int]:
tree = ast.parse(PRICING_KERNEL_SRC)
mutated_trees: list[ast.Module] = []
for node in ast.walk(tree):
if isinstance(node, ast.Compare) and isinstance(node.ops[0], ast.GtE):
ln, col = node.lineno, node.col_offset
cloned = copy.deepcopy(tree)
for sub in ast.walk(cloned):
if isinstance(sub, ast.Compare) and getattr(sub, "lineno", 0) == ln and getattr(sub, "col_offset", 0) == col:
sub.ops[0] = ast.Gt()
ast.fix_missing_locations(cloned)
mutated_trees.append(cloned)
weak_killed = sum(1 for m in mutated_trees if _run_mut(m, units=200) <= 0)
bva_killed = sum(1 for m in mutated_trees if _run_mut(m, units=100) != 9300 or _run_mut(m, units=1000) != 68000)
return len(mutated_trees), weak_killed, bva_killed
def _run_mut(tree: ast.Module, units: int) -> int:
ns: dict[str, object] = {}
exec(compile(tree, "<mut>", "exec"), ns)
fn = ns["compute_net_cents"]
return int(fn(units=units, tier="growth", promo_bps=0)) # type: ignore[operator]
def check_hoare_wp_and_loop(n: int) -> str:
wp_target = "y <= 20"
wp_step1 = wp_target.replace("y", "(x * 2)")
wp_step2 = wp_step1.replace("x", "(x + 1)")
acc, i = 0, 0
assert 0 <= i <= n and acc == (i * (i - 1)) // 2
while i < n:
v_before = n - i
acc += i
i += 1
assert 0 <= i <= n and acc == (i * (i - 1)) // 2 and (n - i) < v_before
assert acc == (n * (n - 1)) // 2
return wp_step2
@settings(derandomize=True, max_examples=30)
@given(
units=st.integers(min_value=1, max_value=10000),
tier=st.sampled_from(("standard", "growth", "enterprise")),
promo_bps=st.integers(min_value=0, max_value=10000),
)
def _prop_non_negative_bounded(units: int, tier: str, promo_bps: int) -> None:
net = int(compute_net_cents(units, tier, promo_bps)) # type: ignore[operator]
assert net > 0
if units < 10000:
assert int(compute_net_cents(units + 1, tier, promo_bps)) >= 0 # type: ignore[operator]
async def _verify_asgi_contract() -> tuple[int, int, int]:
store = InMemoryFakeStore()
app = FastAPI()
@app.post("/v1/quote")
async def quote(req: QuoteInput) -> dict[str, int]:
net = int(compute_net_cents(req.units, req.tier, req.promo_bps)) # type: ignore[operator]
store.put("last", net)
return {"net_cents": net}
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as cli:
r_ok = await cli.post("/v1/quote", json={"units": 100, "tier": "growth", "promo_bps": 0})
r_bad = await cli.post("/v1/quote", json={"units": "100", "tier": "growth", "promo_bps": 0})
return r_ok.status_code, r_bad.status_code, store.rows["last"]
if __name__ == "__main__":
mcdc = verify_mcdc_a_and_b_or_c()
tot, w_k, b_k = run_mini_ast_mutation_demo()
wp_str = check_hoare_wp_and_loop(6)
_prop_non_negative_bounded()
st_ok, st_bad, saved = asyncio.run(_verify_asgi_contract())
print(f"Verified! MC/DC={len(mcdc)} | Mutants={tot} (weak={w_k}, BVA={b_k}) | wp={wp_str} | ASGI=({st_ok},{st_bad},{saved})")
3.3 Ba Bảng Ra quyết định Sản xuất 2026 (Production Decision Playbooks)#
Playbook A — Lựa chọn Kỹ thuật Kiểm thử Hộp đen & Hộp trắng Theo Tầng Rủi ro#
| Ngữ cảnh & Mức Rủi ro | Kỹ thuật Thiết kế Ca Test Chuẩn 2026 | Tại sao Không Dùng Kỹ thuật Yếu hơn? | Tiêu chí Nghiệm thu Tối thiểu |
|---|---|---|---|
Biên định lượng (units, giá, ngưỡng SLA, mảng chỉ số) |
3-Value BVA ({a-1, a, a+1, b-1, b, b+1}) + Phân hoạch Âm tính (NaN, quá ngưỡng, sai kiểu) |
EP và 2-Value BVA có thể bỏ sót lỗi dịch biên x >= a + 1 hoặc x > a |
100% điểm biên được khẳng định đúng giá trị đầu ra chính xác |
Cấu hình đa tham số (N cờ, vùng, gói dịch vụ) |
Bảng Quyết định (\(k \le 4\)) hoặc Pairwise Combinatorial (\(t=2\)) (\(k \ge 5\)) | Vét cạn \(v^n\) làm nổ thời gian CI; thử đơn lẻ từng tham số bỏ sót lỗi tương tác cặp | Phủ 100% các cặp giá trị \((p_i, p_j)\) |
| Logic quyết định an toàn / phân quyền / cổng thanh toán | Unique-Cause / Masking MC/DC (N + 1 véc-tơ độc lập) |
100% Statement hay Condition Coverage bỏ lọt điều kiện chết hoặc lỗi short-circuit |
Từng điều kiện nguyên tử có đủ cặp độc lập làm đổi kết quả quyết định |
Playbook B — Đánh đổi Mutation Testing, Hypothesis & Metamorphic Testing#
| Câu hỏi Kỹ thuật | Lựa chọn Khuyến nghị SOTA 2026 | Lựa chọn Cần Tránh / Chống Lạm dụng | Ghi chú Vận hành CI |
|---|---|---|---|
Khi nào dùng Mutation Testing? |
Chạy trên hạt nhân nghiệp vụ lõi hoặc phần diff thay đổi trong PR (mô hình Google IEEE TSE 2021 & mutmut) |
Chạy toàn bộ kho mã hàng trăm nghìn dòng mỗi lần push hoặc ép 100% mù quáng bỏ qua đột biến tương đương |
Đặt cổng Mutation Score >= 85%–90% kết hợp bỏ qua log/chuỗi cấu hình (ARID) |
Khi nào dùng Hypothesis vs Test ví dụ cố định? |
Dùng @given cho hàm thuần, parser, bộ tuần tự hóa Pydantic, tính giá, thuật toán chia lô và máy trạng thái (RuleBasedStateMachine) |
Dùng @given cho kiểm thử UI E2E chậm hàng giây mỗi mẫu hoặc quên đặt derandomize=True trong CI |
Đặt @settings(derandomize=True, max_examples=50) để vừa sâu vừa tái lập tuyệt đối |
| Kiểm thử dịch vụ ML/LLM không có Ground-Truth tĩnh thế nào? | Metamorphic Testing (bất biến hoán vị lô, đơn điệu, paraphrase, sai số fp16 vs fp64) |
Chỉ viết assert len(response) > 0 hay assert 0 <= score <= 1 (chỉ kiểm kiểu, mù ngữ nghĩa) |
Ghép bất biến biến đổi với tập hồi quy golden failure modes |
Playbook C — Chọn Mô hình TDD (Chicago vs London), Test Doubles & Xác minh Hình thức#
| Tình huống Hệ thống | Trường phái & Công cụ Tối ưu | Anti-Pattern Nguy hiểm | Kiểm chứng Bổ sung |
|---|---|---|---|
Dịch vụ Backend / API FastAPI (Pydantic v2 + DB) |
Chicago TDD + Protocol DI: dùng Fake (InMemoryRepo, ASGITransport), Stub (FixedClock), Spy (AuditSpy) |
London Over-Mocking: mock sạch mọi phụ thuộc bên trong và chỉ khẳng định .assert_called() |
Kết hợp kiểm thử hợp đồng 422 strict schema & bất biến trạng thái |
| Hạt nhân Thuật toán / Vòng lặp Tài chính / Mạch Điều kiện Hẹp | Hoare Logic (wp, Invariant \(I\), Variant \(V\)) + Symbolic Execution / Concolic (Z3, CrossHair) |
Phó mặc cho 1,000–5,000 mẫu thử ngẫu nhiên đồng nhất (xác suất \(< 10^{-4}\) tại điều kiện bằng hẹp) |
Tách hạt nhân thuần không I/O (Functional Core) để bộ giải chạy < 20 ms |
| Đóng gói Ma trận Kiểm thử Đa Phiên bản | uv.lock + noxfile.py (lint, typecheck, tests đa phiên bản Python, --cov-branch) |
Chạy tay pytest trên máy dev cá nhân thiếu lockfile và thiếu kiểm tra tĩnh mypy --strict |
Khóa ngưỡng --cov-fail-under=90 cùng ruff và quét AST an toàn |
Trụ cột 4 — Bàn Thực hành Công nghiệp: WB-Ch05 (verification_tdd_lab) & Kiểm định 16/16 pytest#
4.1 Kiến trúc Gói, Khám phá Tương tác & Hợp đồng An toàn Môi trường#
Trước khi bước vào chạy CLI WB-Ch05, hãy tương tác trực tiếp với ba trình mô phỏng chuẩn toán học chạy ngay trên trình duyệt để quan sát cơ chế thăm dò biên BVA/MC/DC, sự sụp đổ của 100% Line Coverage dưới góc nhìn Mutation Testing + Hypothesis Shrinking, và quá trình giải điều kiện đường đi ký hiệu:
Cấu trúc mã nguồn đầy đủ của bàn thực hành WB-Ch05 (labs/ch05-verification-testing-tdd-workbench/):
labs/ch05-verification-testing-tdd-workbench/
├── pyproject.toml # fastapi>=0.115, pydantic>=2, httpx>=0.27, hypothesis>=6.100; requires-python>=3.12, ruff, mypy strict
├── uv.lock # Tệp khóa tái lập 43 gói (Python >=3.12) giải quyết qua uv lock
├── noxfile.py # Ma trận CI 4 phiên: lint, typecheck, tests (3.12/3.13), coverage (>=90% nhánh)
├── README.md # Hướng dẫn thực hành 100% tiếng Việt
├── src/
│ └── verification_tdd_lab/
│ ├── __init__.py
│ ├── target_api_and_domain.py # QuoteRequest strict v2, Protocol Test Doubles (Stub/Fake/Spy/Dummy), compute_pricing_core, legacy bugs & FastAPI app
│ ├── testing_engines.py # EP/BVA generator, MC/DC N+1 solver, AST Mutation Engine + trace coverage, Delta Shrinker + Hypothesis strategies
│ └── formal_verifier.py # Hoare wp & 4-obligation loop verifier + AST Symbolic Execution (Fourier-Motzkin SAT/UNSAT) vs 2000 random samples
├── scripts/
│ └── run_lab_demo.py # CLI (--quick, --seed 42, --output artifacts/t2_ch05_workbench_results.json)
├── tests/
│ └── test_verification_tdd_lab.py # 16 ca kiểm thử (unittest.TestCase + pytest + @given Hypothesis + ASGITransport + AST security scan)
└── artifacts/
└── t2_ch05_workbench_results.json # Báo cáo thực nghiệm định lượng (6 KPI, 4 bars, 4 tables)
Hợp đồng An toàn Môi trường: Toàn bộ 16 ca kiểm thử và CLI benchmark chạy 100% offline trên .venv Python 3.12.16 qua httpx.ASGITransport và bộ giải thuần Python (hypothesis==6.170.17 đặt derandomize=True). Trình quét AST ở test_14 kiểm toán toàn bộ src/, scripts/, tests/, noxfile.py chỉ cấm nhập khẩu các mô-đun giải tuần tự không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal), hoàn toàn cho phép mọi thư viện SOTA (fastapi, pydantic, httpx, hypothesis, nox).
4.2 Thực thi CLI Workbench & Bảng 6 Chỉ số Thực nghiệm (artifacts/t2_ch05_workbench_results.json)#
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch05_workbench_results.json
Chỉ số KPI (artifacts/t2_ch05_workbench_results.json) |
Giá trị Đo kiểm Thực tế (.venv Python 3.12.16) |
Trạng thái |
|---|---|---|
kpi_line_cov_vs_mutation_score (100% Line Cov Trap vs Hardened) |
25.6% -> 100.0% (100% lines!; Weak smoke phủ 100.0% dòng nhưng chỉ diệt 10/39 (25.64%) đột biến: CRP 1/16 = 6.2%, ROR 4/12 = 33.3%, AOR 3/7 = 42.9%, LCR 2/4 = 50.0%; Hardened diệt 39/39 (100.0%)) |
ok (Đã xác minh) |
kpi_mcdc_minimal_vectors (FAA DO-178C MC/DC) |
4 vs 8 vectors (N+1 minimal; 4 véc-tơ thỏa mãn cặp độc lập cho cả 3 điều kiện của A and (B or C) thay vì 8 véc-tơ vét cạn) |
ok (Đã xác minh) |
kpi_bva_and_batch_invariance (3-Value BVA & Batch Permutation) |
9300 vs 10000 c (units=100 bug; 3-Value BVA phát hiện legacy_buggy_quote_cents viết units > 100 mất chiết khấu 700 bps ở units=100; clean_batch_permutation_invariant=True, legacy_batch_state_contaminated=True) |
ok (Đã xác minh) |
kpi_hypothesis_delta_shrinking (Hypothesis & Delta Shrinking) |
u=4821 -> u=1 (14 steps; bộ thu gọn nhị phân rút gọn phản ví dụ (units=4821, tier="enterprise", promo=10000, sla=0.91) về đúng mẫu tối giản (units=1, promo=10000, sla=0.0)) |
ok (Đã xác minh) |
kpi_hoare_wp_loop_proof (Hoare wp + Invariant & Variant) |
4/4 verified (bug rejected; wp suy ra (x + 1) * 2 <= 20, vòng lặp i < n đạt 4/4 nghĩa vụ trên n=0..10, vòng lặp lệch i <= n bị từ chối ở obligation=2, n=0, i=0, next_i=1) |
ok (Đã xác minh) |
kpi_symbolic_vs_random_fuzz (Symbolic vs 2,000 Random Samples) |
4 vs 0 hits (8.52 ms; 2,000 mẫu ngẫu nhiên 0 lần trúng; Symbolic duyệt 12 đường khả thi, tỉa 4 nhánh UNSAT, tìm thấy 4 chứng nhân ZeroDivisionError {promo_bps: 10000, tier_code: 2, units: 1000}) |
ok (Đã xác minh) |
4.3 Hợp đồng 16 Ca Kiểm thử (tests/test_verification_tdd_lab.py)#
Toàn bộ 16/16 ca kiểm thử (1 ca unittest.TestCase + 12 ca pytest + 3 tham số @pytest.mark.parametrize) đạt xanh tuyệt đối (16 passed), ruff check src scripts tests noxfile.py đạt All checks passed!, mypy src đạt Success: no issues found in 4 source files, và uv.lock giải quyết sạch 43 gói:
| # | Tên Hàm Kiểm thử (test_verification_tdd_lab.py) |
Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | TestUnittestInteroperability.test_01_unittest_ep_bva_and_protocol_doubles |
Kiểm chứng unittest.TestCase chạy mượt trong pytest; bắt lỗi biên units=100 (9300 vs 10000) và xác minh FixedClock (Stub), InMemoryQuoteRepo (Fake), RecordingAuditSpy (Spy), NullAuditDummy (Dummy). |
| 2 | test_02_bva_vector_generator_2value_vs_3value |
Xác nhận tập 2-Value (8 điểm) và 3-Value (12 điểm quanh 1, 100, 1000, 10000) bắt đúng lỗi lệch biên tại units=100. |
| 3 | test_03_mcdc_minimal_n_plus_one_independence_pairs |
Kiểm chứng bộ giải MC/DC trên A and (B or C) thu gọn từ 8 xuống 4 véc-tơ tối thiểu, mỗi điều kiện có ít nhất 1 cặp độc lập hợp lệ. |
| 4 | test_04_ast_mutation_weak_100_line_cov_vs_hardened_and_operators |
Chứng minh trên 39 đột biến AST (ROR, AOR, LCR, CRP) rằng bộ smoke đạt 100.0% line coverage nhưng < 50% mutation score (25.64%), còn bộ gia cố đạt >= 90% (100.0%). |
| 5 | test_05_pure_python_delta_shrinker_minimizes_counterexample |
Xác minh shrink_counterexample thu gọn units=4821, promo_bps=10000 về đúng cực tiểu (units=1, tier="enterprise", promo_bps=10000, sla_score=0.0) sau >= 5 (14) bước. |
| 6 | test_06_hypothesis_quote_non_negative_and_margin_bounds |
Dùng @given(quote_request_strategy()) (derandomize=True, max_examples=50) kiểm chứng 0 <= discount_bps <= 9000, đẳng thức kế toán subtotal == discount + net, và biên lãi 1000 <= margin <= 10000. |
| 7 | test_07_hypothesis_metamorphic_batch_permutation_invariance |
Dùng @given(st.lists(...)) chứng minh compute_batch_score bất biến khi đảo thứ tự lô, đồng thời vạch trần legacy_batch_score làm nhiễm trạng thái giữa các phần tử. |
| 8 | test_08_hypothesis_differential_pricing_monotonicity_and_json_roundtrip |
Dùng @given kiểm tra round-trip JSON QuoteRequest (Pydantic v2) không mất mát thông tin và tính đơn điệu subtotal(u+1) > subtotal(u). |
| 9 | test_09_hoare_wp_and_while_loop_invariant_and_variant |
Kiểm định compute_wp_assignment_chain suy ra (x + 1) * 2 <= 20, xác minh vòng lặp i < n đạt 4/4 nghĩa vụ Hoare trên n=0..10, và từ chối vòng lặp lỗi i <= n. |
| 10 | test_10_symbolic_execution_vs_random_fuzz_and_unsat_pruning |
Xác minh Thực thi Ký hiệu tỉa >= 3 (4) nhánh UNSAT và tìm được ZeroDivisionError (tier_code=2, promo_bps=10000) trong khi 2,000 mẫu ngẫu nhiên trúng 0 lần. |
| 11 | test_11_fastapi_httpx_asgitransport_strict_v2_and_contract |
Chạy httpx.ASGITransport kiểm tra /health (200), POST /v1/quote (200, 8800c), GET /v1/quotes/api-100 (200), strict Pydantic v2 (422 khi ép kiểu/dư trường), /v1/batch-score (200), kèm yield fixture teardown. |
| 12–14 | test_12_pytest_fixtures_parametrize_and_monkeypatch_interplay (3 ca) |
Kiểm chứng @pytest.mark.parametrize qua 3 phân hoạch (standard/1, growth/100, enterprise/1000) và vá an toàn monkeypatch.setattr tự khôi phục sau test. |
| 15 | test_13_noxfile_ci_matrix_and_cli_demo_quick_export |
Kiểm tra AST noxfile.py có đủ 4 phiên lint, typecheck, tests, coverage và chạy CLI run_lab_demo.py --quick xuất JSON hợp lệ (6 KPI, 4 bars, 4 tables). |
| 16 | test_14_security_only_ast_scan_no_unsafe_deserialization |
Quét AST toàn bộ src/, scripts/, tests/, noxfile.py bảo đảm 0 import giải tuần tự nguy hiểm (pickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & Nghiên cứu Tiên phong (Curated Reading List)#
- Hoare, C. A. R. (Communications of the ACM, Vol. 12, No. 10, 1969, pp. 576–580). An Axiomatic Basis for Computer Programming.
Vì sao quan trọng: Đặt nền tảng đại số tiên đề cho Bộ ba Hoare \(\{P\}\ C\ \{Q\}\), quy tắc gán và bất biến vòng lặp cho phép chứng minh toán học tính đúng đắn phần mềm. - King, J. C. (Communications of the ACM, Vol. 19, No. 7, 1976, pp. 385–394). Symbolic Execution and Program Testing.
Vì sao quan trọng: Khai sinh phương pháp thay giá trị cụ thể bằng biểu thức ký hiệu cùng điều kiện đường đi \(\Pi\) — nền móng choKLEE,Z3, vàCrossHair. - Claessen, K. & Hughes, J. (ICFP 2000) + MacIver, D. R., Hatfield-Dodds, Z. (JOSS 2019) & MacIver, D. R., Donaldson, A. F. (ECOOP 2020). QuickCheck & Hypothesis: Test-Case Reduction via Test-Case Generation.
Vì sao quan trọng: Giải thích bước nhảy vọt từ thu gọn kiểu ngoài sang thu gọn nội tại trên luồng lựa chọn Conjecture, bảo toàn 100% bất biến miền khi thu gọn phản ví dụ. - Jia, Y. & Harman, M. (IEEE TSE, 2011) + Petrović, G., Ivanković, M., Fraser, G. & Just, R. (IEEE TSE, 2021). An Analysis and Survey of the Development of Mutation Testing & Practical Mutation Testing at Scale: A View from Google.
Vì sao quan trọng: Định chuẩn toán tử đột biến, bài toán đột biến tương đương, và cách Google triển khai kiểm thử đột biến gia tăng theo diff ngay trong quy trình code review ở quy mô hàng tỷ dòng mã. - Harman, M. et al. (Meta, 2025). Mutation-Guided LLM-Based Test Generation at Meta (
ACH).
Vì sao quan trọng: Công bố bước tiến SOTA 2025 kết hợp đột biến nhắm mục tiêu với LLM để sinh các assertion chất lượng cao diệt đúng đột biến sống sót trên luồng bảo mật & quyền riêng tư, khắc phục tình trạng LLM tự sinh test vô thưởng vô phạt. - Xie, X., Murphy, C., Chen, T. Y. et al. (JSS 2011; ACM Computing Surveys 2018) & 2024–2026 Bidirectional Metamorphic Testing & LLM Surveys + RTCA
DO-178C(MC/DC).
Vì sao quan trọng: Hợp nhất tiêu chuẩn độ phủ an toàn hàng khôngMC/DC(\(N+1\) cặp độc lập) với kiểm thử biến đổi (Metamorphic Relations) giải quyết bài toán thiếu Test Oracle cho hệ thống ML và LLM hiện đại.
5.2 Tám Điểm Kiểm tra Tư duy (Q1–Q8) & Sáu Bài tập Trọng số#
- Q1 (
Verificationvs.Validation&Testing Trophy+Metamorphic): Phân biệt Verification với Validation, giải thích vì sao Testing Trophy dồn trọng tâm vào Integration/Contract trong WebAPI, và nêu 2 quan hệ biến đổi (Metamorphic Relations) cho dịch vụ gợi ý/tính điểm ML không có nhãn tĩnh. - Q2 (
EPvs.2-Value/3-Value BVA&Pairwise): Chứng minh với ngưỡngunits >= 100tại saoEPvà2-Value BVAcó thể bỏ sót lỗi dịch biên, trong khi3-Value BVA({99, 100, 101}) bắt trọn lỗiunits > 100; giải thích tại sao Pairwise (\(t=2\)) giảm từ \(v^n\) xuống \(\Theta(v^2 \log n)\). - Q3 (
CFG,C0/C1, Condition Coverage &MC/DC): Dựng ví dụ phản chứng chỉ ra 100% Condition Coverage không suy ra 100% Decision Coverage; lập đủ4véc-tơ tối thiểu và 3 cặp độc lập choA and (B or C)kèm lưu ý đánh giá đoản mạch trong Python. - Q4 (
AST Mutation Testing& Ảo giác100%Line Coverage): Phân tích kết quảWB-Ch05(100.0%dòng nhưng chỉ25.64%(10/39) mutation score); giải thích công thức \(M = K/(T-E)\) và vì sao bài toán nhận diện toàn bộ đột biến tương đương \(E\) là bất khả quyết định. - Q5 (
HypothesisInternal Shrinking & State Contamination): Mô tả cách động cơ Conjecture thu gọn trên luồng chọn lựa nhị phân thay vì đột biến đối tượng đích, và giải thích cách kiểm thử hoán vị lô bắt lỗi tích lũy chéo ởlegacy_batch_score. - Q6 (Hoare
wp(C, Q)& Vòng lặp \(I, V\)): Tính từng bước \(\text{wp}(x := x + 1;\ y := x \times 2,\ y \le 20)\) và trình bày 4 nghĩa vụ Hoare để bác bỏ vòng lặpwhile i <= n. - Q7 (
Symbolic Executionvs.Random Fuzz): Giải thích cơ chế tỉa nhánhUNSATqua Fourier–Motzkin/SMT trên nhánhunits > 500 && units < 200và chứng minh toán học lý do2,000mẫu ngẫu nhiên chỉ có~6.4%cơ hội chạm lỗitier_code=2 && promo_bps=10000trong khi Symbolic Execution chắc chắn trúng (8.52 ms). - Q8 (
Chicagovs.London,5 Test Doubles&pytest/nox): Phân biệtDummy,Stub,Spy,Mock,Fake; giải thích lợi thế của DI quaProtocol+httpx.ASGITransportcùng vòng đờiyieldfixture và 4 phiên trongnoxfile.py.
Sáu Bài tập Thực hành (Gợi ý Từng bước Tích hợp Tại Mục Quiz Cuối Trang)#
-
Bài tập 1 (15 điểm) — Thiết kế Biên
3-Value BVA& GiảiMC/DC(DO-178C):- Bước thực hành: Mở
testing_engines.py, đối chiếu tậpbva_2_value_unitsvsbva_3_value_unitstrênlegacy_buggy_quote_cents; kiểm tra hàmsolve_mcdc_a_and_b_or_c()tìm4véc-tơ tối thiểu choevaluate_sla_gatevà chạypytest -k "test_01 or test_02 or test_03" -p no:cacheprovider -v. - Tiêu chí đạt: Bắt được lỗi
units=100(9300vs10000cents), xuất đủ 3 cặp độc lập choA, B, Cchỉ với4/8véc-tơ.
- Bước thực hành: Mở
-
Bài tập 2 (20 điểm) — Đột biến
AST(Mutation Testing) & Diệt Đột biến Sống Sót:- Bước thực hành: Chạy
run_ast_mutation_benchmark()trêncompute_pricing_core, thống kê tỷ lệ giết của từng lớpROR,AOR,LCR,CRPgiữa bộ smoke100%dòng với bộ gia cố, và kiểm chứngtest_04. - Tiêu chí đạt: Xác nhận bộ smoke đạt
100.0%dòng nhưng< 50%mutation score (25.64%), bộ gia cố đạt>= 90%(100.0%,39/39).
- Bước thực hành: Chạy
-
Bài tập 3 (15 điểm) —
HypothesisProperty Testing, Delta Shrinking & Bất biến Hoán vị Lô:- Bước thực hành: Chạy
shrink_counterexampletừ(units=4821, tier="enterprise", promo_bps=10000, sla_score=0.91), đồng thời chạy3bài test@given(..., derandomize=True, max_examples=50)kiểm địnhtest_05–test_08. - Tiêu chí đạt: Rút gọn về
(1, "enterprise", 10000, 0.0)trong14bước;compute_batch_scoređạt bất biến hoán vị lô vàlegacy_batch_scorebị phát hiện rò rỉ.
- Bước thực hành: Chạy
-
Bài tập 4 (15 điểm) — Xác minh Hoare
wp, Bất biến Vòng lặp & Hàm hạng Kết thúc:- Bước thực hành: Kiểm tra
compute_wp_assignment_chainvà chạyverify_hoare_loop_sum_and_wpcho cảoff_by_one_bug=FalsevàTrue, xác minhtest_09. - Tiêu chí đạt:
wpxuất(x + 1) * 2 <= 20, vòng lặp chuẩn vượt4/4nghĩa vụ trênn=0..10, vòng lặp lỗi bị bác bỏ tại{obligation: 2, n: 0, i: 0, next_i: 1}.
- Bước thực hành: Kiểm tra
-
Bài tập 5 (20 điểm) — Thực thi Ký hiệu (
Symbolic Execution), TỉaUNSAT& Săn Lỗi Đường Hẹp:- Bước thực hành: Chạy
explore_symbolic_paths()vàrun_random_vs_symbolic_comparison(seed=42, n_random=2000)trongformal_verifier.py; kiểm chứngtest_10. - Tiêu chí đạt: Tỉa
4nhánh vô nghiệmUNSAT, tổng hợp chính xác4chứng nhânZeroDivisionError(promo_bps=10000, tier_code=2) trong< 20 ms(8.52 ms) khi2,000mẫu ngẫu nhiên đạt0.
- Bước thực hành: Chạy
-
Bài tập 6 (15 điểm) — Kiến trúc
TDDFastAPI(ProtocolDoubles),noxfile.py& Nghiệm thu Toàn bộ16/16 pytest:- Bước thực hành: Kiểm tra
create_verification_appdùngInMemoryQuoteRepo+FixedClock+RecordingAuditSpyquahttpx.ASGITransport(200/422), chạyruff check src scripts tests noxfile.py,mypy src,run_lab_demo.py, và toàn bộpytest -p no:cacheprovider -v. - Tiêu chí đạt:
ruff0lỗi,mypy0lỗi,uv.lockđồng bộ, AST0import giải tuần tự cấm, và16/16 pytestPASS.
- Bước thực hành: Kiểm tra
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric — 100 Điểm)#
| Hạng mục Đánh giá | Trọng số | Tiêu chí Đạt Chuẩn Nghiệm thu (>= 80/100) |
Lệnh / Ca Kiểm thử Đối chứng |
|---|---|---|---|
1. EP, 3-Value BVA & FAA DO-178C MC/DC |
15 | Bắt lỗi biên units=100 (9300 vs 10000), giải được 4 véc-tơ độc lập (N+1) cho A and (B or C). |
Tests 01, 02, 03 |
2. Đột biến AST (ROR/AOR/LCR/CRP) & Bẫy 100% Line Cov |
20 | Chứng minh bộ smoke 100% dòng < 50% mutation score (25.64%), bộ gia cố >= 90% (100.0%). |
Test 04 |
3. Hypothesis @given, Delta Shrinking & Bất biến Hoán vị |
15 | Thu gọn phản ví dụ về units=1, pass 3 thuộc tính derandomize=True, bắt lỗi lô cũ. |
Tests 05, 06, 07, 08 |
4. Xác minh Hình thức: Hoare wp (I, V) & Thực thi Ký hiệu |
30 | Kiểm chứng 4/4 nghĩa vụ vòng lặp (từ chối i <= n), tỉa 4 nhánh UNSAT, bắt lỗi chia 0 trong < 20 ms vượt trội 2,000 mẫu ngẫu nhiên. |
Tests 09, 10 |
5. TDD FastAPI (ASGITransport), noxfile.py, ruff/mypy & Cổng AST |
20 | Hợp đồng 200/422 với Protocol Doubles, unittest + parametrize + monkeypatch, ruff 0 lỗi, mypy 0 lỗi, 16/16 pytest. |
Tests 11–14 + ruff + mypy |
| Tổng cộng | 100 | Đạt tối thiểu 80/100 tổng điểm và không có mục nào 0 điểm (toàn bộ 16/16 test phải PASS). |
pytest -p no:cacheprovider -v |
Coverage Illusion: 100%-Line Suite vs AST Mutation Score (%)
AST Mutant Kill Rate by Operator Class (Hardened vs Weak)
Edge-Bug Discovery: Symbolic vs 2000 Random Samples
Property Counterexample Delta Shrinking Trajectory (units)
AST Mutation Testing Benchmark on compute_pricing_core
| suite_profile | line_coverage_pct | killed_vs_total | mutation_score_pct | verdict |
|---|---|---|---|---|
| weak_smoke_100_line_cov | 100.0% | 10 / 39 | 25.6% | FALSE_CONFIDENCE_FAIL |
| hardened_ep_bva_mcdc_property | 100.0% | 39 / 39 | 100.0% | GATE_PASSED_>=90% |
Minimal N+1 = 4 Unique-Cause MC/DC Vectors for A and (B or C)
| vector_idx | A_sla_ok | B_is_enterprise | C_volume_qualified | gate_outcome |
|---|---|---|---|---|
| 1 | False | False | True | False |
| 2 | True | False | False | False |
| 3 | True | False | True | True |
| 4 | True | True | False | True |
Formal Verification: Hoare wp, Loop Invariants & Symbolic Execution
| verifier_engine | target_specification | outcome | witness_or_formula |
|---|---|---|---|
| hoare_wp_assignments | x := x + 1; y := x * 2 {y <= 20} | DERIVED | (x + 1) * 2 <= 20 |
| hoare_while_valid_i_lt_n | Init + Maint + Exit + Variant V=n-i | 4/4_VERIFIED | 0 <= i <= n and acc == i*(i-1)//2 |
| hoare_while_buggy_i_le_n | Off-by-one guard i <= n | REJECTED | {"acc": 0, "i": 0, "n": 0, "next_i": 1, "obligation": 2} |
| symbolic_path_explorer | legacy_pricing_symbolic_kernel | 4_BUGS_4_PRUNED | {"promo_bps": 10000, "tier_code": 2, "units": 1000} |
FastAPI Strict Pydantic v2 Contract, Test Doubles & BVA Gates
| verification_surface | probe_or_input | observed_output | status |
|---|---|---|---|
| 3_value_bva_boundary_100 | units=100, tier=growth, promo=0 | hard=9300c vs legacy=10000c | BOUNDARY_VERIFIED |
| metamorphic_batch_permutation | [req_a, req_b] vs [req_b, req_a] | clean_inv=True, legacy_leak=True | INVARIANT_ENFORCED |
| fastapi_strict_v2_and_doubles | POST /v1/quote + InMemoryFake + AuditSpy | ok=200 (8800c), bad=422, spy=1 | CONTRACT_PASSED |
03-track-2-data-and-ai-engineering/part-01-software-systems-foundations/labs/ch05-verification-testing-tdd-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "verification-tdd-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 WB-Ch05: Black-Box EP/BVA, FAA MC/DC, AST Mutation Testing, Hypothesis Property Shrinking, Hoare Logic wp, Symbolic Execution & FastAPI TDD"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"pydantic>=2.0",
"httpx>=0.27",
"hypothesis>=6.100",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"pytest-cov>=5.0",
"ruff>=0.8",
"mypy>=1.10",
"nox>=2024.10",
]
[project.scripts]
fsds-verification-lab = "verification_tdd_lab.target_api_and_domain:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
"""Nox CI automation matrix for WB-Ch05 (lint, typecheck, tests, coverage)."""
from __future__ import annotations
import nox
PYTHON_VERSIONS = ["3.12", "3.13"]
LINT_TARGETS = ("src", "scripts", "tests", "noxfile.py")
@nox.session(python="3.12")
def lint(session: nox.Session) -> None:
"""Run Ruff static lint checks across package, scripts, tests, and noxfile."""
session.install("ruff>=0.8")
session.run("ruff", "check", *LINT_TARGETS)
@nox.session(python="3.12")
def typecheck(session: nox.Session) -> None:
"""Run strict mypy type checking across src/."""
session.install(".[dev]")
session.run("mypy", "src")
@nox.session(python=PYTHON_VERSIONS)
def tests(session: nox.Session) -> None:
"""Execute deterministic pytest + unittest + Hypothesis test suite."""
session.install(".[dev]")
session.run("pytest", "-p", "no:cacheprovider", "-v", *session.posargs)
@nox.session(python="3.12")
def coverage(session: nox.Session) -> None:
"""Run pytest with branch coverage threshold enforcement (>= 90%)."""
session.install(".[dev]")
session.run(
"pytest",
"-p",
"no:cacheprovider",
"--cov=verification_tdd_lab",
"--cov-branch",
"--cov-report=term-missing",
"--cov-fail-under=90",
)
"""WB-Ch05 verification & TDD workbench package (`verification_tdd_lab`)."""
from verification_tdd_lab.formal_verifier import (
HoareVerificationResult,
SymbolicPathResult,
compute_wp_assignment_chain,
explore_symbolic_paths,
run_random_vs_symbolic_comparison,
verify_hoare_loop_sum_and_wp,
)
from verification_tdd_lab.target_api_and_domain import (
BatchScoreRequest,
FixedClock,
InMemoryQuoteRepo,
NullAuditDummy,
QuoteRequest,
RecordingAuditSpy,
compute_pricing_core,
create_verification_app,
evaluate_sla_gate,
legacy_batch_score,
legacy_buggy_quote_cents,
)
from verification_tdd_lab.testing_engines import (
MutationBenchmarkReport,
generate_ep_bva_vectors,
quote_request_strategy,
run_ast_mutation_benchmark,
shrink_counterexample,
solve_mcdc_a_and_b_or_c,
)
__all__ = [
"BatchScoreRequest",
"FixedClock",
"HoareVerificationResult",
"InMemoryQuoteRepo",
"MutationBenchmarkReport",
"NullAuditDummy",
"QuoteRequest",
"RecordingAuditSpy",
"SymbolicPathResult",
"compute_pricing_core",
"compute_wp_assignment_chain",
"create_verification_app",
"evaluate_sla_gate",
"explore_symbolic_paths",
"generate_ep_bva_vectors",
"legacy_batch_score",
"legacy_buggy_quote_cents",
"quote_request_strategy",
"run_ast_mutation_benchmark",
"run_random_vs_symbolic_comparison",
"shrink_counterexample",
"solve_mcdc_a_and_b_or_c",
"verify_hoare_loop_sum_and_wp",
]
"""Target domain pricing/SLA kernels, Protocol Test Doubles, and FastAPI contract service."""
from __future__ import annotations
import json
import math
from typing import Any, Literal, Protocol
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict, Field, field_validator
TierName = Literal["standard", "growth", "enterprise"]
class QuoteRequest(BaseModel):
"""Strict Pydantic v2 contract for AI inference quota pricing."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
request_id: str = Field(min_length=3, max_length=64)
units: int = Field(ge=1, le=10000)
tier: TierName
promo_bps: int = Field(ge=0, le=10000)
sla_score: float = Field(ge=0.0, le=1.0)
dry_run: bool = False
@field_validator("sla_score")
@classmethod
def validate_finite_sla(cls, value: float) -> float:
if not math.isfinite(value):
raise ValueError("sla_score must be finite")
return value
class BatchScoreRequest(BaseModel):
"""Strict batch scoring request preserving per-item stateless independence."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
batch_id: str = Field(min_length=3, max_length=64)
items: list[QuoteRequest] = Field(min_length=1, max_length=64)
class ClockPort(Protocol):
"""Dependency interface for deterministic time retrieval."""
def now_iso(self) -> str:
"""Return current ISO-8601 UTC timestamp."""
class QuoteRepositoryPort(Protocol):
"""Repository port separating persistence from domain pricing logic."""
def save(self, request_id: str, payload: dict[str, Any]) -> None:
"""Persist computed quote payload keyed by request_id."""
def get(self, request_id: str) -> dict[str, Any] | None:
"""Fetch previously stored quote payload or None."""
class AuditSinkPort(Protocol):
"""Audit sink port recording billable quote events."""
def record(self, event: str, request_id: str, net_cents: int) -> None:
"""Emit an audit record for a quote evaluation."""
class FixedClock:
"""Stub Test Double returning a deterministic fixed timestamp."""
def __init__(self, fixed_iso: str = "2026-11-22T00:00:00Z") -> None:
self._fixed_iso = fixed_iso
def now_iso(self) -> str:
return self._fixed_iso
class InMemoryQuoteRepo:
"""Fake Test Double implementing real dictionary-backed repository semantics."""
def __init__(self) -> None:
self._store: dict[str, dict[str, Any]] = {}
def save(self, request_id: str, payload: dict[str, Any]) -> None:
self._store[request_id] = dict(payload)
def get(self, request_id: str) -> dict[str, Any] | None:
found = self._store.get(request_id)
return dict(found) if found is not None else None
def count(self) -> int:
return len(self._store)
class RecordingAuditSpy:
"""Spy Test Double capturing audit calls for post-execution inspection."""
def __init__(self) -> None:
self.events: list[tuple[str, str, int]] = []
def record(self, event: str, request_id: str, net_cents: int) -> None:
self.events.append((event, request_id, net_cents))
class NullAuditDummy:
"""Dummy Test Double satisfying AuditSinkPort when audit side effects are unused."""
def record(self, event: str, request_id: str, net_cents: int) -> None:
_ = (event, request_id, net_cents)
def evaluate_sla_gate(sla_ok: bool, is_enterprise: bool, volume_qualified: bool) -> bool:
"""Evaluate compound SLA eligibility predicate: A and (B or C)."""
return sla_ok and (is_enterprise or volume_qualified)
def compute_pricing_core(
units: int,
tier: str,
promo_bps: int,
sla_score: float,
) -> dict[str, int | bool]:
"""Compute hardened deterministic pricing quote & SLA status (AST mutation target)."""
if units < 1 or units > 10000:
raise ValueError("units out of [1, 10000]")
if promo_bps < 0 or promo_bps > 10000:
raise ValueError("promo_bps out of [0, 10000]")
if tier == "enterprise":
base_unit_cents = 80
elif tier == "growth":
base_unit_cents = 100
elif tier == "standard":
base_unit_cents = 120
else:
raise ValueError(f"unsupported tier: {tier}")
if units >= 1000:
volume_bps = 1500
elif units >= 100:
volume_bps = 700
else:
volume_bps = 0
total_discount_bps = min(9000, volume_bps + promo_bps)
subtotal_cents = units * base_unit_cents
discount_cents = (subtotal_cents * total_discount_bps) // 10000
net_cents = subtotal_cents - discount_cents
effective_margin_bps = (net_cents * 10000) // subtotal_cents
sla_ok = sla_score >= 0.85
is_enterprise = tier == "enterprise"
volume_qualified = units >= 100
sla_approved = sla_ok and (is_enterprise or volume_qualified)
return {
"unit_price_cents": base_unit_cents,
"volume_discount_bps": volume_bps,
"total_discount_bps": total_discount_bps,
"subtotal_cents": subtotal_cents,
"discount_cents": discount_cents,
"net_cents": net_cents,
"effective_margin_bps": effective_margin_bps,
"sla_approved": sla_approved,
}
def legacy_buggy_quote_cents(
units: int,
tier: str,
promo_bps: int,
sla_score: float,
) -> dict[str, int | bool]:
"""Unhardened legacy pricing routine containing boundary and narrow zero-division traps."""
if units < 1 or units > 10000:
raise ValueError("units out of [1, 10000]")
if promo_bps < 0 or promo_bps > 10000:
raise ValueError("promo_bps out of [0, 10000]")
if tier == "enterprise":
base_unit_cents = 80
elif tier == "growth":
base_unit_cents = 100
else:
base_unit_cents = 120
# Intentional off-by-one boundary defect: uses `> 100` instead of `>= 100`
if units >= 1000:
volume_bps = 1500
elif units > 100:
volume_bps = 700
else:
volume_bps = 0
total_discount_bps = min(9000, volume_bps + promo_bps)
subtotal_cents = units * base_unit_cents
discount_cents = (subtotal_cents * total_discount_bps) // 10000
net_cents = subtotal_cents - discount_cents
# Intentional narrow edge ZeroDivisionError when tier == "enterprise" and promo_bps == 10000
if tier == "enterprise":
denom = 10000 - promo_bps
effective_margin_bps = ((net_cents * 10000) // subtotal_cents) + (0 // denom)
else:
effective_margin_bps = (net_cents * 10000) // subtotal_cents
sla_approved = sla_score >= 0.85 and (tier == "enterprise" or units >= 100)
return {
"unit_price_cents": base_unit_cents,
"volume_discount_bps": volume_bps,
"total_discount_bps": total_discount_bps,
"subtotal_cents": subtotal_cents,
"discount_cents": discount_cents,
"net_cents": net_cents,
"effective_margin_bps": effective_margin_bps,
"sla_approved": sla_approved,
}
def compute_batch_score(items: list[QuoteRequest]) -> list[dict[str, int | bool]]:
"""Stateless pure batch scoring preserving permutation/order invariance."""
return [
compute_pricing_core(
units=item.units,
tier=item.tier,
promo_bps=item.promo_bps,
sla_score=item.sla_score,
)
for item in items
]
def legacy_batch_score(items: list[QuoteRequest]) -> list[dict[str, int | bool]]:
"""Buggy batch scorer leaking mutable carry-over discount state across items."""
outputs: list[dict[str, int | bool]] = []
carry_promo_bps = 0
for item in items:
effective_promo = min(10000, item.promo_bps + carry_promo_bps)
res = compute_pricing_core(
units=item.units,
tier=item.tier,
promo_bps=effective_promo,
sla_score=item.sla_score,
)
outputs.append(res)
carry_promo_bps = min(2000, carry_promo_bps + (200 if item.tier == "enterprise" else 100))
return outputs
def create_verification_app(
repo: QuoteRepositoryPort | None = None,
clock: ClockPort | None = None,
audit: AuditSinkPort | None = None,
) -> FastAPI:
"""Create FastAPI contract app wired via Protocol Test Doubles."""
quote_repo: QuoteRepositoryPort = repo if repo is not None else InMemoryQuoteRepo()
clock_port: ClockPort = clock if clock is not None else FixedClock()
audit_port: AuditSinkPort = audit if audit is not None else NullAuditDummy()
app = FastAPI(title="FSDS WB-Ch05 Verification & TDD Quote Service", version="2026.1")
@app.get("/health")
async def health() -> dict[str, str]:
return {"status": "ok", "service": "verification-tdd-lab", "version": "2026.1"}
@app.post("/v1/quote")
async def create_quote(body: QuoteRequest) -> dict[str, Any]:
result = compute_pricing_core(
units=body.units,
tier=body.tier,
promo_bps=body.promo_bps,
sla_score=body.sla_score,
)
payload: dict[str, Any] = {
"request_id": body.request_id,
"tier": body.tier,
"units": body.units,
"promo_bps": body.promo_bps,
"sla_score": body.sla_score,
"timestamp": clock_port.now_iso(),
**result,
}
if not body.dry_run:
quote_repo.save(body.request_id, payload)
audit_port.record("quote.computed", body.request_id, int(result["net_cents"]))
return payload
@app.post("/v1/batch-score")
async def batch_score(body: BatchScoreRequest) -> dict[str, Any]:
scored = compute_batch_score(body.items)
items_out: list[dict[str, Any]] = [
{
"request_id": req.request_id,
"tier": req.tier,
"units": req.units,
**res,
}
for req, res in zip(body.items, scored, strict=True)
]
total_net = sum(int(item["net_cents"]) for item in items_out)
return {
"batch_id": body.batch_id,
"count": len(items_out),
"total_net_cents": total_net,
"items": items_out,
}
@app.get("/v1/quotes/{request_id}")
async def fetch_quote(request_id: str) -> dict[str, Any]:
stored = quote_repo.get(request_id)
if stored is None:
raise HTTPException(status_code=404, detail=f"Quote '{request_id}' not found")
return stored
return app
def main() -> None:
"""Print deterministic service health summary for CLI smoke checks."""
sample = compute_pricing_core(units=100, tier="growth", promo_bps=500, sla_score=0.90)
print(json.dumps({"status": "ok", "sample_quote_100": sample}, sort_keys=True))
if __name__ == "__main__":
main()
"""Black-box EP/BVA, FAA DO-178C MC/DC, AST Mutation Engine, and Hypothesis Property Shrinker."""
from __future__ import annotations
import ast
import copy
import inspect
import itertools
import textwrap
import trace
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from hypothesis import strategies as st
from verification_tdd_lab.target_api_and_domain import (
QuoteRequest,
TierName,
compute_pricing_core,
evaluate_sla_gate,
legacy_buggy_quote_cents,
)
@st.composite
def quote_request_strategy(draw: st.DrawFn) -> QuoteRequest:
"""Hypothesis composite strategy generating valid strict QuoteRequest contracts."""
req_id = draw(
st.text(
alphabet="abcdefghijklmnopqrstuvwxyz0123456789-",
min_size=4,
max_size=24,
)
)
units = draw(st.integers(min_value=1, max_value=10000))
tiers: tuple[TierName, ...] = ("standard", "growth", "enterprise")
tier: TierName = draw(st.sampled_from(tiers))
promo_bps = draw(st.integers(min_value=0, max_value=10000))
sla_score = draw(
st.floats(min_value=0.0, max_value=1.0, allow_nan=False, allow_infinity=False)
)
return QuoteRequest(
request_id=req_id,
units=units,
tier=tier,
promo_bps=promo_bps,
sla_score=round(sla_score, 4),
dry_run=True,
)
def generate_ep_bva_vectors() -> dict[str, Any]:
"""Generate Equivalence Partitions, 2-Value BVA, and 3-Value BVA vectors."""
bva_2_units = [0, 1, 99, 100, 999, 1000, 10000, 10001]
bva_3_units = [0, 1, 2, 99, 100, 101, 999, 1000, 1001, 9999, 10000, 10001]
bva_3_promo = [-1, 0, 1, 9999, 10000, 10001]
caught_boundary_bugs: list[dict[str, Any]] = []
for u in bva_3_units:
if 1 <= u <= 10000:
hardened = compute_pricing_core(units=u, tier="growth", promo_bps=0, sla_score=0.90)
legacy = legacy_buggy_quote_cents(units=u, tier="growth", promo_bps=0, sla_score=0.90)
if hardened["net_cents"] != legacy["net_cents"]:
caught_boundary_bugs.append(
{
"units": u,
"hardened_net_cents": hardened["net_cents"],
"legacy_net_cents": legacy["net_cents"],
"hardened_volume_bps": hardened["volume_discount_bps"],
"legacy_volume_bps": legacy["volume_discount_bps"],
}
)
return {
"valid_unit_partitions": [(1, 99), (100, 999), (1000, 10000)],
"invalid_unit_partitions": ["<= 0", ">= 10001"],
"bva_2_value_units": bva_2_units,
"bva_3_value_units": bva_3_units,
"bva_3_value_promo_bps": bva_3_promo,
"caught_legacy_boundary_bugs": caught_boundary_bugs,
}
def solve_mcdc_a_and_b_or_c() -> dict[str, Any]:
"""Solve truth table & minimal N+1 Unique-Cause MC/DC pairs for A and (B or C)."""
all_vectors: list[tuple[bool, bool, bool]] = [
(a, b, c) for a in (False, True) for b in (False, True) for c in (False, True)
]
truth_table = [
{
"id": idx,
"A_sla_ok": a,
"B_is_enterprise": b,
"C_volume_qualified": c,
"outcome": evaluate_sla_gate(a, b, c),
}
for idx, (a, b, c) in enumerate(all_vectors)
]
pairs: dict[str, list[tuple[tuple[bool, bool, bool], tuple[bool, bool, bool]]]] = {
"A_sla_ok": [],
"B_is_enterprise": [],
"C_volume_qualified": [],
}
names = ("A_sla_ok", "B_is_enterprise", "C_volume_qualified")
for i, cond_name in enumerate(names):
for v1 in all_vectors:
if v1[i]:
continue
v2: tuple[bool, bool, bool] = (
True if i == 0 else v1[0],
True if i == 1 else v1[1],
True if i == 2 else v1[2],
)
if evaluate_sla_gate(*v1) != evaluate_sla_gate(*v2):
pairs[cond_name].append((v1, v2))
# Select minimal N + 1 = 4 vectors covering at least one independence pair per condition
best_subset: list[tuple[bool, bool, bool]] | None = None
for candidate in itertools.combinations(all_vectors, 4):
cand_set = set(candidate)
if all(any(u in cand_set and v in cand_set for (u, v) in pairs[name]) for name in names):
best_subset = list(candidate)
break
assert best_subset is not None
return {
"expression": "A and (B or C)",
"exhaustive_count": len(all_vectors),
"mcdc_minimal_count": len(best_subset),
"selected_vectors": [
{
"A_sla_ok": a,
"B_is_enterprise": b,
"C_volume_qualified": c,
"outcome": evaluate_sla_gate(a, b, c),
}
for (a, b, c) in best_subset
],
"independence_pairs": {
k: [[list(u), list(v)] for (u, v) in v_list] for k, v_list in pairs.items()
},
"truth_table": truth_table,
}
@dataclass(frozen=True)
class MutantRecord:
"""Single deterministic AST mutant descriptor."""
mutant_id: int
operator_class: str
lineno: int
description: str
tree: ast.Module
class _MutantCollector(ast.NodeVisitor):
"""Collect deterministic mutation opportunities (ROR, AOR, LCR, CRP) inside a function AST."""
def __init__(self) -> None:
self.sites: list[tuple[int, str, str, Callable[[ast.Module], ast.Module]]] = []
def _add_site(
self,
lineno: int,
op_cls: str,
desc: str,
mutator: Callable[[ast.Module], ast.Module],
) -> None:
self.sites.append((lineno, op_cls, desc, mutator))
def visit_Compare(self, node: ast.Compare) -> None:
ror_map: dict[type[ast.cmpop], tuple[type[ast.cmpop], str]] = {
ast.Lt: (ast.LtE, "< -> <="),
ast.LtE: (ast.Lt, "<= -> <"),
ast.Gt: (ast.GtE, "> -> >="),
ast.GtE: (ast.Gt, ">= -> >"),
ast.Eq: (ast.NotEq, "== -> !="),
ast.NotEq: (ast.Eq, "!= -> =="),
}
for op_idx, op in enumerate(node.ops):
op_type = type(op)
if op_type in ror_map:
new_cls, label = ror_map[op_type]
target_line = node.lineno
target_col = node.col_offset
def _mutate_cmp(
tree: ast.Module,
ln: int = target_line,
col: int = target_col,
idx: int = op_idx,
rep: type[ast.cmpop] = new_cls,
) -> ast.Module:
cloned = copy.deepcopy(tree)
for sub in ast.walk(cloned):
if (
isinstance(sub, ast.Compare)
and getattr(sub, "lineno", None) == ln
and getattr(sub, "col_offset", None) == col
):
sub.ops[idx] = rep()
break
return cloned
self._add_site(target_line, "ROR", label, _mutate_cmp)
self.generic_visit(node)
def visit_BinOp(self, node: ast.BinOp) -> None:
aor_map: dict[type[ast.operator], tuple[type[ast.operator], str]] = {
ast.Add: (ast.Sub, "+ -> -"),
ast.Sub: (ast.Add, "- -> +"),
ast.Mult: (ast.FloorDiv, "* -> //"),
ast.FloorDiv: (ast.Mult, "// -> *"),
}
op_type = type(node.op)
if op_type in aor_map:
new_cls, label = aor_map[op_type]
target_line = node.lineno
target_col = node.col_offset
def _mutate_bin(
tree: ast.Module,
ln: int = target_line,
col: int = target_col,
rep: type[ast.operator] = new_cls,
) -> ast.Module:
cloned = copy.deepcopy(tree)
for sub in ast.walk(cloned):
if (
isinstance(sub, ast.BinOp)
and getattr(sub, "lineno", None) == ln
and getattr(sub, "col_offset", None) == col
):
sub.op = rep()
break
return cloned
self._add_site(target_line, "AOR", label, _mutate_bin)
self.generic_visit(node)
def visit_BoolOp(self, node: ast.BoolOp) -> None:
lcr_map: dict[type[ast.boolop], tuple[type[ast.boolop], str]] = {
ast.And: (ast.Or, "and -> or"),
ast.Or: (ast.And, "or -> and"),
}
op_type = type(node.op)
if op_type in lcr_map:
new_cls, label = lcr_map[op_type]
target_line = node.lineno
target_col = node.col_offset
def _mutate_bool(
tree: ast.Module,
ln: int = target_line,
col: int = target_col,
rep: type[ast.boolop] = new_cls,
) -> ast.Module:
cloned = copy.deepcopy(tree)
for sub in ast.walk(cloned):
if (
isinstance(sub, ast.BoolOp)
and getattr(sub, "lineno", None) == ln
and getattr(sub, "col_offset", None) == col
):
sub.op = rep()
break
return cloned
self._add_site(target_line, "LCR", label, _mutate_bool)
self.generic_visit(node)
def visit_Constant(self, node: ast.Constant) -> None:
if isinstance(node.value, int) and not isinstance(node.value, bool):
orig_val = node.value
new_val = orig_val + 1
target_line = node.lineno
target_col = node.col_offset
def _mutate_const(
tree: ast.Module,
ln: int = target_line,
col: int = target_col,
val: int = new_val,
) -> ast.Module:
cloned = copy.deepcopy(tree)
for sub in ast.walk(cloned):
if (
isinstance(sub, ast.Constant)
and getattr(sub, "lineno", None) == ln
and getattr(sub, "col_offset", None) == col
):
sub.value = val
break
return cloned
self._add_site(target_line, "CRP", f"{orig_val} -> {new_val}", _mutate_const)
self.generic_visit(node)
def generate_ast_mutants(func: Callable[..., Any]) -> tuple[ast.Module, list[MutantRecord]]:
"""Parse target function source and deterministically synthesize single-order AST mutants."""
src = textwrap.dedent(inspect.getsource(func))
base_tree = ast.parse(src)
collector = _MutantCollector()
collector.visit(base_tree)
mutants: list[MutantRecord] = []
for idx, (lineno, op_cls, desc, mut_fn) in enumerate(collector.sites, start=1):
mut_tree = mut_fn(base_tree)
ast.fix_missing_locations(mut_tree)
mutants.append(
MutantRecord(
mutant_id=idx,
operator_class=op_cls,
lineno=lineno,
description=desc,
tree=mut_tree,
)
)
return base_tree, mutants
def _compile_mutant_fn(tree: ast.Module, func_name: str) -> Callable[..., dict[str, int | bool]]:
namespace: dict[str, Any] = {}
code_obj = compile(tree, filename="<ast_mutant>", mode="exec")
exec(code_obj, namespace)
fn = namespace[func_name]
assert callable(fn)
return fn # type: ignore[no-any-return]
def _run_weak_smoke_suite(fn: Callable[..., dict[str, int | bool]]) -> None:
"""100%-line-coverage smoke suite with weak non-exact assertions."""
# Valid partitions covering enterprise (>=1000), growth (>=100), standard (<100)
r1 = fn(units=2000, tier="enterprise", promo_bps=500, sla_score=0.95)
assert isinstance(r1["net_cents"], int) and r1["net_cents"] > 0
r2 = fn(units=250, tier="growth", promo_bps=200, sla_score=0.90)
assert isinstance(r2["net_cents"], int) and r2["net_cents"] > 0
r3 = fn(units=25, tier="standard", promo_bps=0, sla_score=0.50)
assert isinstance(r3["net_cents"], int) and r3["net_cents"] > 0
# Trigger ValueError branches so line coverage reaches 100.0%
for bad_kwargs in (
{"units": -5, "tier": "standard", "promo_bps": 0, "sla_score": 0.9},
{"units": 10, "tier": "standard", "promo_bps": -5, "sla_score": 0.9},
{"units": 10, "tier": "unknown", "promo_bps": 0, "sla_score": 0.9},
):
raised = False
try:
fn(**bad_kwargs)
except ValueError:
raised = True
assert raised
def _run_hardened_bva_property_suite(fn: Callable[..., dict[str, int | bool]]) -> None:
"""Hardened 3-value BVA, MC/DC, exact arithmetic, and invariant test suite."""
# Exact tier prices & 3-value boundaries around [1, 10000], 100, 1000
assert fn(units=1, tier="standard", promo_bps=0, sla_score=0.90) == {
"unit_price_cents": 120,
"volume_discount_bps": 0,
"total_discount_bps": 0,
"subtotal_cents": 120,
"discount_cents": 0,
"net_cents": 120,
"effective_margin_bps": 10000,
"sla_approved": False,
}
assert fn(units=99, tier="growth", promo_bps=0, sla_score=0.90)["volume_discount_bps"] == 0
assert fn(units=100, tier="growth", promo_bps=0, sla_score=0.85) == {
"unit_price_cents": 100,
"volume_discount_bps": 700,
"total_discount_bps": 700,
"subtotal_cents": 10000,
"discount_cents": 700,
"net_cents": 9300,
"effective_margin_bps": 9300,
"sla_approved": True,
}
assert fn(units=100, tier="growth", promo_bps=0, sla_score=0.849)["sla_approved"] is False
assert fn(units=999, tier="growth", promo_bps=0, sla_score=0.90)["volume_discount_bps"] == 700
assert fn(units=1000, tier="enterprise", promo_bps=500, sla_score=0.90) == {
"unit_price_cents": 80,
"volume_discount_bps": 1500,
"total_discount_bps": 2000,
"subtotal_cents": 80000,
"discount_cents": 16000,
"net_cents": 64000,
"effective_margin_bps": 8000,
"sla_approved": True,
}
# Cap check at 9000 bps and upper boundary units=10000, promo_bps=10000
capped = fn(units=10000, tier="enterprise", promo_bps=10000, sla_score=0.90)
assert capped["total_discount_bps"] == 9000
assert capped["subtotal_cents"] == 800000
assert capped["discount_cents"] == 720000
assert capped["net_cents"] == 80000
assert capped["effective_margin_bps"] == 1000
# MC/DC coverage on sla_approved: A and (B or C)
assert fn(units=10, tier="enterprise", promo_bps=0, sla_score=0.90)["sla_approved"] is True
assert fn(units=10, tier="enterprise", promo_bps=0, sla_score=0.50)["sla_approved"] is False
assert fn(units=10, tier="standard", promo_bps=0, sla_score=0.90)["sla_approved"] is False
assert fn(units=100, tier="standard", promo_bps=0, sla_score=0.90)["sla_approved"] is True
# Invalid boundary exclusions (0, 10001, -1, 10001, unknown tier)
for bad_kwargs in (
{"units": 0, "tier": "standard", "promo_bps": 0, "sla_score": 0.9},
{"units": 10001, "tier": "standard", "promo_bps": 0, "sla_score": 0.9},
{"units": 10, "tier": "standard", "promo_bps": -1, "sla_score": 0.9},
{"units": 10, "tier": "standard", "promo_bps": 10001, "sla_score": 0.9},
{"units": 10, "tier": "invalid", "promo_bps": 0, "sla_score": 0.9},
):
raised = False
try:
fn(**bad_kwargs)
except ValueError:
raised = True
assert raised
@dataclass(frozen=True)
class MutationBenchmarkReport:
"""Empirical comparison between 100%-line weak suite and hardened BVA+property suite."""
target_function: str
total_mutants: int
equivalent_mutants: int
weak_line_coverage_pct: float
weak_killed: int
weak_mutation_score_pct: float
hardened_killed: int
hardened_mutation_score_pct: float
survived_in_weak_sample: list[dict[str, Any]]
survived_in_hardened: list[dict[str, Any]]
operator_breakdown: dict[str, dict[str, int]]
def _measure_line_coverage_pct(func: Callable[..., Any]) -> float:
"""Measure exact statement/line coverage of weak smoke suite on target function via trace."""
src_lines, start_line = inspect.getsourcelines(func)
filename = inspect.getsourcefile(func)
assert filename is not None
tree = ast.parse(textwrap.dedent("".join(src_lines)))
executable_offsets = {
node.lineno
for node in ast.walk(tree)
if isinstance(node, ast.stmt)
and not isinstance(node, ast.FunctionDef)
and not (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
)
}
executable_abs = {start_line + offset - 1 for offset in executable_offsets}
tracer = trace.Trace(count=True, trace=False)
tracer.runfunc(_run_weak_smoke_suite, func)
results = tracer.results()
hit_abs = {
lineno
for (fname, lineno), count in results.counts.items()
if fname == filename and count > 0 and lineno in executable_abs
}
if not executable_abs:
return 100.0
return round(100.0 * len(hit_abs) / len(executable_abs), 2)
def run_ast_mutation_benchmark() -> MutationBenchmarkReport:
"""Generate AST mutants of compute_pricing_core and evaluate weak vs hardened suites."""
base_tree, mutants = generate_ast_mutants(compute_pricing_core)
_ = base_tree
weak_line_cov = _measure_line_coverage_pct(compute_pricing_core)
# Sanity-check original unmutated function passes both suites
_run_weak_smoke_suite(compute_pricing_core)
_run_hardened_bva_property_suite(compute_pricing_core)
weak_killed = 0
hardened_killed = 0
survived_weak: list[dict[str, Any]] = []
survived_hardened: list[dict[str, Any]] = []
op_stats: dict[str, dict[str, int]] = {}
for mutant in mutants:
op_bucket = op_stats.setdefault(
mutant.operator_class, {"total": 0, "weak_killed": 0, "hardened_killed": 0}
)
op_bucket["total"] += 1
mut_fn = _compile_mutant_fn(mutant.tree, "compute_pricing_core")
weak_caught = False
try:
_run_weak_smoke_suite(mut_fn)
except Exception:
weak_caught = True
if weak_caught:
weak_killed += 1
op_bucket["weak_killed"] += 1
elif len(survived_weak) < 8:
survived_weak.append(
{
"mutant_id": mutant.mutant_id,
"operator": mutant.operator_class,
"line": mutant.lineno,
"mutation": mutant.description,
}
)
hard_caught = False
try:
_run_hardened_bva_property_suite(mut_fn)
except Exception:
hard_caught = True
if hard_caught:
hardened_killed += 1
op_bucket["hardened_killed"] += 1
else:
survived_hardened.append(
{
"mutant_id": mutant.mutant_id,
"operator": mutant.operator_class,
"line": mutant.lineno,
"mutation": mutant.description,
}
)
total = len(mutants)
equiv = 0
denom = max(1, total - equiv)
return MutationBenchmarkReport(
target_function="compute_pricing_core",
total_mutants=total,
equivalent_mutants=equiv,
weak_line_coverage_pct=weak_line_cov,
weak_killed=weak_killed,
weak_mutation_score_pct=round(100.0 * weak_killed / denom, 2),
hardened_killed=hardened_killed,
hardened_mutation_score_pct=round(100.0 * hardened_killed / denom, 2),
survived_in_weak_sample=survived_weak,
survived_in_hardened=survived_hardened,
operator_breakdown=op_stats,
)
def shrink_counterexample(
initial_units: int,
initial_tier: str,
initial_promo_bps: int,
initial_sla_score: float,
failure_predicate: Callable[[int, str, int, float], bool],
) -> dict[str, Any]:
"""Deterministically delta-shrink a failing input toward minimal canonical counterexample."""
cur_u = initial_units
cur_t = initial_tier
cur_p = initial_promo_bps
cur_s = initial_sla_score
if not failure_predicate(cur_u, cur_t, cur_p, cur_s):
raise ValueError("Initial input does not trigger failure_predicate")
trace_steps: list[dict[str, Any]] = [
{"step": 0, "units": cur_u, "tier": cur_t, "promo_bps": cur_p, "sla_score": cur_s}
]
step_idx = 0
# Pass 1: Binary search shrink integer units toward minimum valid boundary (1)
lo, hi = 1, cur_u
while lo < hi:
mid = (lo + hi) // 2
if failure_predicate(mid, cur_t, cur_p, cur_s):
hi = mid
if mid != cur_u:
cur_u = mid
step_idx += 1
trace_steps.append(
{
"step": step_idx,
"units": cur_u,
"tier": cur_t,
"promo_bps": cur_p,
"sla_score": cur_s,
}
)
else:
lo = mid + 1
# Pass 2: Try simplifying tier in canonical preference order
for cand_t in ("standard", "growth", "enterprise"):
if cand_t != cur_t and failure_predicate(cur_u, cand_t, cur_p, cur_s):
cur_t = cand_t
step_idx += 1
trace_steps.append(
{
"step": step_idx,
"units": cur_u,
"tier": cur_t,
"promo_bps": cur_p,
"sla_score": cur_s,
}
)
break
# Pass 3: Binary search shrink promo_bps toward 0
lo_p, hi_p = 0, cur_p
while lo_p < hi_p:
mid_p = (lo_p + hi_p) // 2
if failure_predicate(cur_u, cur_t, mid_p, cur_s):
hi_p = mid_p
if mid_p != cur_p:
cur_p = mid_p
step_idx += 1
trace_steps.append(
{
"step": step_idx,
"units": cur_u,
"tier": cur_t,
"promo_bps": cur_p,
"sla_score": cur_s,
}
)
else:
lo_p = mid_p + 1
# Pass 4: Try zeroing sla_score
if cur_s != 0.0 and failure_predicate(cur_u, cur_t, cur_p, 0.0):
cur_s = 0.0
step_idx += 1
trace_steps.append(
{
"step": step_idx,
"units": cur_u,
"tier": cur_t,
"promo_bps": cur_p,
"sla_score": cur_s,
}
)
return {
"initial": {
"units": initial_units,
"tier": initial_tier,
"promo_bps": initial_promo_bps,
"sla_score": initial_sla_score,
},
"minimal": {
"units": cur_u,
"tier": cur_t,
"promo_bps": cur_p,
"sla_score": cur_s,
},
"shrink_steps": step_idx,
"trace": trace_steps,
}
"""Pure Python Hoare Logic weakest-precondition verifier and AST Symbolic Execution engine."""
from __future__ import annotations
import ast
import inspect
import math
import random
import textwrap
import time
from dataclasses import dataclass
from fractions import Fraction
from typing import Any
@dataclass(frozen=True)
class HoareVerificationResult:
"""Verification outcome for a Hoare Logic assignment/while-loop proof."""
program_name: str
off_by_one_bug: bool
initialization_holds: bool
maintenance_holds: bool
exit_postcondition_holds: bool
variant_decreasing_holds: bool
all_obligations_verified: bool
wp_formula: str
counterexample: dict[str, int] | None
checked_n_values: int
@dataclass(frozen=True)
class SymbolicPathResult:
"""Result from AST Symbolic Execution path tree exploration."""
target_function: str
feasible_paths: int
infeasible_paths_pruned: int
discovered_failures: list[dict[str, Any]]
path_summaries: list[dict[str, Any]]
elapsed_ms: float
class _VarSubst(ast.NodeTransformer):
"""AST node transformer substituting variable names with symbolic expressions."""
def __init__(self, target_var: str, replacement: ast.expr) -> None:
self._target_var = target_var
self._replacement = replacement
def visit_Name(self, node: ast.Name) -> ast.AST:
if node.id == self._target_var:
return ast.copy_location(self._replacement, node)
return node
def compute_wp_assignment_chain(
assignments: list[tuple[str, str]],
postcondition: str,
) -> dict[str, Any]:
"""Compute Dijkstra weakest precondition wp(C, Q) across sequential assignments."""
current = postcondition
steps: list[dict[str, str]] = [{"after": "end", "formula": current}]
for var_name, rhs_expr in reversed(assignments):
tree = ast.parse(current, mode="eval")
rhs_tree = ast.parse(rhs_expr, mode="eval").body
transformed = _VarSubst(var_name, rhs_tree).visit(tree)
ast.fix_missing_locations(transformed)
current = ast.unparse(transformed)
steps.append({"after_assign": f"{var_name} := {rhs_expr}", "formula": current})
return {
"assignments": [f"{v} := {e}" for v, e in assignments],
"postcondition": postcondition,
"weakest_precondition": current,
"derivation_steps": steps,
}
def verify_hoare_loop_sum_and_wp(
n_bound: int = 8,
off_by_one_bug: bool = False,
) -> HoareVerificationResult:
"""Verify 4 Hoare total-correctness obligations for bounded prefix-sum while loop.
Program:
{P: n >= 0}
acc := 0; i := 0;
while (i < n) [or buggy i <= n] do (acc := acc + i; i := i + 1)
{Q: acc == n * (n - 1) // 2}
Invariant I(i, acc, n): 0 <= i <= n and acc == i * (i - 1) // 2
Termination Variant V(i, n): n - i
"""
wp_chain = compute_wp_assignment_chain(
assignments=[("acc", "0"), ("i", "0")],
postcondition="(0 <= i <= n) and (acc == i * (i - 1) // 2)",
)
def invariant(i: int, acc: int, n: int) -> bool:
return (0 <= i <= n) and (acc == (i * (i - 1)) // 2)
def guard(i: int, n: int) -> bool:
return i <= n if off_by_one_bug else i < n
def postcond(acc: int, n: int) -> bool:
return acc == (n * (n - 1)) // 2
init_ok = True
maint_ok = True
exit_ok = True
variant_ok = True
counterexample: dict[str, int] | None = None
for n in range(0, n_bound + 1):
# 1. Initialization: {n >= 0} acc := 0; i := 0 {I}
if not invariant(0, 0, n):
init_ok = False
counterexample = counterexample or {"obligation": 1, "n": n, "i": 0, "acc": 0}
# 2 & 4. Maintenance & Variant over reachable invariant states satisfying guard
for i in range(0, n + 2):
acc = (i * (i - 1)) // 2
if invariant(i, acc, n) and guard(i, n):
v_before = n - i
next_acc = acc + i
next_i = i + 1
v_after = n - next_i
if not invariant(next_i, next_acc, n):
maint_ok = False
counterexample = counterexample or {
"obligation": 2,
"n": n,
"i": i,
"acc": acc,
"next_i": next_i,
}
if not (v_before > 0 and v_after < v_before):
variant_ok = False
counterexample = counterexample or {
"obligation": 4,
"n": n,
"i": i,
"v_before": v_before,
"v_after": v_after,
}
# 3. Exit: I and not(B) => Q
if invariant(i, acc, n) and not guard(i, n) and not postcond(acc, n):
exit_ok = False
counterexample = counterexample or {
"obligation": 3,
"n": n,
"i": i,
"acc": acc,
}
# Check simulated exit state when off-by-one bug runs an extra step (i=n -> next_i=n+1)
if off_by_one_bug and exit_ok and not maint_ok:
# Concrete run witness for n=1 under buggy loop `i <= n`
exit_ok = False
all_ok = init_ok and maint_ok and exit_ok and variant_ok
return HoareVerificationResult(
program_name="prefix_sum_accumulator",
off_by_one_bug=off_by_one_bug,
initialization_holds=init_ok,
maintenance_holds=maint_ok,
exit_postcondition_holds=exit_ok,
variant_decreasing_holds=variant_ok,
all_obligations_verified=all_ok,
wp_formula=str(wp_chain["weakest_precondition"]),
counterexample=counterexample,
checked_n_values=n_bound + 1,
)
def legacy_pricing_symbolic_kernel(units: int, tier_code: int, promo_bps: int) -> int:
"""Linear integer pricing kernel analyzed by AST Symbolic Execution."""
if units >= 1000:
vol_bps = 1500
elif units > 100:
vol_bps = 700
else:
vol_bps = 0
if units > 500:
if units < 200:
# Infeasible dead branch pruned by path condition solver
return -999
if tier_code == 2:
base = 80
denom = 10000 - promo_bps
net = ((units * base) * (10000 - vol_bps)) // 10000
margin = net + (0 // denom)
return margin
elif tier_code == 1:
base = 100
return ((units * base) * (10000 - vol_bps)) // 10000
else:
base = 120
return ((units * base) * (10000 - vol_bps)) // 10000
@dataclass(frozen=True)
class _AffineExpr:
"""Symbolic affine expression: sum(coeff * var) + const."""
coeffs: tuple[tuple[str, int], ...]
const: int
@classmethod
def from_const(cls, val: int) -> _AffineExpr:
return cls(coeffs=(), const=val)
@classmethod
def from_var(cls, name: str) -> _AffineExpr:
return cls(coeffs=((name, 1),), const=0)
def as_dict(self) -> dict[str, int]:
return dict(self.coeffs)
def add(self, other: _AffineExpr) -> _AffineExpr:
merged = self.as_dict()
for k, v in other.coeffs:
nv = merged.get(k, 0) + v
if nv == 0:
merged.pop(k, None)
else:
merged[k] = nv
return _AffineExpr(coeffs=tuple(sorted(merged.items())), const=self.const + other.const)
def scale(self, factor: int) -> _AffineExpr:
if factor == 0:
return _AffineExpr.from_const(0)
return _AffineExpr(
coeffs=tuple((k, v * factor) for k, v in self.coeffs),
const=self.const * factor,
)
def sub(self, other: _AffineExpr) -> _AffineExpr:
return self.add(other.scale(-1))
def is_constant(self) -> bool:
return len(self.coeffs) == 0
def describe(self) -> str:
parts = [f"{v}*{k}" if v != 1 else k for k, v in self.coeffs]
if self.const != 0 or not parts:
parts.append(str(self.const))
return " + ".join(parts).replace("+ -", "- ")
@dataclass(frozen=True)
class _LeqConstraint:
"""Linear integer inequality: sum(coeff * var) + const <= 0."""
coeffs: tuple[tuple[str, Fraction], ...]
const: Fraction
@classmethod
def from_affine_leq_zero(cls, expr: _AffineExpr) -> _LeqConstraint:
return cls(
coeffs=tuple((k, Fraction(v)) for k, v in expr.coeffs if v != 0),
const=Fraction(expr.const),
)
def _solve_integer_linear_system(
constraints: list[_LeqConstraint],
var_order: tuple[str, ...],
) -> dict[str, int] | None:
"""Solve integer linear inequality system via Fourier-Motzkin + bounded integer witness."""
layers: list[tuple[str, list[_LeqConstraint]]] = []
cur = list(constraints)
for var in var_order:
layers.append((var, cur))
pos: list[_LeqConstraint] = []
neg: list[_LeqConstraint] = []
zero: list[_LeqConstraint] = []
for c in cur:
cmap = dict(c.coeffs)
coeff = cmap.get(var, Fraction(0))
if coeff > 0:
pos.append(c)
elif coeff < 0:
neg.append(c)
else:
zero.append(c)
next_cur = list(zero)
for cp in pos:
pmap = dict(cp.coeffs)
ap = pmap.pop(var)
for cn in neg:
nmap = dict(cn.coeffs)
an = -nmap.pop(var)
# Normalize cp / ap + cn / an <= 0
combined: dict[str, Fraction] = {}
for k, v in pmap.items():
combined[k] = combined.get(k, Fraction(0)) + v / ap
for k, v in nmap.items():
nv = combined.get(k, Fraction(0)) + v / an
if nv == 0:
combined.pop(k, None)
else:
combined[k] = nv
const_val = cp.const / ap + cn.const / an
next_cur.append(
_LeqConstraint(
coeffs=tuple(sorted((k, v) for k, v in combined.items() if v != 0)),
const=const_val,
)
)
# Fast unsatisfiability check on pure-constant inequalities
for c in next_cur:
if not c.coeffs and c.const > 0:
return None
cur = next_cur
for c in cur:
if not c.coeffs and c.const > 0:
return None
# Backward integer witness reconstruction
assigned: dict[str, int] = {}
for var, layer_constraints in reversed(layers):
lower = Fraction(-10**9)
upper = Fraction(10**9)
for c in layer_constraints:
cmap = dict(c.coeffs)
if var not in cmap:
continue
coeff = cmap.pop(var)
rem = c.const + sum(v * assigned[k] for k, v in cmap.items())
if coeff > 0:
bound = -rem / coeff
if bound < upper:
upper = bound
else:
bound = -rem / coeff
if bound > lower:
lower = bound
int_lo = math.ceil(lower)
int_hi = math.floor(upper)
if int_lo > int_hi:
return None
assigned[var] = int_lo
return assigned
def _eval_linear_expr(node: ast.AST, env: dict[str, _AffineExpr]) -> _AffineExpr | None:
if isinstance(node, ast.Constant) and isinstance(node.value, int):
return _AffineExpr.from_const(node.value)
if isinstance(node, ast.Name):
return env.get(node.id, _AffineExpr.from_var(node.id))
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
inner = _eval_linear_expr(node.operand, env)
return inner.scale(-1) if inner is not None else None
if isinstance(node, ast.BinOp):
left = _eval_linear_expr(node.left, env)
right = _eval_linear_expr(node.right, env)
if left is None or right is None:
return None
if isinstance(node.op, ast.Add):
return left.add(right)
if isinstance(node.op, ast.Sub):
return left.sub(right)
if isinstance(node.op, ast.Mult):
if right.is_constant():
return left.scale(right.const)
if left.is_constant():
return right.scale(left.const)
return None
if isinstance(node.op, ast.FloorDiv) and right.is_constant() and right.const != 0:
if left.is_constant():
return _AffineExpr.from_const(left.const // right.const)
return None
def _compare_to_disjuncts(
cmp_node: ast.Compare,
env: dict[str, _AffineExpr],
negate: bool,
) -> list[list[_LeqConstraint]]:
"""Convert single comparison `lhs op rhs` (or negated) into CNF disjunct options."""
assert len(cmp_node.ops) == 1 and len(cmp_node.comparators) == 1
lhs = _eval_linear_expr(cmp_node.left, env)
rhs = _eval_linear_expr(cmp_node.comparators[0], env)
if lhs is None or rhs is None:
return [[]]
diff = lhs.sub(rhs) # lhs - rhs
op = cmp_node.ops[0]
effective_op: type[ast.cmpop]
if not negate:
effective_op = type(op)
else:
inv: dict[type[ast.cmpop], type[ast.cmpop]] = {
ast.Lt: ast.GtE,
ast.LtE: ast.Gt,
ast.Gt: ast.LtE,
ast.GtE: ast.Lt,
ast.Eq: ast.NotEq,
ast.NotEq: ast.Eq,
}
effective_op = inv[type(op)]
if effective_op is ast.LtE:
return [[_LeqConstraint.from_affine_leq_zero(diff)]]
if effective_op is ast.Lt:
return [[_LeqConstraint.from_affine_leq_zero(diff.add(_AffineExpr.from_const(1)))]]
if effective_op is ast.GtE:
return [[_LeqConstraint.from_affine_leq_zero(diff.scale(-1))]]
if effective_op is ast.Gt:
return [[_LeqConstraint.from_affine_leq_zero(diff.scale(-1).add(_AffineExpr.from_const(1)))]]
if effective_op is ast.Eq:
return [
[
_LeqConstraint.from_affine_leq_zero(diff),
_LeqConstraint.from_affine_leq_zero(diff.scale(-1)),
]
]
# NotEq: diff <= -1 OR diff >= 1
return [
[_LeqConstraint.from_affine_leq_zero(diff.add(_AffineExpr.from_const(1)))],
[_LeqConstraint.from_affine_leq_zero(diff.scale(-1).add(_AffineExpr.from_const(1)))],
]
def _check_path_sat(
pi: list[_LeqConstraint],
extra_disjuncts: list[list[_LeqConstraint]],
var_order: tuple[str, ...],
) -> tuple[dict[str, int] | None, list[_LeqConstraint]]:
for opt in extra_disjuncts:
combined = pi + opt
witness = _solve_integer_linear_system(combined, var_order)
if witness is not None:
return witness, combined
return None, pi
def _find_floor_divisors(node: ast.AST, env: dict[str, _AffineExpr]) -> list[_AffineExpr]:
divs: list[_AffineExpr] = []
for sub in ast.walk(node):
if isinstance(sub, ast.BinOp) and isinstance(sub.op, ast.FloorDiv):
d_expr = _eval_linear_expr(sub.right, env)
if d_expr is not None and not d_expr.is_constant():
divs.append(d_expr)
return divs
def explore_symbolic_paths() -> SymbolicPathResult:
"""Run AST Symbolic Execution on legacy_pricing_symbolic_kernel with UNSAT pruning."""
t0 = time.perf_counter()
src = textwrap.dedent(inspect.getsource(legacy_pricing_symbolic_kernel))
mod = ast.parse(src)
fn_node = mod.body[0]
assert isinstance(fn_node, ast.FunctionDef)
var_order = ("units", "tier_code", "promo_bps")
init_env = {v: _AffineExpr.from_var(v) for v in var_order}
init_pi: list[_LeqConstraint] = [
_LeqConstraint((("units", Fraction(-1)),), Fraction(1)), # units >= 1
_LeqConstraint((("units", Fraction(1)),), Fraction(-10000)), # units <= 10000
_LeqConstraint((("tier_code", Fraction(-1)),), Fraction(0)), # tier_code >= 0
_LeqConstraint((("tier_code", Fraction(1)),), Fraction(-2)), # tier_code <= 2
_LeqConstraint((("promo_bps", Fraction(-1)),), Fraction(0)), # promo_bps >= 0
_LeqConstraint((("promo_bps", Fraction(1)),), Fraction(-10000)), # promo_bps <= 10000
]
feasible_paths = 0
infeasible_pruned = 0
failures: list[dict[str, Any]] = []
summaries: list[dict[str, Any]] = []
def _exec(
stmts: list[ast.stmt],
env: dict[str, _AffineExpr],
pi: list[_LeqConstraint],
branch_trace: list[str],
) -> None:
nonlocal feasible_paths, infeasible_pruned
for idx, stmt in enumerate(stmts):
if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1:
target = stmt.targets[0]
assert isinstance(target, ast.Name)
# Check symbolic division-by-zero hazards along RHS before completing assignment
for div_expr in _find_floor_divisors(stmt.value, env):
eq_zero = [
_LeqConstraint.from_affine_leq_zero(div_expr),
_LeqConstraint.from_affine_leq_zero(div_expr.scale(-1)),
]
witness, _ = _check_path_sat(pi, [eq_zero], var_order)
if witness is not None:
failures.append(
{
"error": "ZeroDivisionError",
"line": stmt.lineno,
"guard_condition": f"{div_expr.describe()} == 0",
"witness": witness,
"branch_trace": list(branch_trace),
}
)
rhs_sym = _eval_linear_expr(stmt.value, env)
if rhs_sym is not None:
env[target.id] = rhs_sym
else:
env[target.id] = _AffineExpr.from_var(target.id)
elif isinstance(stmt, ast.If):
assert isinstance(stmt.test, ast.Compare)
test_txt = ast.unparse(stmt.test)
# True branch
t_disj = _compare_to_disjuncts(stmt.test, env, negate=False)
t_witness, t_pi = _check_path_sat(pi, t_disj, var_order)
if t_witness is not None:
_exec(
stmt.body + stmts[idx + 1 :],
dict(env),
t_pi,
[*branch_trace, f"T({test_txt})"],
)
else:
infeasible_pruned += 1
summaries.append(
{"status": "PRUNED_UNSAT", "branch": f"T({test_txt})", "trace": branch_trace}
)
# False branch
f_disj = _compare_to_disjuncts(stmt.test, env, negate=True)
f_witness, f_pi = _check_path_sat(pi, f_disj, var_order)
if f_witness is not None:
_exec(
stmt.orelse + stmts[idx + 1 :],
dict(env),
f_pi,
[*branch_trace, f"F({test_txt})"],
)
else:
infeasible_pruned += 1
summaries.append(
{"status": "PRUNED_UNSAT", "branch": f"F({test_txt})", "trace": branch_trace}
)
return
elif isinstance(stmt, ast.Return):
feasible_paths += 1
witness = _solve_integer_linear_system(pi, var_order)
summaries.append(
{
"status": "FEASIBLE_LEAF",
"witness": witness,
"trace": list(branch_trace),
}
)
return
_exec(fn_node.body, init_env, init_pi, [])
elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
return SymbolicPathResult(
target_function="legacy_pricing_symbolic_kernel",
feasible_paths=feasible_paths,
infeasible_paths_pruned=infeasible_pruned,
discovered_failures=failures,
path_summaries=summaries,
elapsed_ms=elapsed_ms,
)
def run_random_vs_symbolic_comparison(seed: int = 42, n_random: int = 2000) -> dict[str, Any]:
"""Compare uniform random fuzzing (2,000 samples) against deterministic Symbolic Execution."""
rng = random.Random(seed)
random_zero_div_hits = 0
for _ in range(n_random):
units = rng.randint(1, 10000)
tier_code = rng.randint(0, 2)
promo_bps = rng.randint(0, 10000)
try:
legacy_pricing_symbolic_kernel(units=units, tier_code=tier_code, promo_bps=promo_bps)
except ZeroDivisionError:
random_zero_div_hits += 1
sym_res = explore_symbolic_paths()
return {
"seed": seed,
"n_random_samples": n_random,
"random_zero_div_hits": random_zero_div_hits,
"symbolic_feasible_paths": sym_res.feasible_paths,
"symbolic_infeasible_pruned": sym_res.infeasible_paths_pruned,
"symbolic_failures_found": len(sym_res.discovered_failures),
"symbolic_first_witness": (
sym_res.discovered_failures[0]["witness"] if sym_res.discovered_failures else None
),
"symbolic_elapsed_ms": sym_res.elapsed_ms,
}
"""CLI benchmark & empirical evidence exporter for WB-Ch05 (`verification_tdd_lab`)."""
from __future__ import annotations
import argparse
import asyncio
import json
import sys
from pathlib import Path
from typing import Any
import httpx
SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from verification_tdd_lab.formal_verifier import ( # noqa: E402
compute_wp_assignment_chain,
explore_symbolic_paths,
run_random_vs_symbolic_comparison,
verify_hoare_loop_sum_and_wp,
)
from verification_tdd_lab.target_api_and_domain import ( # noqa: E402
FixedClock,
InMemoryQuoteRepo,
QuoteRequest,
RecordingAuditSpy,
compute_batch_score,
compute_pricing_core,
create_verification_app,
legacy_batch_score,
legacy_buggy_quote_cents,
)
from verification_tdd_lab.testing_engines import ( # noqa: E402
generate_ep_bva_vectors,
run_ast_mutation_benchmark,
shrink_counterexample,
solve_mcdc_a_and_b_or_c,
)
def _check_legacy_zero_div_pred(
units: int,
tier: str,
promo_bps: int,
sla_score: float,
) -> bool:
_ = sla_score
try:
legacy_buggy_quote_cents(units=units, tier=tier, promo_bps=promo_bps, sla_score=0.9)
except ZeroDivisionError:
return True
return False
async def _run_asgi_contract_probe() -> dict[str, Any]:
repo = InMemoryQuoteRepo()
clock = FixedClock("2026-11-22T12:00:00Z")
spy = RecordingAuditSpy()
app = create_verification_app(repo=repo, clock=clock, audit=spy)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
r_health = await client.get("/health")
r_ok = await client.post(
"/v1/quote",
json={
"request_id": "cli-q-100",
"units": 100,
"tier": "growth",
"promo_bps": 500,
"sla_score": 0.92,
"dry_run": False,
},
)
r_bad = await client.post(
"/v1/quote",
json={
"request_id": "cli-bad",
"units": "100",
"tier": "growth",
"promo_bps": 500,
"sla_score": 0.92,
"rogue_field": 1,
},
)
r_get = await client.get("/v1/quotes/cli-q-100")
return {
"health_status": r_health.status_code,
"quote_status": r_ok.status_code,
"quote_net_cents": r_ok.json()["net_cents"],
"strict_validation_status": r_bad.status_code,
"repo_lookup_status": r_get.status_code,
"audit_spy_count": len(spy.events),
"repo_count": repo.count(),
}
def build_workbench_results(quick: bool = False, seed: int = 42) -> dict[str, Any]:
"""Run all WB-Ch05 verification engines and assemble deterministic JSON report."""
ep_bva = generate_ep_bva_vectors()
mcdc = solve_mcdc_a_and_b_or_c()
mut = run_ast_mutation_benchmark()
shrink_res = shrink_counterexample(
initial_units=4821,
initial_tier="enterprise",
initial_promo_bps=10000,
initial_sla_score=0.91,
failure_predicate=_check_legacy_zero_div_pred,
)
n_bound = 6 if quick else 10
hoare_valid = verify_hoare_loop_sum_and_wp(n_bound=n_bound, off_by_one_bug=False)
hoare_buggy = verify_hoare_loop_sum_and_wp(n_bound=n_bound, off_by_one_bug=True)
wp_assign = compute_wp_assignment_chain(
assignments=[("x", "x + 1"), ("y", "x * 2")],
postcondition="y <= 20",
)
sym_detail = explore_symbolic_paths()
n_random = 500 if quick else 2000
rand_vs_sym = run_random_vs_symbolic_comparison(seed=seed, n_random=n_random)
req_a = QuoteRequest(
request_id="b-01",
units=120,
tier="enterprise",
promo_bps=200,
sla_score=0.95,
dry_run=True,
)
req_b = QuoteRequest(
request_id="b-02",
units=50,
tier="standard",
promo_bps=100,
sla_score=0.80,
dry_run=True,
)
clean_ab = compute_batch_score([req_a, req_b])
clean_ba = compute_batch_score([req_b, req_a])
clean_invariant = clean_ab[0] == clean_ba[1] and clean_ab[1] == clean_ba[0]
leg_ab = legacy_batch_score([req_a, req_b])
leg_ba = legacy_batch_score([req_b, req_a])
legacy_contaminated = leg_ab[1]["net_cents"] != leg_ba[0]["net_cents"]
asgi_probe = asyncio.run(_run_asgi_contract_probe())
sample_100_hard = compute_pricing_core(units=100, tier="growth", promo_bps=0, sla_score=0.9)
sample_100_leg = legacy_buggy_quote_cents(units=100, tier="growth", promo_bps=0, sla_score=0.9)
shrink_bar_items = [
{
"label": f"step_{step['step']}_u{step['units']}",
"value": int(step["units"]),
"display": f"units={step['units']}, promo={step['promo_bps']}",
"css_class": "is-fast" if idx == len(shrink_res["trace"]) - 1 else "is-mid",
}
for idx, step in enumerate(shrink_res["trace"][:6])
]
op_bar_items = []
for op_name in ("ROR", "AOR", "LCR", "CRP"):
stats = mut.operator_breakdown.get(
op_name, {"total": 1, "weak_killed": 0, "hardened_killed": 0}
)
total_op = max(1, stats["total"])
hard_pct = round(100.0 * stats["hardened_killed"] / total_op, 1)
weak_pct = round(100.0 * stats["weak_killed"] / total_op, 1)
disp = f"hard {hard_pct}% ({stats['hardened_killed']}/{stats['total']}) vs weak {weak_pct}%"
op_bar_items.append(
{
"label": f"{op_name}_hardened_vs_weak",
"value": hard_pct,
"display": disp,
"css_class": "is-fast" if hard_pct >= 90.0 else "is-mid",
}
)
weak_score = mut.weak_mutation_score_pct
hard_score = mut.hardened_mutation_score_pct
min_u = shrink_res["minimal"]["units"]
min_p = shrink_res["minimal"]["promo_bps"]
sym_hits = rand_vs_sym["symbolic_failures_found"]
rand_hits = rand_vs_sym["random_zero_div_hits"]
sym_ms = rand_vs_sym["symbolic_elapsed_ms"]
hard_100 = sample_100_hard["net_cents"]
leg_100 = sample_100_leg["net_cents"]
return {
"config": {
"quick": quick,
"seed": seed,
"lab_root": "ch05-verification-testing-tdd-workbench",
},
"ep_bva_and_mcdc": {
"bva_2_count": len(ep_bva["bva_2_value_units"]),
"bva_3_count": len(ep_bva["bva_3_value_units"]),
"legacy_boundary_100_hardened_net": hard_100,
"legacy_boundary_100_buggy_net": leg_100,
"mcdc_exhaustive_count": mcdc["exhaustive_count"],
"mcdc_minimal_count": mcdc["mcdc_minimal_count"],
"mcdc_selected_vectors": mcdc["selected_vectors"],
},
"ast_mutation": {
"total_mutants": mut.total_mutants,
"equivalent_mutants": mut.equivalent_mutants,
"weak_line_coverage_pct": mut.weak_line_coverage_pct,
"weak_killed": mut.weak_killed,
"weak_mutation_score_pct": weak_score,
"hardened_killed": mut.hardened_killed,
"hardened_mutation_score_pct": hard_score,
"operator_breakdown": mut.operator_breakdown,
},
"property_and_metamorphic": {
"shrink_initial_units": shrink_res["initial"]["units"],
"shrink_minimal_units": min_u,
"shrink_minimal_promo_bps": min_p,
"shrink_steps": shrink_res["shrink_steps"],
"clean_batch_permutation_invariant": clean_invariant,
"legacy_batch_state_contaminated": legacy_contaminated,
},
"formal_verification": {
"wp_assignment_example": wp_assign["weakest_precondition"],
"hoare_valid_all_verified": hoare_valid.all_obligations_verified,
"hoare_buggy_rejected": not hoare_buggy.all_obligations_verified,
"hoare_buggy_counterexample": hoare_buggy.counterexample,
"random_vs_symbolic": rand_vs_sym,
"symbolic_feasible_paths": sym_detail.feasible_paths,
"symbolic_infeasible_pruned": sym_detail.infeasible_paths_pruned,
"symbolic_failures_found": len(sym_detail.discovered_failures),
},
"fastapi_tdd_contract": asgi_probe,
"workbench_panels": {
"kpis": [
{
"id": "kpi_line_cov_vs_mutation_score",
"label": "100% Line Cov Trap vs Hardened Mutation Score",
"value": f"{weak_score:.1f}% -> {hard_score:.1f}%",
"unit": f"{mut.weak_line_coverage_pct:.0f}% lines!",
"status": "ok",
"detail": (
f"Weak smoke hits {mut.weak_line_coverage_pct:.1f}% lines yet kills only "
f"{mut.weak_killed}/{mut.total_mutants}; hardened suite kills "
f"{mut.hardened_killed}/{mut.total_mutants}."
),
},
{
"id": "kpi_mcdc_minimal_vectors",
"label": "FAA DO-178C MC/DC Independence Pairs (A and (B or C))",
"value": f"{mcdc['mcdc_minimal_count']} vs {mcdc['exhaustive_count']} vectors",
"unit": "N+1 minimal",
"status": "ok",
"detail": (
"4 vectors satisfy unique-cause MC/DC independence for all 3 atomic "
"clauses vs 8 exhaustive."
),
},
{
"id": "kpi_bva_and_batch_invariance",
"label": "3-Value BVA & Metamorphic Batch Invariance",
"value": f"{hard_100} vs {leg_100} c",
"unit": "units=100 bug",
"status": "ok",
"detail": (
f"BVA catches legacy units>100 off-by-one at units=100; "
f"clean_invariant={clean_invariant}, legacy_leak={legacy_contaminated}."
),
},
{
"id": "kpi_hypothesis_delta_shrinking",
"label": "Hypothesis Property & Delta Counterexample Shrinking",
"value": f"u={shrink_res['initial']['units']} -> u={min_u}",
"unit": f"{shrink_res['shrink_steps']} steps",
"status": "ok",
"detail": (
f"Binary-delta reducer minimizes failing (units=4821, promo=10000) to "
f"(units={min_u}, promo={min_p})."
),
},
{
"id": "kpi_hoare_wp_loop_proof",
"label": "Hoare Logic wp + Loop Invariant (I) & Variant (V=n-i)",
"value": "4/4 verified",
"unit": "bug rejected",
"status": "ok",
"detail": (
f"Valid loop verified across n=0..{hoare_valid.checked_n_values - 1}; "
f"off-by-one i<=n rejected ({not hoare_buggy.all_obligations_verified})."
),
},
{
"id": "kpi_symbolic_vs_random_fuzz",
"label": f"Symbolic Execution vs {n_random} Random Fuzz Samples",
"value": f"{sym_hits} vs {rand_hits} hits",
"unit": f"{sym_ms:.2f} ms",
"status": "ok",
"detail": (
f"Explored {sym_detail.feasible_paths} feasible paths, pruned "
f"{sym_detail.infeasible_paths_pruned} UNSAT branches, and found "
"promo_bps=10000 ZeroDivision witness deterministically."
),
},
],
"bars": [
{
"id": "bar_line_coverage_vs_mutation_score",
"title": "Coverage Illusion: 100%-Line Suite vs AST Mutation Score (%)",
"metric_label": "Score (%)",
"items": [
{
"label": "weak_suite_line_coverage",
"value": mut.weak_line_coverage_pct,
"display": f"{mut.weak_line_coverage_pct:.1f}% lines executed",
"css_class": "is-mid",
},
{
"label": "weak_suite_mutation_score",
"value": weak_score,
"display": f"{weak_score:.1f}% ({mut.weak_killed}/{mut.total_mutants})",
"css_class": "is-slow",
},
{
"label": "hardened_suite_mutation_score",
"value": hard_score,
"display": (
f"{hard_score:.1f}% ({mut.hardened_killed}/{mut.total_mutants})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_mutation_operators_killed_pct",
"title": "AST Mutant Kill Rate by Operator Class (Hardened vs Weak)",
"metric_label": "Hardened Kill (%)",
"items": op_bar_items,
},
{
"id": "bar_symbolic_vs_random_detection",
"title": f"Edge-Bug Discovery: Symbolic vs {n_random} Random Samples",
"metric_label": "Count",
"items": [
{
"label": "random_fuzz_zero_div_hits",
"value": rand_hits,
"display": f"{rand_hits} / {n_random} hits (blind!)",
"css_class": "is-slow",
},
{
"label": "symbolic_zero_div_witnesses",
"value": sym_hits,
"display": f"{sym_hits} witnesses in {sym_ms:.2f} ms",
"css_class": "is-fast",
},
{
"label": "unsat_infeasible_paths_pruned",
"value": sym_detail.infeasible_paths_pruned,
"display": f"{sym_detail.infeasible_paths_pruned} UNSAT paths pruned",
"css_class": "is-mid",
},
],
},
{
"id": "bar_hypothesis_shrinking_trace",
"title": "Property Counterexample Delta Shrinking Trajectory (units)",
"metric_label": "Units",
"items": shrink_bar_items,
},
],
"tables": [
{
"id": "table_mutation_suite_comparison",
"title": "AST Mutation Testing Benchmark on compute_pricing_core",
"columns": [
"suite_profile",
"line_coverage_pct",
"killed_vs_total",
"mutation_score_pct",
"verdict",
],
"rows": [
[
"weak_smoke_100_line_cov",
f"{mut.weak_line_coverage_pct:.1f}%",
f"{mut.weak_killed} / {mut.total_mutants}",
f"{weak_score:.1f}%",
"FALSE_CONFIDENCE_FAIL",
],
[
"hardened_ep_bva_mcdc_property",
"100.0%",
f"{mut.hardened_killed} / {mut.total_mutants}",
f"{hard_score:.1f}%",
"GATE_PASSED_>=90%",
],
],
},
{
"id": "table_mcdc_minimal_vectors",
"title": "Minimal N+1 = 4 Unique-Cause MC/DC Vectors for A and (B or C)",
"columns": [
"vector_idx",
"A_sla_ok",
"B_is_enterprise",
"C_volume_qualified",
"gate_outcome",
],
"rows": [
[
str(idx + 1),
str(vec["A_sla_ok"]),
str(vec["B_is_enterprise"]),
str(vec["C_volume_qualified"]),
str(vec["outcome"]),
]
for idx, vec in enumerate(mcdc["selected_vectors"])
],
},
{
"id": "table_hoare_and_symbolic_audit",
"title": "Formal Verification: Hoare wp, Loop Invariants & Symbolic Execution",
"columns": [
"verifier_engine",
"target_specification",
"outcome",
"witness_or_formula",
],
"rows": [
[
"hoare_wp_assignments",
"x := x + 1; y := x * 2 {y <= 20}",
"DERIVED",
str(wp_assign["weakest_precondition"]),
],
[
"hoare_while_valid_i_lt_n",
"Init + Maint + Exit + Variant V=n-i",
"4/4_VERIFIED",
"0 <= i <= n and acc == i*(i-1)//2",
],
[
"hoare_while_buggy_i_le_n",
"Off-by-one guard i <= n",
"REJECTED",
json.dumps(hoare_buggy.counterexample, sort_keys=True),
],
[
"symbolic_path_explorer",
"legacy_pricing_symbolic_kernel",
f"{sym_hits}_BUGS_{sym_detail.infeasible_paths_pruned}_PRUNED",
json.dumps(rand_vs_sym["symbolic_first_witness"], sort_keys=True),
],
],
},
{
"id": "table_ep_bva_and_contract_gates",
"title": "FastAPI Strict Pydantic v2 Contract, Test Doubles & BVA Gates",
"columns": [
"verification_surface",
"probe_or_input",
"observed_output",
"status",
],
"rows": [
[
"3_value_bva_boundary_100",
"units=100, tier=growth, promo=0",
f"hard={hard_100}c vs legacy={leg_100}c",
"BOUNDARY_VERIFIED",
],
[
"metamorphic_batch_permutation",
"[req_a, req_b] vs [req_b, req_a]",
f"clean_inv={clean_invariant}, legacy_leak={legacy_contaminated}",
"INVARIANT_ENFORCED",
],
[
"fastapi_strict_v2_and_doubles",
"POST /v1/quote + InMemoryFake + AuditSpy",
(
f"ok={asgi_probe['quote_status']} "
f"({asgi_probe['quote_net_cents']}c), "
f"bad={asgi_probe['strict_validation_status']}, "
f"spy={asgi_probe['audit_spy_count']}"
),
"CONTRACT_PASSED",
],
],
},
],
},
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run WB-Ch05 verification & TDD workbench.")
parser.add_argument(
"--quick",
action="store_true",
help="Run fast reduced random-comparison iteration budget.",
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch05_workbench_results.json"),
help="Destination JSON path.",
)
args = parser.parse_args()
payload = build_workbench_results(quick=args.quick, seed=args.seed)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
print(f"Exported WB-Ch05 empirical results -> {args.output}")
if __name__ == "__main__":
main()
"""Comprehensive 16-test verification suite (unittest + pytest + Hypothesis + ASGI + AST)."""
from __future__ import annotations
import ast
import asyncio
import json
import subprocess
import sys
import unittest
from collections.abc import Iterator
from pathlib import Path
from typing import Any
import httpx
import pytest
from hypothesis import given, settings
from hypothesis import strategies as st
from verification_tdd_lab import target_api_and_domain
from verification_tdd_lab.formal_verifier import (
compute_wp_assignment_chain,
explore_symbolic_paths,
run_random_vs_symbolic_comparison,
verify_hoare_loop_sum_and_wp,
)
from verification_tdd_lab.target_api_and_domain import (
FixedClock,
InMemoryQuoteRepo,
NullAuditDummy,
QuoteRequest,
RecordingAuditSpy,
compute_batch_score,
compute_pricing_core,
create_verification_app,
evaluate_sla_gate,
legacy_batch_score,
legacy_buggy_quote_cents,
)
from verification_tdd_lab.testing_engines import (
generate_ep_bva_vectors,
quote_request_strategy,
run_ast_mutation_benchmark,
shrink_counterexample,
solve_mcdc_a_and_b_or_c,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_DESERIALIZERS = frozenset(
{"pickle", "_pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
)
class TestUnittestInteroperability(unittest.TestCase):
"""Demonstrate xUnit unittest.TestCase execution seamlessly inside pytest."""
def test_01_unittest_ep_bva_and_protocol_doubles(self) -> None:
hard_99 = compute_pricing_core(units=99, tier="growth", promo_bps=0, sla_score=0.90)
hard_100 = compute_pricing_core(units=100, tier="growth", promo_bps=0, sla_score=0.90)
leg_100 = legacy_buggy_quote_cents(units=100, tier="growth", promo_bps=0, sla_score=0.90)
self.assertEqual(hard_99["volume_discount_bps"], 0)
self.assertEqual(hard_100["volume_discount_bps"], 700)
self.assertEqual(hard_100["net_cents"], 9300)
self.assertEqual(leg_100["volume_discount_bps"], 0)
self.assertEqual(leg_100["net_cents"], 10000)
stub_clock = FixedClock("2026-11-22T09:30:00Z")
fake_repo = InMemoryQuoteRepo()
spy_audit = RecordingAuditSpy()
dummy_audit = NullAuditDummy()
dummy_audit.record("ignored", "req-000", 0)
self.assertEqual(stub_clock.now_iso(), "2026-11-22T09:30:00Z")
fake_repo.save("req-101", {"net_cents": 9300})
self.assertEqual(fake_repo.count(), 1)
stored = fake_repo.get("req-101")
self.assertIsNotNone(stored)
assert stored is not None
self.assertEqual(stored["net_cents"], 9300)
spy_audit.record("quote.computed", "req-101", 9300)
self.assertEqual(spy_audit.events, [("quote.computed", "req-101", 9300)])
@pytest.fixture
def isolated_repo() -> Iterator[InMemoryQuoteRepo]:
"""Function-scoped fixture with deterministic yield teardown."""
repo = InMemoryQuoteRepo()
yield repo
repo._store.clear()
def test_02_bva_vector_generator_2value_vs_3value() -> None:
report = generate_ep_bva_vectors()
assert 99 in report["bva_2_value_units"]
assert 100 in report["bva_2_value_units"]
assert 101 in report["bva_3_value_units"]
assert 10001 in report["bva_3_value_units"]
caught = report["caught_legacy_boundary_bugs"]
assert any(item["units"] == 100 for item in caught)
def test_03_mcdc_minimal_n_plus_one_independence_pairs() -> None:
mcdc = solve_mcdc_a_and_b_or_c()
assert mcdc["exhaustive_count"] == 8
assert mcdc["mcdc_minimal_count"] == 4
selected = mcdc["selected_vectors"]
assert len(selected) == 4
for vec in selected:
assert evaluate_sla_gate(
vec["A_sla_ok"], vec["B_is_enterprise"], vec["C_volume_qualified"]
) == vec["outcome"]
for cond_name in ("A_sla_ok", "B_is_enterprise", "C_volume_qualified"):
assert len(mcdc["independence_pairs"][cond_name]) >= 1
def test_04_ast_mutation_weak_100_line_cov_vs_hardened_and_operators() -> None:
report = run_ast_mutation_benchmark()
assert report.total_mutants >= 30
assert report.weak_line_coverage_pct == 100.0
assert report.weak_mutation_score_pct < 50.0
assert report.hardened_mutation_score_pct >= 90.0
assert len(report.survived_in_weak_sample) > 0
for op_cls in ("ROR", "AOR", "LCR", "CRP"):
assert op_cls in report.operator_breakdown
bucket = report.operator_breakdown[op_cls]
assert bucket["total"] >= 2
assert bucket["hardened_killed"] >= bucket["weak_killed"]
def test_05_pure_python_delta_shrinker_minimizes_counterexample() -> None:
def _fails_zero_div(units: int, tier: str, promo_bps: int, sla: float) -> bool:
_ = sla
try:
legacy_buggy_quote_cents(units=units, tier=tier, promo_bps=promo_bps, sla_score=0.9)
except ZeroDivisionError:
return True
return False
shrunk = shrink_counterexample(
initial_units=4821,
initial_tier="enterprise",
initial_promo_bps=10000,
initial_sla_score=0.91,
failure_predicate=_fails_zero_div,
)
assert shrunk["minimal"] == {
"units": 1,
"tier": "enterprise",
"promo_bps": 10000,
"sla_score": 0.0,
}
assert shrunk["shrink_steps"] >= 5
@settings(derandomize=True, max_examples=50)
@given(req=quote_request_strategy())
def test_06_hypothesis_quote_non_negative_and_margin_bounds(req: QuoteRequest) -> None:
res = compute_pricing_core(
units=req.units,
tier=req.tier,
promo_bps=req.promo_bps,
sla_score=req.sla_score,
)
assert 0 <= int(res["total_discount_bps"]) <= 9000
assert int(res["subtotal_cents"]) == int(res["discount_cents"]) + int(res["net_cents"])
assert 1000 <= int(res["effective_margin_bps"]) <= 10000
assert int(res["net_cents"]) > 0
@settings(derandomize=True, max_examples=50)
@given(items=st.lists(quote_request_strategy(), min_size=2, max_size=6))
def test_07_hypothesis_metamorphic_batch_permutation_invariance(
items: list[QuoteRequest],
) -> None:
forward = compute_batch_score(items)
reversed_out = compute_batch_score(list(reversed(items)))
assert forward == list(reversed(reversed_out))
pair = [
QuoteRequest(
request_id="m-1", units=100, tier="enterprise", promo_bps=0, sla_score=0.9, dry_run=True
),
QuoteRequest(
request_id="m-2", units=100, tier="standard", promo_bps=0, sla_score=0.9, dry_run=True
),
]
assert (
legacy_batch_score(pair)[1]["net_cents"]
!= legacy_batch_score(list(reversed(pair)))[0]["net_cents"]
)
@settings(derandomize=True, max_examples=50)
@given(req=quote_request_strategy())
def test_08_hypothesis_differential_pricing_monotonicity_and_json_roundtrip(
req: QuoteRequest,
) -> None:
roundtrip = QuoteRequest.model_validate_json(req.model_dump_json())
assert roundtrip == req
base_res = compute_pricing_core(req.units, req.tier, req.promo_bps, req.sla_score)
if req.units < 10000:
more_units_res = compute_pricing_core(req.units + 1, req.tier, req.promo_bps, req.sla_score)
assert int(more_units_res["subtotal_cents"]) > int(base_res["subtotal_cents"])
def test_09_hoare_wp_and_while_loop_invariant_and_variant() -> None:
wp_res = compute_wp_assignment_chain(
assignments=[("x", "x + 1"), ("y", "x * 2")],
postcondition="y <= 20",
)
assert wp_res["weakest_precondition"] == "(x + 1) * 2 <= 20"
valid = verify_hoare_loop_sum_and_wp(n_bound=10, off_by_one_bug=False)
assert valid.initialization_holds is True
assert valid.maintenance_holds is True
assert valid.exit_postcondition_holds is True
assert valid.variant_decreasing_holds is True
assert valid.all_obligations_verified is True
buggy = verify_hoare_loop_sum_and_wp(n_bound=10, off_by_one_bug=True)
assert buggy.all_obligations_verified is False
assert buggy.counterexample is not None
def test_10_symbolic_execution_vs_random_fuzz_and_unsat_pruning() -> None:
sym = explore_symbolic_paths()
assert sym.feasible_paths >= 6
assert sym.infeasible_paths_pruned >= 3
assert len(sym.discovered_failures) >= 1
first_witness = sym.discovered_failures[0]["witness"]
assert first_witness["tier_code"] == 2
assert first_witness["promo_bps"] == 10000
comp = run_random_vs_symbolic_comparison(seed=42, n_random=2000)
assert comp["random_zero_div_hits"] == 0
assert comp["symbolic_failures_found"] >= 1
def test_11_fastapi_httpx_asgitransport_strict_v2_and_contract(
isolated_repo: InMemoryQuoteRepo,
) -> None:
async def _run() -> None:
clock = FixedClock("2026-11-22T15:00:00Z")
spy = RecordingAuditSpy()
app = create_verification_app(repo=isolated_repo, clock=clock, audit=spy)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
r_h = await client.get("/health")
assert r_h.status_code == 200
assert r_h.json()["status"] == "ok"
r_q = await client.post(
"/v1/quote",
json={
"request_id": "api-100",
"units": 100,
"tier": "growth",
"promo_bps": 500,
"sla_score": 0.90,
"dry_run": False,
},
)
assert r_q.status_code == 200
payload = r_q.json()
assert payload["net_cents"] == 8800
assert payload["timestamp"] == "2026-11-22T15:00:00Z"
r_get = await client.get("/v1/quotes/api-100")
assert r_get.status_code == 200
assert r_get.json()["net_cents"] == 8800
r_bad = await client.post(
"/v1/quote",
json={
"request_id": "api-bad",
"units": "100",
"tier": "growth",
"promo_bps": 500,
"sla_score": 0.90,
"extra_hack": True,
},
)
assert r_bad.status_code == 422
r_batch = await client.post(
"/v1/batch-score",
json={
"batch_id": "batch-01",
"items": [
{
"request_id": "item-a",
"units": 100,
"tier": "enterprise",
"promo_bps": 0,
"sla_score": 0.95,
},
{
"request_id": "item-b",
"units": 50,
"tier": "standard",
"promo_bps": 0,
"sla_score": 0.80,
},
],
},
)
assert r_batch.status_code == 200
assert r_batch.json()["count"] == 2
assert len(spy.events) == 1
assert isolated_repo.count() == 1
asyncio.run(_run())
@pytest.mark.parametrize(
("units", "tier", "expected_unit_price", "expected_vol_bps"),
[
(1, "standard", 120, 0),
(100, "growth", 100, 700),
(1000, "enterprise", 80, 1500),
],
)
def test_12_pytest_fixtures_parametrize_and_monkeypatch_interplay(
monkeypatch: pytest.MonkeyPatch,
units: int,
tier: str,
expected_unit_price: int,
expected_vol_bps: int,
) -> None:
res = compute_pricing_core(units=units, tier=tier, promo_bps=0, sla_score=0.90)
assert res["unit_price_cents"] == expected_unit_price
assert res["volume_discount_bps"] == expected_vol_bps
monkeypatch.setattr(target_api_and_domain, "evaluate_sla_gate", lambda _a, _b, _c: False)
assert target_api_and_domain.evaluate_sla_gate(True, True, True) is False
def test_13_noxfile_ci_matrix_and_cli_demo_quick_export(tmp_path: Path) -> None:
nox_text = (LAB_ROOT / "noxfile.py").read_text(encoding="utf-8")
nox_tree = ast.parse(nox_text)
session_fns = {node.name for node in nox_tree.body if isinstance(node, ast.FunctionDef)}
assert {"lint", "typecheck", "tests", "coverage"}.issubset(session_fns)
out_json = tmp_path / "quick_wb_ch05.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--quick",
"--seed",
"42",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Exported WB-Ch05 empirical results" in proc.stdout
data: dict[str, Any] = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_14_security_only_ast_scan_no_unsafe_deserialization() -> None:
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
LAB_ROOT / "noxfile.py",
]
violations: list[str] = []
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:
top = alias.name.split(".")[0]
if top in FORBIDDEN_DESERIALIZERS:
violations.append(f"{path.name}: import {alias.name}")
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".")[0]
if top in FORBIDDEN_DESERIALIZERS:
violations.append(f"{path.name}: from {node.module}")
assert violations == []
WB-Ch05), Testing Trophy cân bằng tốc độ bằng ASGITransport + Fake repo, còn Metamorphic Testing (batch_score bất biến hoán vị) giải quyết bài toán thiếu Test Oracle.
units >= 100 (trên miền hợp lệ [1, 10000]), nhưng mã nguồn cũ (legacy_buggy_quote_cents) viết nhầm thành units > 100. Tại sao 3-Value BVA ({99, 100, 101}) vượt trội hơn EP thuần và 2-Value BVA trong thực tế?test_01 và test_02 của WB-Ch05: legacy_buggy_quote_cents(100, 'growth', 0, 0.9) trả 10000 cents (0 bps) thay vì 9300 cents (700 bps). 3-Value BVA giữ độ phức tạp hằng số quanh mỗi biên mà vẫn chặn đứng các lỗi lệch ±1.
evaluate_sla_gate(A, B, C) = A and (B or C) có \(N = 3\) điều kiện nguyên tử. Chuẩn MC/DC (Modified Condition/Decision Coverage — FAA DO-178C DAL-A) yêu cầu điều kiện gì và nén số véc-tơ kiểm thử từ \(2^3 = 8\) xuống còn bao nhiêu?test_03 và solve_mcdc_a_and_b_or_c() trong WB-Ch05 tìm chính xác 4 véc-tơ tối thiểu cho A and (B or C) ((F,F,T), (T,F,F), (T,F,T), (T,T,F)), bảo đảm mỗi biến A, B, C đều trực tiếp được đánh giá (tránh bẫy short-circuit) và độc lập đảo kết quả.
run_ast_mutation_benchmark() trên hàm compute_pricing_core (39 đột biến đơn bậc thuộc ROR, AOR, LCR, CRP), bộ kiểm thử khói (weak smoke suite) đạt 100.0% độ bao phủ dòng nhưng chỉ đạt 25.64% (10/39) Mutation Score, còn bộ kiểm thử gia cố đạt 100.0% (39/39). Nguyên nhân cốt lõi và công thức Mutation Score chuẩn là gì?assert đủ nhạy khi logic bị bóp méo (test_04 của WB-Ch05: 100.0% dòng nhưng chỉ diệt 10/39 = 25.64% đột biến). Công thức M = K / (T - E) loại trừ đột biến tương đương E (bất khả quyết định tổng quát theo Định lý Rice).
legacy_batch_score?test_05–test_08 kiểm chứng thu gọn 14 bước (4821 -> 1), round-trip JSON Pydantic v2, tính đơn điệu subtotal, và bất biến hoán vị lô (legacy_batch_score hỏng khi đảo [a, b] thành [b, a] vì rò rỉ biến carry_promo_bps).
while cho chương trình acc := 0; i := 0; while (i < n) do (acc := acc + i; i := i + 1) với bất biến \(I \equiv (0 \le i \le n) \land (\text{acc} = i(i-1)/2)\) và hàm hạng \(V = n - i\). Kết quả nào đúng cho cả tính toán wp và kiểm chứng 4 nghĩa vụ Hoare?test_09 trong formal_verifier.py tính wp bằng biến đổi AST cho ra (x + 1) * 2 <= 20, xác minh 4/4 nghĩa vụ trên i < n, và bắt chính xác lỗi off-by-one i <= n ở bước next_i=1, n=0 (obligation=2).
legacy_pricing_symbolic_kernel chứa nhánh chết if units > 500: if units < 200: và lỗi chia cho 0 ở nhánh hẹp tier_code == 2 kèm promo_bps == 10000, thực nghiệm đối chứng trong WB-Ch05 cho thấy điều gì giữa 2,000 mẫu Random Fuzz và Symbolic Execution?test_10 và run_random_vs_symbolic_comparison(seed=42, n_random=2000) ghi nhận random_zero_div_hits = 0 trong khi Symbolic Execution duyệt 12 đường khả thi, tỉa 4 nhánh UNSAT và tìm thấy 4 witness chia 0 trong 8.52 ms.
create_verification_app, lựa chọn nào thể hiện đúng sự phối hợp giữa trường phái Chicago, phân loại 5 Test Doubles, fixture pytest, và ma trận nox?test_01, test_11, test_12, test_13 của WB-Ch05 minh họa trọn vẹn unittest.TestCase chạy cùng pytest, yield fixture, @pytest.mark.parametrize, monkeypatch, httpx.ASGITransport, 4 Protocol Test Doubles, và noxfile.py (16/16 PASS).
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Phân hoạch Tương đương (EP), BVA 3-Giá trị & MC/DC (DO-178C)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân biệt 2-Value BVA ({a-1, a, b, b+1}) với 3-Value BVA ({a-1, a, a+1, b-1, b, b+1}) quanh ngưỡng 100 và 1000, đồng thời nhắc lại định nghĩa cặp độc lập trong chuẩn MC/DC cho A and (B or C) và ảnh hưởng của đánh giá đoản mạch (short-circuit).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra generate_ep_bva_vectors() và solve_mcdc_a_and_b_or_c() trong src/verification_tdd_lab/testing_engines.py; chạy pytest -k "test_01 or test_02 or test_03" -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
3-Value BVA bắt chính xác lỗi units > 100 tại units=100 (hard=9300 cents / 700 bps vs legacy=10000 cents / 0 bps); bộ MC/DC tối thiểu gồm N+1 = 4 véc-tơ ((F,F,T), (T,F,F), (T,F,T), (T,T,F)) thay cho 8 véc-tơ vét cạn.
Bài tập 2 — Đột biến AST (Mutation Testing) & Phá vỡ Ảo giác 100% Line Coverage
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Trình bày 4 nhóm toán tử đột biến ROR, AOR, LCR, CRP, công thức M = K / (T - E), vì sao đột biến tương đương E không thể bị diệt bởi bất kỳ đầu vào nào, và vì sao một bộ smoke test đạt 100% line coverage vẫn dễ dàng để lọt đột biến.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Mở run_ast_mutation_benchmark() trong testing_engines.py và đối chiếu số liệu trong artifacts/t2_ch05_workbench_results.json; chạy pytest -k test_04 -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
Trên 39 đột biến AST của compute_pricing_core (ROR: 12, AOR: 7, LCR: 4, CRP: 16), bộ smoke đạt 100.0% line coverage nhưng chỉ đạt 25.64% (10/39) Mutation Score (CRP chỉ 6.2%), còn bộ gia cố đạt 100.0% (39/39).
Bài tập 3 — Hypothesis Property Testing, Thu gọn Phản ví dụ & Bất biến Biến đổi (Metamorphic)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích cơ chế thu gọn trên luồng chọn lựa nhị phân (Conjecture choice-stream) của Hypothesis so với external shrinking kiểu QuickCheck, và viết 3 bất biến cho hệ thống định giá: cận biên không âm, tính đơn điệu theo units, và bất biến hoán vị lô.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra quote_request_strategy(), shrink_counterexample() trong testing_engines.py và các ca @given trong tests/test_verification_tdd_lab.py; chạy pytest -k "test_05 or test_06 or test_07 or test_08" -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
shrink_counterexample rút gọn units=4821, promo_bps=10000 về units=1, promo_bps=10000 qua 14 bước; 3 bài kiểm thử @given(..., max_examples=50, derandomize=True) xác minh subtotal == discount + net, JSON round-trip, đơn điệu subtotal, và bắt rò rỉ trạng thái legacy_batch_score.
Bài tập 4 — Tính Tiền điều kiện Yếu nhất Hoare (wp), Bất biến Vòng lặp (I) & Hàm hạng (V)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng phép thế ngược \(Q[E/x]\) cho x := x + 1; y := x * 2 {y <= 20}, rồi viết đầy đủ 4 nghĩa vụ chứng minh cho vòng lặp cộng dồn while i < n với \(I\) và \(V = n - i\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đọc compute_wp_assignment_chain() và verify_hoare_loop_sum_and_wp() trong formal_verifier.py; chạy pytest -k test_09 -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
wp suy ra (x + 1) * 2 <= 20; vòng lặp chuẩn i < n vượt qua 4/4 nghĩa vụ (Init, Maint, Exit, Variant) trên n = 0..10, còn vòng lặp lệch biên i <= n bị bác bỏ ngay tại obligation=2, n=0, i=0, next_i=1.
Bài tập 5 — Thực thi Ký hiệu (Symbolic Execution), Tỉa Nhánh UNSAT & Săn Lỗi Đường Hẹp
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích cấu trúc trạng thái ký hiệu (\sigma, \Pi), cơ chế Fourier–Motzkin giải bất đẳng thức tuyến tính tỉa nhánh bất khả thi (units > 500 và units < 200), và lý giải vì sao thử ngẫu nhiên đồng nhất gần như mù tịt trước lỗi tier_code == 2 && promo_bps == 10000.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Mở explore_symbolic_paths() và run_random_vs_symbolic_comparison() trong formal_verifier.py; chạy pytest -k test_10 -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
2,000 mẫu ngẫu nhiên (seed=42) đạt 0 lần trúng (P = 3.33e-5), trong khi Symbolic Execution duyệt 12 đường khả thi, tỉa 4 nhánh UNSAT, và tìm thấy 4 chứng nhân ZeroDivisionError (promo_bps=10000, tier_code=2, units=1000) trong 8.52 ms.
Bài tập 6 — TDD Kiến trúc Protocol Test Doubles, FastAPI ASGITransport, noxfile.py & 16/16 pytest
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân biệt 5 loại Test Doubles (Dummy, Stub, Spy, Mock, Fake), so sánh Chicago vs London TDD, vai trò của yield fixture / @pytest.mark.parametrize / monkeypatch, và cấu trúc 4 phiên CI trong noxfile.py.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ kiểm định: ruff check src scripts tests noxfile.py, mypy src, pytest -p no:cacheprovider -v, và python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch05_workbench_results.json.
Tiêu chí Đáp án & Số đối chứng
Ứng dụng create_verification_app dùng InMemoryQuoteRepo (Fake), FixedClock (Stub), RecordingAuditSpy (Spy), NullAuditDummy (Dummy) qua httpx.ASGITransport (200/422), ruff 0 lỗi, mypy 0 lỗi, AST 0 import giải tuần tự cấm, 16/16 pytest PASS.