Chương 11 — Tầng Tiêu thụ OLAP (Star Schema, SCD Types 1–6, ClickHouse & Apache Pinot, Materialized Views) & Feast Feature Store (Point-in-Time ASOF & Training–Serving Parity)
Từ SCD Type 1 bóp méo 34.15% (537,917.64 USD) vs SCD Type 2 (0.0 USD), ClickHouse MergeTree 1/1,221 granule (99.92% skip), AggregatingMergeTree MV (12.14x) & ReplacingMergeTree argMax (0.0 USD) đến DuckDB ASOF Point-in-Time (81.75%->0.0% future leak; OOT AUC 0.5143->0.8858) & Feast 100% Parity (max_diff=0.0).
Unit ID:
T2-P2-U05
Track & Part: Track 2 (EDAI) — Part 2: Modern Data Engineering: Streaming, Open Lakehouse, Compute & Governance (part-02-data-engineering-and-lakehouse)
Truy xuất Giáo trình Gốc (R33): Bài 11 Data Engineering — Consumption Layer (Dimensional modeling,SCD,OLAP engines (Clickhouse & Pinot), and materialized views,Feature core,Feature view design,Feature transformation,ML integration,Lab: Implement feature stores and feature processing pipelines [Feast]) trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Tích hợp Chuyên đề Sâu Cốt lõi (Deep-Dive Article #15): Point-in-Time Features and Training–Serving Parity trong 03-35-special-topics-extracted.md
Bài thực hành Song hành (Lab 10): labs/lab-10-feast-clickhouse-pit-feature-store/README.md (feast_olap_pit_lab)
Tình huống Mở đầu: Năm Thảm họa Kinh điển Ở Tầng Tiêu thụ Dữ liệu & AI (Consumption Layer)#
Sau khi dữ liệu thô đã được thu nạp qua Kafka/Debezium (Chương 7), chuẩn hóa trong Lakehouse Iceberg/Delta (Chương 8) và biến đổi qua Spark/Flink (Chương 9–10), tất cả giá trị kinh doanh hội tụ tại Tầng Tiêu thụ (Consumption Layer) phục vụ hai đối tượng hoàn toàn khác biệt: bảng điều khiển phân tích thời gian thực (BI & Real-Time OLAP) và hệ thống suy luận Học máy (Feature Store & ML Serving). Nếu kỹ sư thiết kế tầng này theo thói quen OLTP hoặc xử lý lô đơn giản, năm thảm họa sản xuất nghiêm trọng sẽ xảy ra ngay lập tức:
- Bóp méo Toàn bộ Lịch sử Doanh thu Vì Dùng
SCD Type 1Thay VìSCD Type 2: Trong tập thực nghiệm12,000giao dịch (1,575,346.92 USD,600khách hàng) củaLab 10, có180khách hàng nâng hạng từStandardlênVIPvào giai đoạn giữa quý. Khi đội BI dùng SCD Type 1 (ghi đè thẳng cộtsegment_tier), toàn bộ giao dịch quá khứ trước ngày nâng hạng bị gán nhầm vào nhómVIP, dịch chuyển sai268,958.82 USDtừStandardsangVIPvà tạo tổng sai lệch tuyệt đối537,917.64 USD(34.15%doanh thu)! Ngược lại, SCD Type 2 nối theo khoảng hiệu lực thời gian đạt sai số0.0 USD(0.0%). - Đóng băng Bảng Điều khiển OLAP Vì Khóa Sắp xếp Sai & Thiếu
Materialized Views: Trên bảng10,000,000dòng củaClickHouse MergeTree(index_granularity = 8,192,1,221granules), đặt khóaORDER BY (tx_ts, customer_id)buộc truy vấn lọc 1 khách hàng trong 7 ngày phải quét285granules (2,334,720dòng); chỉ bằng cách đảo tiền tố khóa sangORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts), ClickHouse chỉ chạm1granule (8,192dòng — bỏ qua99.92%dữ liệu, gọn hơn285.0x). Kết hợpAggregatingMergeTreeIncremental Materialized View trên240,000giao dịch ởDuckDB, kích thước quét rút xuống2,400dòng (100.0xnhỏ hơn) và tốc độ10truy vấn phân tích tăng12.14x(344.08 ms -> 28.35 ms). - Phình Số liệu Tài chính Trên
ReplacingMergeTreeVì Quên Cơ chế Hợp nhất Bất đồng bộ: Khi5,000đơn hàng (1,198,102.88 USD) nhận900bản ghi CDC cập nhật phiên bảnver,ReplacingMergeTree(ver)chỉ khử trùng lặp bất đồng bộ ở các lần merge nền. Truy vấnSELECT SUM(amount_usd)trực tiếp trước lúc merge bị cộng đúp lên1,416,082.78 USD(+217,979.90 USD=+18.19%); dùngargMax(amount_usd, ver)thu đúng5,000đơn với sai số0.0 USD. - Ảo giác Mô hình
ROC-AUC = 0.9853Rồi Sụp đổ Thành0.5143Ngoài Thực tế (Deep-Dive Article #15— Look-Ahead Leakage): Đội ML nối bảng nhãn gian lận (2,400giao dịch) với bảng đặc trưng người dùng theo phép nối ảnh chụp mới nhất cùng ngày (Naive Latest-Window Join). Vì sau khi giao dịch gian lận xảy ra khoảng30 phút – 4 giờ, hệ thống vận hành mới khóa thẻ (tx_velocity_1hrơi về gần0) và ghi nhậnchargeback_flag_count >= 1, phép nối ngây thơ làm rò rỉ tương lai trên81.75%mẫu (1,962 / 2,400)! Mô hình đạtROC-AUC = 0.9853trên kiểm định giả tạo, nhưng khi chạy trên dữ liệu phục vụ nhân quả thực tế (OOT Serving) thì sụp đổ thảm hại xuốngROC-AUC = 0.5143(rơi-0.4710AUC). Trong khi đó,DuckDB 2.0 ASOF LEFT JOIN+TTL = 3,600sđạt0.0%(0mẫu) rò rỉ tương lai, đẩy đúng232mẫu quá hạnTTLvềNULL, và giúp mô hình đạtROC-AUC = 0.8858ngoài thực tế (hơn mô hình ngây thơ+0.3715AUC!). - Thảm họa Lệch Huấn luyện–Phục vụ (
Training–Serving Skew): Viết lại logic tính đặc trưng ở dịch vụ API tách rời với mã huấn luyện ngoại tuyến (lệch đơn vị chia, bỏ quên hạnTTLcủa Redis) gây sai lệch trên500 / 500yêu cầu phục vụ (0.0%parity,48lỗi lệchTTL). Đóng gói chung hàm biến đổi vàoFeast OnDemandFeatureViewkèm đồng bộTTLđưa tỷ lệ đồng nhất về100.0%(0vi phạm,max_abs_diff = 0.0).
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 11 và feast_olap_pit_lab (Lab 10), kỹ sư Dữ liệu & AI nắm vững:
- Mô hình hóa Đa chiều &
SCD Types 1–6: Thiết kế chuẩn xác bảng Fact (Transaction,Periodic,Accumulating),Conformed Dimensions, phân biệtStar SchemavsSnowflakevsOne Big Table (OBT), và cài đặtSCD Type 2(valid_from,valid_to,is_current) kèm chứng minh định lượng độ méo lịch sử củaSCD Type 1. - Động cơ OLAP Thời gian thực (
ClickHouse&Apache Pinot) &Materialized Views: Hiểu sâu giải phẫuMergeTree(chỉ mục thưa8,192dòng/granule, thiết kế khóaORDER BY), phòng tránh bẫy chưa hợp nhất củaReplacingMergeTree(ver)bằngargMax/FINAL, vận hành IncrementalMATERIALIZED VIEW(AggregatingMergeTree) vớisumState/uniqState, và đối chiếuApache Pinot(Star-Tree Index,Realtime Upsert). - Kiến trúc
FeastFeature Store Toàn diện: Thiết kế bộ tứ cốt lõi (Entity,DataSource/PushSource,FeatureViewgắnttl,OnDemandFeatureView), tách bạch Offline Store (DuckDB/ClickHouse/Parquet) vs Online Store (Redis/DynamoDB), luồng đồng bộmaterialize&PushSourcedual-write. - Chuyên đề Sâu #15 —
Point-in-Time ASOF&Training–Serving Parity: Chứng minh bất biến nhân quả \(t_{\text{feat}} \le t_{\text{label}}\) và ràng buộcTTL, thực thiDuckDB 2.0 ASOF LEFT JOINloại bỏ triệt để Look-Ahead Leakage (\(\rho_{\text{leak}} \equiv 0\)), nhận diện ảo giác ML offline, và vận hành Offline–Online Parity Auditor (<= 1e-6tolerance) trong CI/CD.
Bảng Truy xuất Giáo trình Gốc & Deep-Dive #15 sang Chuẩn SOTA 2026 (Unit T2-P2-U05)#
Nội dung Gốc (02-track-edai-raw-curriculum.md R33 & Article #15) |
Nâng cấp Chuẩn SOTA 2026 (ch-11) |
Mục trong Chương 11 | Tạo tác & Kiểm thử (feast_olap_pit_lab) |
|---|---|---|---|
1. Dimensional modeling (R33) |
Star vs Snowflake vs One Big Table (OBT); Transaction/Periodic/Accumulating Fact; Conformed Dimensions |
Trụ cột 1 (§1.1) + Trụ cột 2 (§2.2) | olap_scd_engine.py, Test 02 |
2. SCD (R33) |
Phân tích đầy đủ SCD Types 0–6; chứng minh toán học & thực nghiệm độ méo lịch sử của Type 1 vs độ chính xác tuyệt đối Type 2 ([valid_from, valid_to)) |
Trụ cột 1 (§1.2) + Mermaid 1 + Widget 1 | run_scd1_vs_scd2_duckdb_audit, Test 03 |
3. OLAP engines (ClickHouse & Pinot), and materialized views (R33) |
ClickHouse MergeTree sparse index (8,192), ReplacingMergeTree(ver) + argMax/FINAL, AggregatingMergeTree Incremental MV & Refreshable MV; Apache Pinot Star-Tree & Upsert |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1–§2.2) + Widget 1 | 01_clickhouse_star_scd2_mv.sql, simulate_clickhouse_mergetree_and_mv, Tests 04, 05, 12 |
4. Feature core & Feature view design (R33) |
Kiến trúc Dual-Store (Offline vs Redis Online), Entity, FileSource/ClickHouseSource/PushSource, RequestSource, FeatureView với ttl chặt chẽ |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1) + Mermaid 3 | configs/feature_store.yaml, feast_repo/features.py, Tests 13, 14 |
5. Feature transformation & ML integration (R33) |
Batch pre-agg, Streaming PushSource, và OnDemandFeatureView dùng chung 1 hàm thuần túy cho Train & Serve |
Trụ cột 1 (§1.6) + Trụ cột 3 (§3.2) + Widget 3 | compute_shared_risk_features, Tests 10, 15 |
| 6. Deep-Dive Article #15: Point-in-Time Features and Training–Serving Parity | 4 phần chuẩn mực: (1) Failure Case Look-Ahead Mirage & Skew; (2) Công thức ASOF + TTL, \(\rho_{\text{leak}}\), \(\epsilon_{\text{parity}}\); (3) Thực nghiệm ML Ablation (0.9853 -> 0.5143 vs PIT 0.8858); (4) Playbook quyết định sản xuất |
Trụ cột 1 (§1.5–§1.6) + Trụ cột 2 (§2.2) + Mermaid 2 + Widgets 2–3 | pit_feature_store.py, Tests 06–10 |
7. Lab: Implement feature stores & pipelines (Feast) (R33) |
Kiến trúc Hai Tầng: ClickHouse + Redis + Postgres + Feast Server (docker-compose.yml + DDL + YAML + AST) + Động cơ DuckDB 2.0 ASOF + Polars + sklearn + OpenTelemetry SDK 100% offline |
Trụ cột 3 (§3.1–§3.3) + Trụ cột 4 (§4.1–§4.3) | Toàn bộ lab-10-feast-clickhouse-pit-feature-store/ (17/17 pytest PASS, 0 skip, ruff, mypy) |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 11 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 11 & feast_olap_pit_lab |
Giá trị Thực nghiệm Lab 10 |
|---|---|---|---|
| \(t_{\text{tx}}, t_{\text{from}}, t_{\text{to}}\) | timestamp (\(\text{UTC}\)) | Thời điểm giao dịch và khoảng hiệu lực nửa mở \([t_{\text{from}}, t_{\text{to}})\) của phiên bản SCD Type 2 | 12,000 giao dịch, 90 ngày |
| \(\Delta R_{\text{SCD1}}(c)\) | \(\text{USD}\) | Độ méo doanh thu lịch sử phân khúc \(c\) do ghi đè SCD Type 1 thay cho nối khoảng SCD Type 2 | 537,917.64 USD (34.15%) vs 0.0 USD |
| \(N, G, k_{\text{hit}}\) | dòng, dòng/granule, granules | Tổng dòng phân vùng, kích thước granule thưa (8,192), và số granule chạm điều kiện lọc |
\(N=10\text{M}\), \(G=8{,}192\), \(k_{\text{hit}}=1\) (99.92% skip) |
| \(t_{\text{label}}, t_{\text{feat}}, \text{TTL}\) | timestamp, giây (\(\text{s}\)) | Thời điểm nhãn gian lận, thời điểm ảnh chụp đặc trưng, và ngưỡng hết hạn độ tươi | 2,400 nhãn, 16,300 snapshots, \(\text{TTL} = 3{,}600\text{s}\) |
| \(t^*(e, t_{\text{label}})\) | timestamp / \(\bot\) | Thời điểm đặc trưng nhân quả tối đại thỏa \(t_j \le t_{\text{label}}\) và \(t_{\text{label}} - t_j \le \text{TTL}\) | 232 nhãn quá hạn \(\to \bot\) (NULL) |
| \(\rho_{\text{leak}}\) | \([0, 1]\) | Tỷ lệ rò rỉ tương lai \(\frac{1}{N} \sum \mathbb{I}[t_{\text{feat}, i} > t_{\text{label}, i}]\) | Naive 81.75% (1,962/2,400) vs PIT 0.0% |
| \(\epsilon_{\text{parity}}, \tau_{\text{tol}}\) | vô hướng | Sai khác cực đại \(|f_{\text{offline\_PIT}} - f_{\text{online\_KV}}|\) trên tập kiểm toán trực tuyến | Broken 4.79 (0.0% pass) vs Unified 0.0 (100.0%) |
Trụ cột 1 — Nguyên lý Gốc: Star/SCD 1–6, ClickHouse MergeTree, Pinot & Chuyên đề Sâu #15 (Point-in-Time ASOF & Parity)#
1.1 Mô hình hóa Đa chiều (Star Schema, Snowflake, One Big Table)#
Tại tầng tiêu thụ BI/Kho dữ liệu, việc tổ chức lại dữ liệu giao dịch đã làm sạch ở tầng Silver/Gold nhằm tối ưu tính dễ hiểu cho nghiệp vụ và hiệu năng truy vấn cột:
- Lược đồ Hình sao (
Star Schema— Kimball): Đặt bảng Fact ở trung tâm (chứa khóa ngoạisurrogate_keyvà các độ đo số học cộng gộp được nhưamount_usd,quantity) nối trực tiếp 1 bước tới các bảng Dimension đã phi chuẩn hóa (ví dụDimCustomer,DimMerchant,DimDate). - Lược đồ Bông tuyết (
Snowflake Schema): Chuẩn hóa tiếp các bảng chiều theo cấp (DimCustomer -> DimCity -> DimCountry -> DimRegion). Giảm trùng lặp chuỗi ở bảng chiều nhưng buộc truy vấn OLAP phải thực hiện nhiều phépJOINsâu, làm tăng độ trễ đuôi trên các cụm phân tán. - Một Bảng Lớn Duy nhất (
One Big Table — OBT): Dát phẳng trước (pre-join) bảng Fact với các thuộc tính Dimension tại thời điểm ghi xuống OLAP (ClickHouse/BigQuery/DuckDB). OBT loại bỏ hoàn toàn chi phíJOINlúc đọc nhưng phải đánh đổi bằng việc khó cập nhật hồi tố nếu dùng sai cơ chế Dimension (vẫn phải sinh OBT từ nguồn SCD Type 2 chuẩn!).
Ba Loại Bảng Fact & Chiều Thống nhất (Conformed Dimensions)#
- Transaction Fact: Ghi nhận từng sự kiện nguyên tử tại một thời điểm (ví dụ
fact_transactions). - Periodic Snapshot Fact: Chụp ảnh trạng thái định kỳ cuối ngày/giờ/tháng (ví dụ số dư tài khoản cuối ngày
fact_daily_balance). - Accumulating Snapshot Fact: Theo dõi vòng đời đa mốc thời gian của một đối tượng (ví dụ
order_created_ts,paid_ts,shipped_ts,delivered_tsđược cập nhật dần khi đơn hàng đi qua các trạm). - Conformed Dimensions: Bảng chiều chuẩn dùng chung giữa nhiều Fact (ví dụ
DimCustomerdùng chung cho cả Sales Fact lẫn Support Fact), bảo đảm mọi phòng ban nhìn chung một khái niệm phân hạng và vùng địa lý.
1.2 Chiều Thay đổi Chậm (SCD Types 1–6) & Toán học Bảo toàn Lịch sử#
Trong thế giới thực, thuộc tính của thực thể thay đổi theo thời gian. Khi khách hàng cust_0012 nâng hạng từ Standard lên VIP vào ngày 45, có 6 chiến lược lưu trữ lịch sử (SCD Types 0–6):
| Loại SCD | Cơ chế Lưu trữ & Cập nhật | Toàn vẹn Lịch sử (As-Was)? |
Tình huống Sử dụng Chuẩn |
|---|---|---|---|
| Type 0 | Giữ nguyên giá trị ban đầu, từ chối cập nhật | Có (bất biến) | Ngày đăng ký đầu tiên (signup_date), năm sinh |
| Type 1 | Ghi đè trực tiếp dòng hiện tại bằng giá trị mới | KHÔNG (phá hủy quá khứ) | Sửa lỗi chính tả email/tên — TUYỆT ĐỐI CẤM cho phân khúc doanh thu/rủi ro |
| Type 2 | Đóng phiên bản cũ (valid_to = t_change, is_current = 0) và thêm dòng mới (customer_sk mới, valid_from = t_change, valid_to = '2099-12-31', is_current = 1) |
TOÀN VẸN 100% | Chuẩn mực công nghiệp cho mọi báo cáo lịch sử BI và truy vết huấn luyện ML |
| Type 3 | Thêm cột prev_segment_tier lưu trạng thái liền trước trên cùng 1 dòng |
Chỉ nhớ 1 bước trước | Phân tích trước/sau tái cơ cấu lãnh thổ kinh doanh ngắn hạn |
| Type 4 | Bảng chính chỉ giữ trạng thái mới nhất; đẩy toàn bộ lịch sử sang bảng phụ dim_customer_history |
Có (qua bảng lịch sử) | Cần truy vấn điểm danh hiện tại cực nhanh mà vẫn lưu dấu kiểm toán |
| Type 6 | Hybrid 1+2+3: Lưu nhiều dòng lịch sử kiểu Type 2, kèm cột current_tier (cập nhật Type 1 trên mọi dòng) và prev_tier (Type 3) |
Có cả As-Was lẫn As-Is | Cho phép xem đồng thời "Doanh thu từ người dùng lúc mua là Standard nhưng nay đã thành VIP" |
Định lý Bảo toàn Lịch sử SCD Type 2 & Độ méo Hồi tố SCD Type 1#
Với mỗi thực thể \(u\), bảng SCD Type 2 phân hoạch trục thời gian thành các khoảng nửa mở rời nhau \(I_{u,k} = [t_{\text{from}}^{(u,k)}, t_{\text{to}}^{(u,k)})\) sao cho với mọi giao dịch phát sinh tại \(t_{\text{tx}}\):
Tính duy nhất này bảo đảm phép Temporal Interval Join không bao giờ nhân đôi hay đánh rơi bất kỳ giao dịch nào (12,000 -> 12,000 dòng). Ngược lại, dùng SCD Type 1 (thay toàn bộ lịch sử bằng trạng thái cuối \(\text{tier}_{\text{latest}}(u)\)) gây ra Độ méo Doanh thu Lịch sử Hồi tố (Retroactive Historical Distortion):
Trong Lab 10 (test_03, 12,000 giao dịch, 180 khách nâng hạng), SCD Type 1 dịch chuyển oan 268,958.82 USD doanh thu Standard sang VIP, đẩy tổng sai lệch tuyệt đối lên 537,917.64 USD (34.15%), trong khi SCD Type 2 giữ sai số 0.0 USD (0.0%).
1.3 Động cơ OLAP Thời gian thực (ClickHouse vs. Apache Pinot) & Materialized Views#
Khi phục vụ bảng điều khiển tương tác thời gian thực (< 50 ms P99), PostgreSQL (lưu theo dòng, kéo cả bản ghi rộng vào buffer pool cho 1 phép SUM) và Trino trên Object Store (chi phí khởi tạo lịch trình và I/O S3 tính bằng giây) đều hụt hơi. Hai động cơ OLAP cột hàng đầu hiện nay giải quyết bài toán này theo hai kiến trúc bổ trợ nhau:
1. Giải phẫu ClickHouse MergeTree Family & Toán học Granule Pruning#
- Chỉ mục Thưa Chính (
Sparse Primary Index): Dữ liệu trong mỗi part được sắp xếp vật lý theo khóaORDER BY (k_1, k_2, ...). Thay vì đánh chỉ mục từng dòng như B-Tree (tốn hàng chục GB RAM), ClickHouse chia cột đã sắp xếp thành các Granule kích thước cố định \(G = 8{,}192\) dòng (index_granularity = 8192) và chỉ lưu 1 mốc đánh dấu (mark) vào tệpprimary.idxnằm thường trực trong RAM. Số mốc cho \(N\) dòng là \(N_g = \lceil N / G \rceil\). - Tỷ lệ Bỏ qua Granule (
Granule Skip Ratio): Nếu bộ lọcWHEREkhớp tiền tố đầu củaORDER BYvà chạm \(k_{\text{hit}}\) granules:\[\text{Scan Skip Ratio} = 1 - \frac{k_{\text{hit}} \cdot G}{N}, \qquad \text{Speedup}_{\text{granule}} = \frac{k_{\text{bad}} \cdot G}{k_{\text{hit}} \cdot G} = \frac{k_{\text{bad}}}{k_{\text{hit}}}\]Trên phân vùng \(N = 10{,}000{,}000\) dòng (\(N_g = 1{,}221\) granules,test_04), thiết kế đúngORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts)giúp truy vấn lọc 1 khách hàng/7 ngày chỉ đọc \(k_{\text{hit}} = 1\) granule (8,192dòng, bỏ qua99.92%bảng), nhanh hơn285.0xso với khóa ngây thơ đặt thời gian lên trướcORDER BY (tx_ts, customer_id)(\(k_{\text{bad}} = 285\) granules =2,334,720dòng)! ReplacingMergeTree(ver)& Bẫy Đọc Trước Compaction: Engine này sinh ra để khử trùng lặp các bản ghi CDC/Flink có cùng khóaORDER BY, giữ lại dòng mang phiên bảnverlớn nhất. Cạm bẫy chết người: Quá trình loại trùng chỉ chạy bất đồng bộ trong background merge. Truy vấnSELECT SUM(...)trực tiếp khi các part chưa hợp nhất sẽ tính đúp bản ghi cũ và mới! Trên5,000đơn hàng +900bản cập nhật trongLab 10(test_05),SELECTthô làm doanh thu phình+217,979.90 USD(+18.19%). Để đảm bảo độ chính xác tuyệt đối0.0 USD, luôn phải truy vấn quaargMax(col, ver) GROUP BY key(song song tối ưu) hoặc gắn từ khóaFINAL(hỗ trợ đa luồng từ ClickHouse 23.12+).AggregatingMergeTree+ IncrementalMATERIALIZED VIEW: Không giống View của Postgres chạy lại toàn bảng, Incremental Materialized View của ClickHouse là một bộ kích hoạt chèn (INSERT Trigger): mỗi lô dữ liệu mới chèn vào bảng gốc được gom trạng thái trung gian (sumState,countState,uniqStatetheo HyperLogLog) ngay lập tức và đổ vào bảng đíchAggregatingMergeTree. Khi đọc (sumMerge,uniqMerge), chi phí giảm từ \(O(N_{\text{raw}})\) xuống \(O(N_{\text{buckets}})\): trongLab 10, kích thước quét thu gọn240,000 -> 2,400dòng (100.0x) và rút thời gian10truy vấnDuckDBtừ344.08 msxuống28.35 ms(12.14xnhanh hơn).- Đột phá SOTA 2024–2026 (
ClickHouse Projections,Refreshable MV&SharedMergeTree):Projections: Cho phép lưu thêm thứ tự sắp xếp phụ hoặc bảng tổng hợp nhỏ ngay bên trong cùng Data Part, đồng bộ nguyên tử khi ghi và tự động được bộ tối ưu truy vấn chọn khi lọc theo cột phụ mà không cần duy trì bảng MV riêng biệt.Refreshable Materialized Views(REFRESH EVERY 5 MINUTE): Giải quyết các truy vấn tổng hợp phức tạp cóJOINđa bảng SCD Type 2 hoặc khử trùng lặpargMaxtrên bảngApache Iceberg/Delta Lakenguồn mà Incremental MV đơn bảng không hỗ trợ.SharedMergeTree: Đưa các data parts lên Object Storage (S3/GCS/MinIO) làm nguồn sơ cấp, biến NVMe cục bộ thành cache đọc phân tán và mở rộng compute chỉ trong vài giây.
2. Apache Pinot: Segment, Star-Tree Index & Realtime Kafka Upsert#
Khi kiến trúc hướng đến hàng chục nghìn truy vấn đồng thời mỗi giây (10k–50k QPS) trực tiếp từ ứng dụng người dùng cuối (User-Facing Analytics như bảng điều khiển tài xế Uber, đối tác Grab/Shopee hoặc LinkedIn Profile Views), Apache Pinot tỏa sáng nhờ:
- Cấu trúc Segment kép (
Offline+Realtime): Phân đoạn đang ghi (Realtime Segment) tiêu thụ trực tiếp từng sự kiện từApache Kafkatrên RAM, sau đó niêm phong thành phân đoạn cột nén bất biến (immutable columnar segment) và hợp nhất chu kỳ vớiOffline Segmentđẩy từ Spark/Iceberg. Star-Tree Index: Cấu trúc cây lai kết hợp phân tách theo danh sách chiều (dimensionsSplitOrder) và nút sao (*) tiền tổng hợp sẵn các thước đo. Nhờ tham số chặn trênmaxLeafRecords(ví dụ10,000), mọi truy vấn cắt lát đa chiều ở nút lá không bao giờ quét quámaxLeafRecordsdòng — khóa chặt độ trễ P99< 20 msbất kể bảng phình lên hàng chục tỷ dòng.- Native Realtime Upsert & Hệ Chỉ mục Đa lớp: Hỗ trợ đồng thời
Inverted Index(tìm kiếm điều kiện đẳng thức tức thời),Range Index,JSON Index, và Upsert gốc thông qua bảng băm ánh xạ khóa chính \(\to\) vị trí tài liệu hợp lệ mới nhất trênBitMap, loại bỏ hiện tượng phình trùng lặp khi nhận luồng CDC/Flink.
1.4 Kiến trúc Cốt lõi của Feature Store (Feast)#
Tại sao Data Warehouse / OLAP vẫn chưa đủ cho Học máy Sản xuất? Vì bảng OLAP không tự động giải quyết chống rò rỉ tương lai theo từng mốc mili-giây của hàng triệu nhãn huấn luyện, và bảng OLAP cũng không sinh ra để chịu tải tra cứu theo khóa đơn lẻ (1–5 ms, 20k QPS) tại bước suy luận trực tuyến. Feast (Feature Store mã nguồn mở chuẩn mực) nối liền khoảng trống này qua 4 lớp thành phần:
- Entity & Feature Core (
Feature Registry):Entityđịnh danh thực thể cốt lõi (customer_id), là khóa nối bất biến xuyên suốt từ bảng nhãn ngoại tuyến đến kho KV trực tuyến. Toàn bộ lược đồ đặc trưng (Entity,DataSource,FeatureView,OnDemandFeatureView) được định nghĩa dưới dạng mã Python (Feature-as-Code) và quản lý phiên bản quafeast apply. - Feature View Design:
BatchFeatureView/FeatureView: Ánh xạ nguồn lịch sử (FileSource,ClickHouseSource,BigQuerySource) kèm danh sách trường dữ liệu (Field) và ngưỡng hết hạnttl(Time-to-Live) bắt buộc để chặn đặc trưng lỗi thời.StreamFeatureView/PushSource: Nhận đặc trưng vận tốc tính từ Kafka/Flink và hỗ trợ ghi song song (dual-write quaPushMode.ONLINE_AND_OFFLINE) cả Offline lẫn Online với độ trễ dưới vài giây.OnDemandFeatureView: Biến đổi thời điểm yêu cầu (request-time transforms), kết hợp đặc trưng lấy từ kho vớiRequestSourcechứa tham số tức thời trong request API (nhưamount_usdcủa giao dịch đang thanh toán).
- Ba Chế độ Biến đổi Đặc trưng (
Feature Transformations):- Batch Pre-Computation: Tính các đặc trưng chậm (
acct_age_days,amount_ewma_30d) qua Spark/DuckDB/ClickHouse và đẩy sang Online Store định kỳ bằngfeast materialize-incremental. - Streaming Incremental Aggregates: Tính đặc trưng cửa sổ ngắn (
tx_velocity_1h,tx_count_5m) bằng Flink (Chương 10) rồi gọistore.push(...)vàoPushSource. - On-Demand Request-Time Transforms: Thực thi phép chia tỷ lệ, chuẩn hóa phi tuyến (\(\ln(1 + x)\)) hoặc ghép ngữ cảnh ngay tại thời điểm truy xuất mà dùng chung một hàm Python cho cả Training lẫn Serving.
- Batch Pre-Computation: Tính các đặc trưng chậm (
- Dual-Store & ML Integration: Offline Store (
DuckDB/ClickHouse/Snowflake/Parquet) lưu toàn bộ lịch sử để tạo tập huấn luyện (get_historical_featuresdùng Point-in-TimeASOF JOIN); Online Store (Redis/DynamoDB/PostgreSQL) chỉ lưu giá trị mới nhất của mỗientity_idđể suy luận (get_online_features).
1.5 Chuyên đề Sâu #15 (Deep-Dive Article #15): Point-in-Time Features & Chống Rò rỉ Tương lai (Look-Ahead Leakage)#
4 Trụ cột Chuẩn hóa của Deep-Dive Article #15: (1) Tình huống Thất bại Thực tế (
Failure Case); (2) Mô hình Toán học Nhân quả (Formal Model); (3) Thực nghiệm Ablation Kiểm chứng (Lab 10); (4) Bảng Quyết định Sản xuất (Production Decision Playbook).
1. Tình huống Thất bại Kinh điển (Concrete Failure Case)#
Trong bài toán chống gian lận thẻ thanh toán:
- Tại \(t_{\text{label}} = \text{10:00:00}\), kẻ gian quẹt thẻ trái phép với vận tốc trước giao dịch cao (
tx_velocity_1h = 4.8) nhưng lúc này tài khoản chưa hề cóchargeback_flag_count. - 2 giờ sau (\(t_{\text{post}} = \text{12:00:00}\)), hệ thống hậu kiểm phát hiện bất thường, khóa thẻ (khiến
tx_velocity_1htụt về0.05) và đánh dấuchargeback_flag_count = 2. - Sai lầm chí mạng: Kỹ sư dùng phép nối ngây thơ
Naive Latest-Window Join(lấy ảnh chụp mới nhất cuối ngày hoặc trong cửa sổ[t_label - 6h, t_label + 6h]). Phép nối này kéo dữ liệu tương lai \(t_{\text{post}} > t_{\text{label}}\) ghép ngược vào mẫu huấn luyện lúc10:00:00! - Hệ quả kép (
Offline Mirage -> Production Collapse): Mô hìnhLogisticRegressionđặt trọng số khổng lồ vàochargeback_flag_countvà thậm chí học trọng số âm sai lệch chotx_velocity_1h(vì sau khi khóa thẻ vận tốc bị ép về0!). Khi chấm kiểm định trên bảng có rò rỉ, mô hình khoe chiến tíchROC-AUC = 0.9853(PR-AUC = 0.9752); nhưng ngay khi đưa lên API phục vụ thực tế lúc10:00(True Causal OOT Serving, nơi tương lai chưa xảy ra!),ROC-AUCsụp đổ xuống0.5143(tụt-0.4710AUC — gần như đoán bừa!).
2. Mô hình Toán học Truy xuất Nhân quả Point-in-Time ASOF & Ràng buộc TTL#
Cho nhãn \((e_i, t_{\text{label}, i}, y_i)\) và chuỗi lịch sử đặc trưng \(\mathcal{F}(e_i) = \{(t_j, \mathbf{x}_j)\}\). Dấu thời gian đặc trưng hợp lệ duy nhất phải thỏa mãn Bất biến Nhân quả (Causality) lẫn Ràng buộc Độ tươi (Freshness TTL):
- Nếu tập ứng viên rỗng (không có bản ghi quá khứ hoặc bản ghi gần nhất đã già hơn
TTL), vector đặc trưng BẮT BUỘC trả về \(\bot\) (NULL). Tuyệt đối không được vay mượn bản ghi \(t_j > t_{\text{label}, i}\) hoặc "đào mộ" snapshot quá hạnTTL. - Tỷ lệ Rò rỉ Tương lai (
Future-Leakage Rate):\[\rho_{\text{leak}} = \frac{1}{N} \sum_{i=1}^{N} \mathbb{I}\!\left[t_{\text{feat}, i} > t_{\text{label}, i}\right]\] - Độ phức tạp Thuật toán
ASOF JOIN: Thay vì tự nối bình phương \(O(N \cdot M)\) hay phân cửa sổROW_NUMBER()tốn \(O((N+M)\log(N+M))\) bộ nhớ đệm,DuckDB 2.0vàClickHousecài đặtASOF LEFT JOINbằng thuật toán quét hai con trỏ trên phân vùng đã sắp xếp (Sort-Merge Two-Pointer Scan), đạt độ phức tạp \(O(N \log N + M \log M)\) cho bước sắp xếp (hoặc \(O(N + M)\) nếu đã sắp sẵn trên ClickHouseORDER BY (customer_id, feat_ts)!).
1.6 Đồng nhất Huấn luyện–Phục vụ (Training–Serving Parity) & 4 Nguồn gốc Skew#
Ngăn rò rỉ tương lai mới chỉ giải quyết nửa chặng đường của Article #15. Nửa còn lại là bảo đảm cùng một thực thể tại cùng một thời điểm nhận được vector đặc trưng giống hệt nhau giữa Offline Training và Online Serving:
Trong đó \(\tau_{\text{tol}} = 10^{-6}\) cho số thực và \(\Delta_{\text{NULL}}\) là số lượng sai lệch mặt nạ giá trị thiếu. Ngoài chỉ số kiểm tra từng điểm, đội MLOps còn theo dõi phân phối đặc trưng tổng thể giữa tập Offline và luồng Online bằng Population Stability Index (PSI):
Khi \(\text{PSI} > 0.25\) hoặc \(\epsilon_{\text{parity}} > 10^{-6}\), hệ thống kích hoạt cảnh báo Training–Serving Skew từ 4 nguyên nhân gốc rễ:
- Viết lại phép biến đổi ở hai ngôn ngữ/dịch vụ khác nhau: Ví dụ Offline chạy \(\ln(1 + \text{amount}/\text{ewma})\) nhưng API trực tuyến viết nhầm thành
amount / 100.0(như nhánhBrokentrongLab 10, khiến500 / 500request sai lệch tớimax_abs_diff = 4.789989). - Bất nhất hạn
TTLvà xử lýNULL: OfflineASOFtrả vềNULLkhi hết hạnTTL = 3,600s, nhưng Redis Online quên đặtEXPIREnên vẫn phục vụ giá trị cũ từ tuần trước (48 / 500lỗi lệchTTLtrongLab 10). - Lệch múi giờ & cắt cửa sổ (
Timezone / Truncation Drift): Offline nhóm theoUTCcòn Online cắt cửa sổ theo giờ địa phương. - Hỏng đồng bộ Backfill: Sửa lỗi lịch sử ở Offline Store nhưng quên phát lại lên Online Store.
Principal Industrial Tip #15c — Online/Offline Feature Parity,
ASOF JOIN,ClickHouse DataLakeCatalog& Serving Tail-Latency SLA (2025–2026):
- Đánh đổi kiến trúc giữa
Dual-Write(PushSource) vàCDC Backfill:PushSourceghi song song tới Redis Online và Offline Store đạt độ tươi< 1s, nhưng rất dễ tạo Split-Brain Skew khi Redis ghi thành công mà lô Parquet/Iceberg Offline rớt giữa đường (hoặc ngược lại khi chạy backfill lịch sử chỉ đổ vào Offline mà quên đẩy Redis). Trong sản xuất 2025–2026 (kiểuFeast+FlinkhoặcTectondeclarative PIT engine), mọi cập nhật trạng thái phải đi qua một nguồn chân lý bất biến (Kafka/Delta/Iceberg) gắn cùngevent_ts+created_ts; tuyệt đối không gọi hai lệnh ghi rời không giao dịch khi chạy backfill lịch sử!- Cạm bẫy
ASOF JOINtrên dữ liệu đến trễ (Late-Arriving Features): Nếu bảng đặc trưng Offline không tách biệtevent_ts(thời điểm hành vi xảy ra) vàcreated_ts(thời điểm pipeline thực sự ghi nhận xong đặc trưng), phépASOF JOINsẽ nhặt các giá trị đến muộn mà hệ thống suy luận trực tuyến lúct_labelthực tế chưa hề nhìn thấy. Với mô hình tài chính/gian lận nhạy cảm, hãy nối Point-in-Time theocreated_ts <= t_labelhoặc kết hợp cửa sổ watermark từ Flink (Chương 10) để tránh ảo giác dữ liệu ngoại tuyến.- Liên kết Zero-ETL Bằng
ClickHouse DataLakeCatalogvs. Tiêu thụMergeTreeCục bộ: Thay vì sao chép hàng chục TB lịch sử từ Iceberg/Delta vào đĩa cục bộ ClickHouse chỉ cho truy vấn khám phá hoặc nạp Offline PIT,ClickHouse DataLakeCatalogkết nối trực tiếpApache Polaris,Unity CataloghoặcAWS GlueREST Catalog để đọc thẳng Parquet trên S3 theo đúng snapshot ACID. Đánh đổi & Chế độ Lỗi: đọc trực tiếp quaDataLakeCatalogchịu độ trễS3 GET(100–500 ms+) và không có chỉ mục thưaprimary.idxhay Incremental MV của ClickHouse cục bộ — trỏ dashboard> 500 QPSthẳng vào bảng Lakehouse lạnh sẽ gây bão S3429 SlowDownvà vỡSLA P99 < 50 ms; mô hình chuẩn là giữ dữ liệu lạnh trênClickHouse DataLakeCatalogvà chỉ kết tinh cửa sổ nóng (30–90ngày) + MV vàoMergeTreecục bộ.- Bảo vệ Tail-Latency SLA (
P99 < 10 ms) tại Online Serving: Luôn khóa chặtentity_key_serialization_version: 3trongFeast, đặt Redis--maxmemory-policy volatile-ttlkhớpTTLcủaFeatureView(tránh Redis hết RAM âm thầm evict khóa đang nóng hoặc giữ khóa hết hạn), gộp tra cứu đa đặc trưng bằngRedis MGET/ pipelining, và đo shadow-replay tự động hàng đêm (OpenTelemetryspans + Parity Auditor \(\epsilon_{\text{parity}} \le 10^{-6}\)).
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất: Tích hợp ClickHouse + Feast Dual-Store & Cẩm nang Quyết định#
2.1 Kiến trúc Tham chiếu Dual-Store Feast + ClickHouse + Redis Kèm Parity Gate#
Ngân sách Hiệu năng & Độ tin cậy Sản xuất (SLOs)#
| Thành phần Tầng Tiêu thụ | Độ trễ Mục tiêu (P99) |
Thông lượng Mục tiêu | Ngân sách RAM / Lưu trữ & Bảo vệ |
|---|---|---|---|
ClickHouse BI + Incremental MV |
< 30–50 ms |
500 – 5,000 QPS |
Sparse primary.idx trong RAM (~1 MB / 10M dòng), MV cắt 100x I/O quét |
Apache Pinot User-Facing OLAP |
< 20 ms |
5,000 – 50,000 QPS |
Star-Tree Index giới hạn lá <= 10,000 dòng/segment |
Redis Online Feature Store |
< 5–10 ms |
10,000 – 100,000 QPS |
Bắt buộc --maxmemory-policy volatile-ttl và đồng bộ TTL theo FeatureView |
DuckDB / ClickHouse Offline PIT |
100 ms – 10 s (theo lô 10k–10M) |
Batch Training & Backfill | Thuật toán ASOF LEFT JOIN + phân vùng theo ngày, bảo đảm \(\rho_{\text{leak}} = 0\) |
2.2 Cẩm nang Quyết định Sản xuất (Production Decision Playbook) — Deep-Dive Article #15 & R33#
| Câu hỏi Kiến trúc | Khi nào Chọn Phương án A | Khi nào Chọn Phương án B | Ngưỡng / Điều kiện Quyết định |
|---|---|---|---|
| Star Schema vs. OBT | Star Schema (SCD2): Khi cần Conformed Dimensions dùng chung đa phòng ban và chiều cập nhật liên tục |
OBT: Khi cần dashboard OLAP tốc độ cực đại không JOIN |
Sinh bảng OBT tự động từ nguồn SCD Type 2; cấm dùng SCD Type 1 |
ClickHouse vs. Apache Pinot |
ClickHouse: Phân tích đa năng, truy vấn phức tạp, nén cột cực cao, ASOF JOIN, đọc trực tiếp Iceberg |
Apache Pinot: Dashboard người dùng cuối tải siêu cao (> 10k QPS) và upsert theo khóa chính từ Kafka |
Dựa trên đỉnh QPS đồng thời và độ phức tạp ad-hoc SQL |
| Incremental MV vs. Refreshable MV | Incremental MV (AggregatingMergeTree): Cộng dồn đơn bảng (SUM, COUNT, uniqState) cập nhật tức thời lúc INSERT |
Refreshable MV: Phép tính cần JOIN đa bảng SCD2, argMax đa phần tử hoặc tái tính định kỳ 5–15 phút |
Incremental đạt độ trễ dưới giây; Refreshable xử lý logic liên bảng |
Batch materialize vs. PushSource |
Batch materialize: Đặc trưng thay đổi chậm (hồ sơ ngày, acct_age_days, amount_ewma_30d) |
Streaming PushSource: Đặc trưng vận tốc nhạy gian lận (tx_velocity_1h, cửa sổ 5 phút) |
Ràng buộc độ tươi dữ liệu (Freshness SLA < 10s vs 1–24h) |
Pre-computed vs. OnDemandFeatureView |
Pre-computed (FeatureView): Đặc trưng lịch sử chỉ phụ thuộc thực thể đã biết trước thời điểm gọi API |
OnDemandFeatureView: Cần kết hợp giá trị trong kho với tham số tức thời của request (amount_usd) |
Bắt buộc dùng OnDemandFeatureView để chia sẻ 1 hàm duy nhất tránh Skew |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Khả thi (ClickHouse SQL, Feast 0.40 & DuckDB 2.0 ASOF)#
3.1 Lược đồ ClickHouse 24.8: SCD2, ReplacingMergeTree, AggregatingMergeTree MV & ASOF JOIN#
Tệp sql/01_clickhouse_star_scd2_mv.sql trong Lab 10 (được kiểm toán tự động tại test_12) cài đặt trọn vẹn các mẫu thiết kế OLAP chuẩn sản xuất:
-- 1. Bảng tổng hợp AggregatingMergeTree + Incremental Materialized View
CREATE TABLE IF NOT EXISTS consumption_olap.agg_hourly_customer_stats (
customer_id String,
hour_bucket DateTime('UTC'),
tx_count_state AggregateFunction(count, String),
revenue_state AggregateFunction(sum, Float64),
uniq_merchants AggregateFunction(uniq, String)
) ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(hour_bucket)
ORDER BY (customer_id, hour_bucket);
CREATE MATERIALIZED VIEW IF NOT EXISTS consumption_olap.mv_hourly_customer_stats
TO consumption_olap.agg_hourly_customer_stats AS
SELECT customer_id, toStartOfHour(tx_ts) AS hour_bucket,
countState(tx_id) AS tx_count_state,
sumState(amount_usd) AS revenue_state,
uniqState(merchant_id) AS uniq_merchants
FROM consumption_olap.fact_transactions
GROUP BY customer_id, hour_bucket;
-- 2. Truy vấn Point-in-Time ASOF LEFT JOIN với ràng buộc TTL = 3600s trên ClickHouse
SELECT f.tx_id, f.customer_id, f.tx_ts,
IF(dateDiff('second', h.feat_ts, f.tx_ts) <= 3600, h.tx_velocity_1h, NULL) AS tx_velocity_1h
FROM consumption_olap.fact_transactions AS f
ASOF LEFT JOIN consumption_olap.customer_risk_features_history AS h
ON f.customer_id = h.customer_id AND f.tx_ts >= h.feat_ts;
3.2 Kho Đặc trưng Feast Hợp nhất (feast_repo/features.py) & DuckDB 2.0 ASOF JOIN#
Bí quyết triệt tiêu Training–Serving Skew là tách hàm biến đổi toán học thuần túy (compute_shared_risk_features) để dùng chung cả trong OnDemandFeatureView của Feast lẫn động cơ huấn luyện DuckDB/Polars (test_10, test_14, test_15):
def compute_shared_risk_features(
tx_velocity_1h: float | None,
amount_usd: float,
amount_ewma: float | None,
chargeback_flag_count: float | None,
) -> dict[str, float | None]:
if tx_velocity_1h is None or amount_ewma is None or chargeback_flag_count is None:
return {"log_amount_ratio": None, "risk_velocity_score": None, "is_high_velocity_burst": None}
log_amount_ratio = round(math.log1p(max(0.0, amount_usd) / max(1.0, amount_ewma)), 8)
risk_velocity_score = round(0.55 * math.log1p(max(0.0, tx_velocity_1h)) + 0.45 * max(0.0, chargeback_flag_count), 8)
is_high_velocity_burst = 1.0 if tx_velocity_1h >= 4.0 else 0.0
return {
"log_amount_ratio": log_amount_ratio,
"risk_velocity_score": risk_velocity_score,
"is_high_velocity_burst": is_high_velocity_burst,
}
Và phía động cơ ngoại tuyến DuckDB 2.0 (src/feast_olap_pit_lab/pit_feature_store.py) thực thi chính xác truy vấn ASOF LEFT JOIN kèm khóa hạn TTL:
SELECT l.label_id, l.customer_id, l.event_ts, l.amount_usd, l.is_fraud, f.feat_ts,
CASE WHEN f.feat_ts IS NOT NULL AND EPOCH(l.event_ts) - EPOCH(f.feat_ts) <= 3600
THEN f.tx_velocity_1h ELSE NULL END AS tx_velocity_1h
FROM read_parquet('fraud_labels.parquet') AS l
ASOF LEFT JOIN read_parquet('customer_risk_features.parquet') AS f
ON l.customer_id = f.customer_id AND l.event_ts >= f.feat_ts;
Khai báo kho đặc trưng hoàn chỉnh, chạy độc lập 100% trong feast_repo/features.py (tương thích cả cụm Feast 0.40+ lẫn kiểm định cục bộ trên .venv Python 3.12+ không cài feast) bảo đảm 0% sai lệch giữa Training và Serving:
from __future__ import annotations
import math
from dataclasses import dataclass, field as dataclass_field
from datetime import timedelta
from typing import Any, Callable
import pandas as pd
FEATURE_TTL_SECONDS = 3600
try:
from feast import ( # type: ignore[import-not-found]
Entity,
FeatureView,
Field,
FileSource,
PushSource,
RequestSource,
ValueType,
)
from feast.on_demand_feature_view import ( # type: ignore[import-not-found]
on_demand_feature_view,
)
from feast.types import Float64, Int64 # type: ignore[import-not-found]
except ImportError:
# Shim nhẹ giúp chạy/kiểm định logic OnDemandFeatureView hoàn toàn cục bộ khi không cài feast
class ValueType: # type: ignore[no-redef]
STRING = "STRING"
Float64 = "Float64"
Int64 = "Int64"
@dataclass
class Field: # type: ignore[no-redef]
name: str
dtype: Any
@dataclass
class Entity: # type: ignore[no-redef]
name: str
join_keys: list[str]
value_type: Any = ValueType.STRING
description: str = ""
@dataclass
class FileSource: # type: ignore[no-redef]
name: str
path: str
timestamp_field: str
@dataclass
class PushSource: # type: ignore[no-redef]
name: str
batch_source: FileSource
@dataclass
class RequestSource: # type: ignore[no-redef]
name: str
schema: list[Field] = dataclass_field(default_factory=list)
@dataclass
class FeatureView: # type: ignore[no-redef]
name: str
entities: list[Entity]
ttl: timedelta
schema: list[Field]
online: bool
source: PushSource
tags: dict[str, str] = dataclass_field(default_factory=dict)
def on_demand_feature_view( # type: ignore[no-redef]
*, sources: list[Any], schema: list[Field]
) -> Callable[[Callable[[pd.DataFrame], pd.DataFrame]], Callable[[pd.DataFrame], pd.DataFrame]]:
def _decorator(fn: Callable[[pd.DataFrame], pd.DataFrame]) -> Callable[[pd.DataFrame], pd.DataFrame]:
fn.sources = sources # type: ignore[attr-defined]
fn.schema = schema # type: ignore[attr-defined]
return fn
return _decorator
def compute_shared_risk_features(
tx_velocity_1h: float | None,
amount_usd: float,
amount_ewma: float | None,
chargeback_flag_count: float | None,
) -> dict[str, float | None]:
if tx_velocity_1h is None or amount_ewma is None or chargeback_flag_count is None:
return {
"log_amount_ratio": None,
"risk_velocity_score": None,
"is_high_velocity_burst": None,
}
log_amount_ratio = round(math.log1p(max(0.0, amount_usd) / max(1.0, amount_ewma)), 8)
risk_velocity_score = round(
0.55 * math.log1p(max(0.0, tx_velocity_1h)) + 0.45 * max(0.0, chargeback_flag_count),
8,
)
is_high_velocity_burst = 1.0 if tx_velocity_1h >= 4.0 else 0.0
return {
"log_amount_ratio": log_amount_ratio,
"risk_velocity_score": risk_velocity_score,
"is_high_velocity_burst": is_high_velocity_burst,
}
customer = Entity(
name="customer_id",
join_keys=["customer_id"],
value_type=ValueType.STRING,
description="Canonical customer identifier shared across offline and online stores.",
)
customer_risk_batch_source = FileSource(
name="customer_risk_features_parquet_source",
path="data/customer_risk_features.parquet",
timestamp_field="feat_ts",
)
customer_risk_push_source = PushSource(
name="customer_risk_features_push_source",
batch_source=customer_risk_batch_source,
)
tx_request_source = RequestSource(
name="transaction_request_context",
schema=[Field(name="amount_usd", dtype=Float64)],
)
customer_risk_fv = FeatureView(
name="customer_risk_features",
entities=[customer],
ttl=timedelta(seconds=FEATURE_TTL_SECONDS),
schema=[
Field(name="tx_velocity_1h", dtype=Float64),
Field(name="amount_ewma", dtype=Float64),
Field(name="chargeback_flag_count", dtype=Int64),
Field(name="acct_age_days", dtype=Float64),
],
online=True,
source=customer_risk_push_source,
tags={"team": "risk-ml", "article": "deep-dive-15"},
)
@on_demand_feature_view(
sources=[customer_risk_fv, tx_request_source],
schema=[
Field(name="log_amount_ratio", dtype=Float64),
Field(name="risk_velocity_score", dtype=Float64),
Field(name="is_high_velocity_burst", dtype=Float64),
],
)
def transformed_risk_features(inputs: pd.DataFrame) -> pd.DataFrame:
rows = [
compute_shared_risk_features(
tx_velocity_1h=float(row["tx_velocity_1h"]) if pd.notna(row["tx_velocity_1h"]) else None,
amount_usd=float(row["amount_usd"]),
amount_ewma=float(row["amount_ewma"]) if pd.notna(row["amount_ewma"]) else None,
chargeback_flag_count=(
float(row["chargeback_flag_count"])
if pd.notna(row["chargeback_flag_count"])
else None
),
)
for _, row in inputs.iterrows()
]
return pd.DataFrame(rows)
if __name__ == "__main__":
sample_inputs = pd.DataFrame(
[
{"tx_velocity_1h": 5.2, "amount_usd": 450.0, "amount_ewma": 90.0, "chargeback_flag_count": 1.0},
{"tx_velocity_1h": 1.5, "amount_usd": 40.0, "amount_ewma": 80.0, "chargeback_flag_count": 0.0},
{"tx_velocity_1h": None, "amount_usd": 120.0, "amount_ewma": 60.0, "chargeback_flag_count": 0.0},
]
)
out = transformed_risk_features(sample_inputs)
expected_0 = compute_shared_risk_features(5.2, 450.0, 90.0, 1.0)
assert list(out.columns) == ["log_amount_ratio", "risk_velocity_score", "is_high_velocity_burst"]
assert abs(float(out.loc[0, "log_amount_ratio"]) - float(expected_0["log_amount_ratio"] or 0.0)) <= 1e-9
assert out.loc[0, "is_high_velocity_burst"] == 1.0
assert out.loc[1, "is_high_velocity_burst"] == 0.0
assert pd.isna(out.loc[2, "log_amount_ratio"])
print("Pillar 3 transformed_risk_features parity check PASSED:", out.to_dict(orient="records"))
3.3 Thực chiến Ngành & Bài học Quy mô Lớn (Industry Case Studies)#
- Cloudflare & PostHog (
ClickHouseSparse Index & Incremental MV): Đảo khóa sắp xếp thành(tenant_id, toStartOfHour(ts), ts)để bỏ qua> 98%granules khi lọc từng khách hàng, đồng thời dùngAggregatingMergeTree(uniqState,sumState) giữ bảng điều khiển tỷ dòng ở mức< 50 ms. - Uber Michelangelo & DoorDash (
Point-in-Time ASOFChống Rò rỉ Gian lận & ETA): Cấm hoàn toàn phép nốidaily snapshottheo ngày; mọi pipeline huấn luyện đều phải qua truy vấn time-travelt_feat <= t_labelvà kiểm định chặt trên tập holdout Out-of-Time (OOT). - Tín dụng Số Fintech (
Feast OnDemandFeatureView& Đêm Kiểm toán Parity): Gỡ bỏ dịch vụ tính đặc trưng viết tay bằng Java tách khỏi code Python huấn luyện, hợp nhất vềOnDemandFeatureView+Redis TTLđồng bộ và chạy Parity Auditor (<= 1e-6) mỗi ngày để cắt hoàn toàn sụt giảm chất lượng ngầm.
Trụ cột 4 — Thực hành Công nghiệp (Lab 10: feast_olap_pit_lab) & Bảng Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Của Lab 10 (labs/lab-10-feast-clickhouse-pit-feature-store/)#
-
Tầng 1 — Tạo tác Triển khai
ClickHouse+Redis+PostgreSQL+FeastThật (Kiểm toán tĩnh tronginfra_audit.py):docker-compose.yml:4dịch vụ gắn tag cố định (clickhouse/clickhouse-server:24.8-alpine,redis:7.4-alpine,postgres:16.4-alpine,feastdev/feature-server:0.40.1), đầy đủhealthcheck,depends_on: condition: service_healthy, mạng cô lậpconsumption_net, giới hạn CPU/RAM và biến môi trường mặc định.sql/01_clickhouse_star_scd2_mv.sql:6/6kiểm toán DDL (dim_customer_scd2,MergeTreeindex_granularity = 8192,ReplacingMergeTree(ver)+argMax,AggregatingMergeTree+MATERIALIZED VIEW,ASOF LEFT JOIN).configs/feature_store.yaml&feast_repo/features.py:5/5kiểm toán Feast YAML (Redisonline,DuckDBoffline,entity_key_serialization_version: 3,on_demand_transforms) và kiểm toán AST (Entity,PushSource,RequestSource,FeatureViewgắnttl=3600s,OnDemandFeatureView,0unsafe imports).
-
Tầng 2 — Động cơ
DuckDB 2.0.1+Polars 2.1.0+scikit-learn 1.9.1+OpenTelemetry SDK 1.45.2100% Offline (0Tệp.parquet/.duckdb*Rác): Chạy toàn bộ trên Python3.12dùngtempfile.TemporaryDirectory(), phát5spans đo đạc OpenTelemetry SDK thật (TracerProvider+SimpleSpanProcessor+InMemorySpanExporter), xuất duy nhất báo cáo kiểm chứng tạiartifacts/t2_ch11_lab10_results.json(6KPIs,4biểu đồ thanh,4bảng,otel_telemetry).
Danh sách 17 Kiểm thử Nghiệm thu (tests/test_feast_olap_pit_lab.py)#
| Nhóm Kiểm thử | Mã Test (pytest) |
Bất biến Kỹ thuật Được Xác minh Tự động |
|---|---|---|
| Bảo mật AST & Sinh Dữ liệu Star | test_01, test_02 |
Cấm pickle/joblib/cloudpickle/dill/shelve/marshal; sinh tất định 12,000 tx & 600 khách hàng (180 nâng hạng Standard -> VIP) |
SCD Type 1 vs. SCD Type 2 (DuckDB) |
test_03 |
SCD Type 1 méo 537,917.64 USD (34.15%, 268,958.82 USD Standard \(\to\) VIP); SCD Type 2 đạt 0.0 USD (0.0%) |
ClickHouse MergeTree, MV & Dedup |
test_04, test_05 |
Bỏ qua 99.92% granules (285.0x); AggregatingMergeTree MV giảm quét 100.0x (240k -> 2.4k) & nhanh 12.14x; ReplacingMergeTree argMax 0.0 USD vs +18.19% chưa merge |
Article #15: ASOF JOIN & TTL |
test_06–test_08 |
Sinh 16,300 snapshots & 2,400 nhãn; Naive rò rỉ 81.75% (1,962/2,400) vs DuckDB ASOF 0.0%; đẩy 232 mẫu quá hạn TTL=3600s về NULL |
| ML Leakage Mirage & Parity Gate | test_09, test_10 |
Naive 0.9853 Mirage \(\to\) 0.5143 OOT (-0.4710); PIT 0.8953 CV \(\to\) 0.8858 OOT (+0.3715 thắng Naive); Parity Unified 100.0% (0.0 lệch) vs Broken 0.0% |
| Hạ tầng, Shared Kernel, CLI & OTel | test_11–test_17 |
Kiểm toán Compose (4 services), ClickHouse SQL (6/6), Feast YAML (5/5), Feast AST, OnDemand determinism, schema 6/4/4, 5 spans OpenTelemetry SDK (InMemorySpanExporter), 0 tệp .parquet/.duckdb* rác |
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch11_lab10_results.json)#
Thực nghiệm (feast_olap_pit_lab) |
Thông số Đo được (Xác định, seed=42) |
Bất biến Được Chứng minh |
|---|---|---|
SCD Type 1 vs. SCD Type 2 (DuckDB) |
Tổng 1,575,346.92 USD: SCD1 méo 537,917.64 USD (34.15%); SCD2 sai số 0.0 USD (0.0%) |
Chỉ SCD Type 2 bảo toàn sự thật lịch sử |
ClickHouse Granule Pruning (10M, G=8,192) |
Good ORDER BY: 1 granule (8,192 dòng, 99.92% skip) vs Bad key: 285 granules (2,334,720 dòng) |
Khóa chính tốt giảm 285.0x dữ liệu đọc |
AggregatingMergeTree MV (240k, DuckDB) |
Dòng quét 240,000 -> 2,400 (100.0x), độ trễ 10 truy vấn 344.08 -> 28.35 ms (12.14x) |
Tiền tổng hợp lúc ghi khớp 100% bảng thô |
ReplacingMergeTree(ver) CDC Dedup |
Chưa merge: 1,416,082.78 USD (+217,979.90 USD = +18.19%); argMax: 0.0 USD sai số |
Tránh đọc trùng trên part chưa merge |
Point-in-Time DuckDB ASOF + TTL=3600s |
Naive rò rỉ 81.75% (1,962/2,400); PIT ASOF: 0.0% (0 mẫu), 232 quá hạn TTL \(\to\) NULL |
Loại bỏ 100% Look-Ahead Leakage & stale data |
Fraud ML Ablation (OOT Serving) |
Naive: 0.9853 \(\to\) 0.5143 OOT (-0.4710); PIT ASOF: 0.8953 CV \(\to\) 0.8858 OOT (+0.3715) |
PIT đánh bại hoàn toàn mô hình rò rỉ ngoài thực tế |
Offline–Online Parity (500 requests) |
Broken code: 0.0% pass (500 vi phạm, 48 lỗi TTL); Unified Feast: 100.0% (0.0 lệch) |
Chia sẻ 1 hàm OnDemandFeatureView + đồng bộ TTL |
OpenTelemetry Telemetry (InMemorySpanExporter) |
span_count = 5: lab10.olap.scd1_vs_scd2_audit, clickhouse_mergetree_mv, duckdb_asof_join, offline_online_parity, benchmark.suite |
Đo đạc thực chứng đầy đủ thuộc tính span qua OTel SDK |
4.3 Quy trình Kiểm định Tự động (17/17 pytest)#
cd 03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-10-feast-clickhouse-pit-feature-store
python scripts/run_lab_demo.py --tx 12000 --labels 2400 --seed 42 --output artifacts/t2_ch11_lab10_results.json
ruff check src tests scripts feast_repo
mypy src
pytest -p no:cacheprovider -v
Trụ cột 5 — Danh mục Tài liệu SOTA & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#
- Kimball, R. & Ross, M. (2013). "The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling (3rd Ed.)." — Kinh thánh về
Star Schema,Conformed Dimensions, vàSCD Types 0–6. - Schulze, R. et al. / ClickHouse Team (2024). "ClickHouse: Lightning Fast Analytics for Everyone" &
SharedMergeTreeArchitecture. VLDB / ClickHouse Engineering Docs. — Giải phẫuMergeTreesparse primary index (8,192-row granules),ReplacingMergeTree,AggregatingMergeTreeIncremental Materialized Views và kiến trúc tách rời compute–storage. - Im, J.-F. et al. / LinkedIn (2018–2025). "Pinot: Realtime Distributed OLAP Datastore" & Star-Tree Indexing. ACM SIGMOD. — Cách
Apache Pinotđảm bảo độ trễ< 20 msP99 ở> 10k QPSbằng cấu trúc Segment, Inverted/Star-Tree index và Realtime Upsert. - Huyen, C. (2022–2025) & Feast Community. "Designing Machine Learning Systems" + "Feast Feature Store Architecture: Point-in-Time Joins & On-Demand Feature Views". — Nền tảng lý thuyết của Deep-Dive Article #15 về rò rỉ tương lai và Training–Serving Parity.
- Raasveldt, M. & Mühleisen, H. / DuckDB Labs (2024–2026). "Vectorized
ASOF JOINExecution inDuckDB". — Thực thi phép nối Point-in-Time nhân quả tốc độ cao hoàn toàn nội bộ trên Parquet không cần cụm Spark nặng nề.
5.2 Sáu Bài tập Tự luận & Thực hành (ex1 – ex6) Kèm Thang điểm (Grading Rubric)#
-
Bài tập 1 (
ex1, 15%) — Mô hình hóa Đa chiều &SCD Type 1vs.SCD Type 2: Dẫn xuất bất biến khoảng hiệu lực \([t_{\text{from}}, t_{\text{to}})\) củaSCD Type 2và công thức độ méo lịch sử \(\Delta R_{\text{SCD1}}(c)\); giải thích vì sao trên12,000giao dịch của Lab 10 (test_03),SCD Type 1làm dịch chuyển268,958.82 USD(537,917.64 USDtổng sai lệch =34.15%) cònSCD Type 2đạt0.0 USD. Thang điểm: Đúng toán học khoảng SCD2 & công thức méo (5%), phân tích định lượngStandard -> VIP(5%), passTests 02–03(5%). -
Bài tập 2 (
ex2, 15%) —ClickHouse MergeTreeGranule Pruning,AggregatingMergeTreeMV &ReplacingMergeTree: Tính số granule tối thiểu cho bảng10Mdòng (\(G = 8{,}192\)) và giải thích mức tăng tốc285.0xkhi đặt đúng tiền tốORDER BY; chứng minh cơ chế trigger củaAggregatingMergeTree(100.0xgiảm dòng quét,12.14xnhanh hơn) và lý doSELECTtrơn trênReplacingMergeTree(ver)bị phình+18.19%(+217,979.90 USD) trước khi dùngargMax(Tests 04–05). Thang điểm: Đúng toán học Sparse Index & MV (5%), giải thích đúng bẫyReplacingMergeTree(5%), passTests 04–05(5%). -
Bài tập 3 (
ex3, 20%) — Deep-Dive Article #15: Toán họcPoint-in-Time ASOF JOIN& Hết hạnTTL: Viết phương trình \(t^*(e_i, t_{\text{label}, i})\) tích hợp cả hai ràng buộc \(t_j \le t_{\text{label}, i}\) lẫn \((t_{\text{label}, i} - t_j) \le \text{TTL}\); giải thích vì saoNaive Latest-Window Joinlàm rò rỉ81.75%(1,962/2,400) mẫu trong Lab 10 và phân tích tác dụng của việc ép232bản ghi quá hạnTTL = 3,600svềNULLtrongDuckDB 2.0(Tests 07–08). Thang điểm: Đúng công thức PIT + TTL (7%), phân tích đúng truy vấnDuckDB ASOF(7%), passTests 06–08(6%). -
Bài tập 4 (
ex4, 20%) — Giải phẫu Thảm họaOffline Mirage -> Production Collapse: Giải thích cơ chế tại sao các đặc trưng hậu kiểm sau gian lận (chargeback_flag_count, khóa thẻ éptx_velocity_1h -> 0) vừa đẩy mô hình Naive lênROC-AUC = 0.9853(PR-AUC = 0.9752), vừa đầu độc bộ trọng số khiến mô hình sụp đổ xuốngROC-AUC = 0.5143(-0.4710) trên tập phục vụ nhân quảOOT, trong khi mô hìnhPIT ASOFgiữ vững0.8858(+0.3715cao hơn Naive,test_09). Thang điểm: Giải thích chính xác cơ chế đảo dấu trọng số (7%), đối chiếuROC-AUC&PR-AUC(7%), passtest_09(6%). -
Bài tập 5 (
ex5, 15%) — Kiểm toánTraining–Serving Parity&Feast OnDemandFeatureView: Liệt kê 4 nguồn gốc gâyTraining–Serving Skew; phân tích kết quả kiểm toán500yêu cầu trực tuyến củatest_10(Broken online lỗi500/500,48lỗi lệchTTLvs UnifiedOnDemandFeatureViewđạt100.0%parity vớimax_abs_diff = 0.0) và kiểm thử hàmcompute_shared_risk_features(test_15). Thang điểm: Phân tích đủ 4 nguyên nhân Skew (5%), chứng minh vai trò chia sẻ hàm +TTL(5%), passTests 10, 15(5%). -
Bài tập 6 (
ex6, 15%) — Thiết kế Kiến trúcClickHouse + Feast + Redis, OpenTelemetry & Kiểm toán Tĩnh Toàn phần: So sánh khi nào chọnClickHousevsApache Pinot, BatchmaterializevsPushSource; kiểm định sạch 4 tạo tác hạ tầng (docker-compose.yml,01_clickhouse_star_scd2_mv.sql,feature_store.yaml,feast_repo/features.pyAST), xác minh5spans OpenTelemetry SDK (InMemorySpanExporter), và chạy xanh toàn bộ17/17 pytest+ruff+mypy(Tests 01, 11–14, 16–17). Thang điểm: Quyết định kiến trúc chính xác (5%), giải thích từng tạo tác kiểm toán (5%), đạt xanh17/17 pytest+ruff/mypy0lỗi (5%).
5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#
- (
q1—SCD Type 1vs.SCD Type 2TrongDuckDB 2.0): Trên12,000giao dịch (1,575,346.92 USD,180khách nâng hạngStandard -> VIP) trong Lab 10 (test_03), điều gì xảy ra khi dùng SCD Type 1 so với SCD Type 2? - (
q2—ClickHouse MergeTreeSparse Index &Granule Pruning): Với bảng10,000,000dòng (index_granularity = 8,192,1,221granules) trongtest_04, tại sao đặtORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts)giúp bỏ qua99.92%granules so với đặttx_tslên đầu? - (
q3—AggregatingMergeTreeMV &ReplacingMergeTree(ver)Hazard): TrongTests 04–05, cơ chế hoạt động củaAggregatingMergeTreeIncremental Materialized View là gì (240,000 -> 2,400dòng,344.08 -> 28.35 ms,12.14xnhanh hơn), và vì saoSELECTtrơn trênReplacingMergeTree(ver)gây phình+18.19%(+217,979.90 USD)? - (
q4—ClickHousevs.Apache Pinot& Lựa chọnStar-Tree Index): Khác biệt kiến trúc cốt lõi giữaClickHousevàApache Pinotlà gì khi phục vụ User-Facing OLAP ở mức> 10,000 QPSvới P99< 20 ms? - (
q5— Chuyên đề #15:DuckDB ASOF JOIN& Ngăn Rò rỉ Tương lai): Công thức Point-in-Time hợp lệ \(t^*(e_i, t_{\text{label}, i})\) đòi hỏi điều kiện gì, và trong Lab 10 (Tests 07–08), phép nối này giải quyết thế nào bài toán81.75%rò rỉ tương lai và232mẫu quá hạnTTL = 3,600s? - (
q6— Giải mãOffline Mirage -> Production CollapseTrong Chống Gian lận): Tại sao mô hình huấn luyện trên phép nối ngây thơ đạtROC-AUC = 0.9853ở kiểm định giả nhưng lại tụt thảm xuống0.5143(-0.4710) ởOOT Serving, kém hơn tới-0.3715AUC so với mô hìnhPIT ASOF(0.8858)? - (
q7—FeastDual-Store & Triệt tiêuTraining–Serving Skew): TrongLab 10(test_10), hai cơ chế kỹ thuật nào giúp Unified Feast Pipeline nâng tỷ lệ đồng nhất Offline–Online trên500yêu cầu từ0.0%(48lỗi TTL + lệch thang đo) lên100.0%(0vi phạm)? - (
q8— Kiểm toán Hạ tầngClickHouse + Redis + Feast& Lưu ý Triển khai): Bộ 4 tạo tác triển khai trongLab 10(Tests 11–14) dùng kiểm toán nào để bảo đảm khả năng sẵn sàng sản xuất khi chưa chạy Docker daemon tại máy phát triển?
Historical Tier Revenue Distortion (USD): SCD Type 1 Overwrite vs SCD Type 2
OLAP Analytical Scan Rows: AggregatingMergeTree MV vs Raw Fact Scan
Deep-Dive #15: Fraud ROC-AUC Mirage (Naive Offline vs Naive Serving vs PIT ASOF)
Training-Serving Feature Parity Pass Rate (% of 500 Audited Serving Requests)
Dimensional Modeling: SCD Type 1 Overwrite vs SCD Type 2 Temporal Interval Join
| segment_tier | ground_truth_usd | scd1_overwrite_usd | scd2_interval_usd |
|---|---|---|---|
| Standard | 1,031,469.37 | 762,510.55 | 1,031,469.37 |
| VIP | 543,877.55 | 812,836.37 | 543,877.55 |
| TOTAL ABS DISTORTION | 0.00 | 537,917.64 (34.15%) | 0.00 (EXACT) |
ClickHouse Sparse Primary Index, AggregatingMergeTree MV & ReplacingMergeTree
| mechanism | naive_baseline | sota_clickhouse | verdict |
|---|---|---|---|
| Granule Pruning (10M rows, G=8,192) | Bad sort key: 2,334,720 rows | Good sort key: 8,192 rows (99.92% skip) | 285.0x fewer rows |
| Incremental Materialized View (10 queries) | Raw scan 240,000 rows (344.08 ms) | AggMT MV 2,400 rows (28.35 ms) | 12.14x faster, exact match |
| ReplacingMergeTree(ver) CDC Upsert | Unmerged SELECT: 5,900 rows (+18.19%) | argMax(amount, ver): 5,000 rows (err 0.0 USD) | PASS (0.0 USD dedup err) |
Deep-Dive Article #15: Look-Ahead Leakage Mirage vs DuckDB ASOF Point-in-Time
| pipeline_variant | future_leak_rate | offline_eval_auc | true_oot_serving_auc |
|---|---|---|---|
| Naive Latest-Window Join (Look-Ahead Bug) | 81.75% (1,962 leaked) | 0.9853 (Mirage!) | 0.5143 (-0.4710 crash) |
| DuckDB ASOF PIT Join + TTL=3600s | 0.0% (0 leaked, 232 TTL NULL) | 0.8953 (5-fold CV) | 0.8858 (+0.3715 vs Naive) |
| Offline-Online Parity (500 requests) | Broken online: 500 violations | Unified Feast: 0 violations | 100.0% EXACT PARITY |
Deployable ClickHouse + Feast + Redis + Postgres Stack Static Audits
| artifact | verified_properties | status |
|---|---|---|
| docker-compose.yml | 4 services (clickhouse, redis, postgres-offline, feast-feature-server) | PASS |
| sql/01_clickhouse_star_scd2_mv.sql | 6/6 checks (SCD2, MergeTree 8192, ReplacingMT+argMax, AggMT MV, ASOF) | PASS |
| configs/feature_store.yaml | 5/5 checks (Redis online, DuckDB offline, entity_key v3, on-demand flag) | PASS |
| feast_repo/features.py (AST) | Entity + PushSource + RequestSource + FeatureView(ttl) + OnDemandFeatureView (0 unsafe imports) | PASS |
03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-10-feast-clickhouse-pit-feature-store
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "feast-olap-pit-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 10: Dimensional Modeling SCD2, ClickHouse MergeTree/Materialized Views, Feast Feature Store, Point-in-Time ASOF Joins & Training-Serving Parity"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"duckdb>=2.0.0",
"polars>=2.0.0",
"pyarrow>=20.0.0",
"scikit-learn>=1.6.0",
"pydantic>=2.0.0",
"pyyaml>=6.0.0",
"numpy>=2.0.0",
"scipy>=1.14.0",
"opentelemetry-sdk>=1.28",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.8",
"mypy>=1.10",
]
[project.scripts]
fsds-feast-olap-pit-lab = "feast_olap_pit_lab.pit_feature_store:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = [
"yaml",
"pyarrow",
"pyarrow.*",
"duckdb",
"polars",
"pandas",
"feast",
"feast.*",
"scipy",
"scipy.*",
"sklearn.*",
]
ignore_missing_imports = true
[[tool.mypy.overrides]]
module = ["feast_repo.*"]
disallow_untyped_decorators = false
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
services:
postgres-offline:
image: postgres:16.4-alpine
container_name: fsds-consumption-postgres-offline
environment:
POSTGRES_USER: "${POSTGRES_USER:-fsds_feast}"
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-fsds_feast_local_dev_only}"
POSTGRES_DB: "${POSTGRES_DB:-feast_offline}"
ports:
- "${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres_offline_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-fsds_feast} -d ${POSTGRES_DB:-feast_offline}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
deploy:
resources:
limits:
cpus: "1.0"
memory: 1G
networks:
- consumption_net
redis:
image: redis:7.4-alpine
container_name: fsds-consumption-redis-online
command: ["redis-server", "--appendonly", "yes", "--maxmemory", "512mb", "--maxmemory-policy", "volatile-ttl"]
ports:
- "${REDIS_PORT:-6379}:6379"
volumes:
- redis_online_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 5s
deploy:
resources:
limits:
cpus: "1.0"
memory: 768M
networks:
- consumption_net
clickhouse:
image: clickhouse/clickhouse-server:24.8-alpine
container_name: fsds-consumption-clickhouse
environment:
CLICKHOUSE_DB: "${CLICKHOUSE_DB:-consumption_olap}"
CLICKHOUSE_USER: "${CLICKHOUSE_USER:-fsds_olap}"
CLICKHOUSE_PASSWORD: "${CLICKHOUSE_PASSWORD:-fsds_olap_local_dev_only}"
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: "1"
ports:
- "${CLICKHOUSE_HTTP_PORT:-8123}:8123"
- "${CLICKHOUSE_NATIVE_PORT:-9000}:9000"
volumes:
- clickhouse_data:/var/lib/clickhouse
- ./sql/01_clickhouse_star_scd2_mv.sql:/docker-entrypoint-initdb.d/01_clickhouse_star_scd2_mv.sql:ro
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:8123/ping | grep -q Ok || exit 1"]
interval: 15s
timeout: 5s
retries: 6
start_period: 20s
deploy:
resources:
limits:
cpus: "2.0"
memory: 2G
networks:
- consumption_net
feast-feature-server:
image: feastdev/feature-server:0.40.1
container_name: fsds-consumption-feast-server
depends_on:
postgres-offline:
condition: service_healthy
redis:
condition: service_healthy
clickhouse:
condition: service_healthy
environment:
FEAST_REPO_PATH: /feast_repo
REDIS_HOST: redis
REDIS_PORT: "${REDIS_PORT:-6379}"
CLICKHOUSE_HOST: clickhouse
CLICKHOUSE_PORT: "${CLICKHOUSE_HTTP_PORT:-8123}"
POSTGRES_HOST: postgres-offline
ports:
- "${FEAST_SERVER_PORT:-6566}:6566"
volumes:
- ./configs/feature_store.yaml:/feast_repo/feature_store.yaml:ro
- ./feast_repo:/feast_repo/feast_repo:ro
healthcheck:
test: ["CMD-SHELL", "curl -sf http://localhost:6566/health || exit 1"]
interval: 15s
timeout: 5s
retries: 5
start_period: 20s
deploy:
resources:
limits:
cpus: "1.5"
memory: 1536M
networks:
- consumption_net
networks:
consumption_net:
driver: bridge
volumes:
postgres_offline_data:
redis_online_data:
clickhouse_data:
project: fsds_fraud_consumption
provider: local
registry: data/registry.db
entity_key_serialization_version: 3
offline_store:
type: duckdb
online_store:
type: redis
connection_string: "${REDIS_HOST:-redis}:${REDIS_PORT:-6379},db=0"
batch_engine:
type: local
flags:
alpha_features: true
on_demand_transforms: true
-- Deployable ClickHouse 24.8+ Consumption Layer Schema:
-- Star Schema with SCD Type 2 Dimension, MergeTree Sparse Index, ReplacingMergeTree Dedup,
-- AggregatingMergeTree Incremental Materialized View, and Point-in-Time ASOF JOIN.
CREATE DATABASE IF NOT EXISTS consumption_olap;
-- 1. Conformed Dimension with Slowly Changing Dimension Type 2 (SCD2) intervals
CREATE TABLE IF NOT EXISTS consumption_olap.dim_customer_scd2
(
customer_sk UInt64,
customer_id String,
segment_tier LowCardinality(String),
region_code LowCardinality(String),
valid_from DateTime64(3, 'UTC'),
valid_to DateTime64(3, 'UTC'),
is_current UInt8,
updated_at DateTime64(3, 'UTC')
)
ENGINE = MergeTree()
ORDER BY (customer_id, valid_from)
SETTINGS index_granularity = 8192;
-- 2. Raw Fact Transactions partitioned monthly & clustered for Sparse Granule Pruning
CREATE TABLE IF NOT EXISTS consumption_olap.fact_transactions
(
tx_id String,
customer_id String,
merchant_id String,
tx_ts DateTime64(3, 'UTC'),
amount_usd Float64,
is_fraud UInt8
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(tx_ts)
ORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts, tx_id)
SETTINGS index_granularity = 8192;
-- 3. ReplacingMergeTree for Idempotent CDC / Flink Upsert Ingestion (Async Background Dedup)
CREATE TABLE IF NOT EXISTS consumption_olap.orders_cdc_dedup
(
order_id String,
customer_id String,
status LowCardinality(String),
amount_usd Float64,
ver UInt64,
updated_ts DateTime64(3, 'UTC')
)
ENGINE = ReplacingMergeTree(ver)
PARTITION BY toYYYYMM(updated_ts)
ORDER BY (customer_id, order_id)
SETTINGS index_granularity = 8192;
-- Exact deduplicated analytical query (safe even before background compaction completes):
-- SELECT customer_id, order_id, argMax(amount_usd, ver) AS exact_amount_usd
-- FROM consumption_olap.orders_cdc_dedup
-- GROUP BY customer_id, order_id;
-- 4. Pre-Aggregated Hourly Target Table (AggregatingMergeTree)
CREATE TABLE IF NOT EXISTS consumption_olap.agg_hourly_customer_stats
(
customer_id String,
hour_bucket DateTime('UTC'),
tx_count_state AggregateFunction(count, String),
revenue_state AggregateFunction(sum, Float64),
uniq_merchants AggregateFunction(uniq, String)
)
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(hour_bucket)
ORDER BY (customer_id, hour_bucket)
SETTINGS index_granularity = 8192;
-- 5. Incremental Materialized View (INSERT trigger updating AggregatingMergeTree in real time)
CREATE MATERIALIZED VIEW IF NOT EXISTS consumption_olap.mv_hourly_customer_stats
TO consumption_olap.agg_hourly_customer_stats
AS
SELECT
customer_id,
toStartOfHour(tx_ts) AS hour_bucket,
countState(tx_id) AS tx_count_state,
sumState(amount_usd) AS revenue_state,
uniqState(merchant_id) AS uniq_merchants
FROM consumption_olap.fact_transactions
GROUP BY customer_id, hour_bucket;
-- 6. Real-Time Feature Store History Table & Point-in-Time ASOF JOIN Retrieval
CREATE TABLE IF NOT EXISTS consumption_olap.customer_risk_features_history
(
customer_id String,
feat_ts DateTime64(3, 'UTC'),
tx_velocity_1h Float64,
amount_ewma Float64,
chargeback_flag_count UInt32,
acct_age_days Float64
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(feat_ts)
ORDER BY (customer_id, feat_ts)
SETTINGS index_granularity = 8192;
-- Point-in-Time ASOF LEFT JOIN enforcing causal boundary (feat_ts <= tx_ts) and 3600s TTL:
-- SELECT
-- f.tx_id,
-- f.customer_id,
-- f.tx_ts,
-- IF(dateDiff('second', h.feat_ts, f.tx_ts) <= 3600, h.tx_velocity_1h, NULL) AS tx_velocity_1h,
-- IF(dateDiff('second', h.feat_ts, f.tx_ts) <= 3600, h.chargeback_flag_count, NULL) AS chargeback_flag_count
-- FROM consumption_olap.fact_transactions AS f
-- ASOF LEFT JOIN consumption_olap.customer_risk_features_history AS h
-- ON f.customer_id = h.customer_id AND f.tx_ts >= h.feat_ts;
"""Deployable Feast Feature Store Repository (Entity, PushSource, TTL FeatureView, OnDemandFeatureView).
Maintains a single pure-Python transformation kernel (`compute_shared_risk_features`) shared
identically across offline historical batch training and online Redis feature serving to guarantee
zero training-serving skew (Deep-Dive Article #15).
"""
from __future__ import annotations
import math
from datetime import timedelta
from typing import Any
FEATURE_TTL_SECONDS = 3600
HIGH_RISK_VELOCITY_THRESHOLD = 4.0
def compute_shared_risk_features(
tx_velocity_1h: float | None,
amount_usd: float,
amount_ewma: float | None,
chargeback_flag_count: float | None,
) -> dict[str, float | None]:
"""Unified On-Demand transformation executed identically in Offline Training and Online Serving.
Preserves causal NULL semantics when upstream TTL-bounded features have expired (`None`).
"""
if tx_velocity_1h is None or amount_ewma is None or chargeback_flag_count is None:
return {
"log_amount_ratio": None,
"risk_velocity_score": None,
"is_high_velocity_burst": None,
}
safe_amount = max(0.0, float(amount_usd))
safe_ewma = max(1.0, float(amount_ewma))
safe_vel = max(0.0, float(tx_velocity_1h))
safe_cb = max(0.0, float(chargeback_flag_count))
log_amount_ratio = round(math.log1p(safe_amount / safe_ewma), 8)
risk_velocity_score = round(0.55 * math.log1p(safe_vel) + 0.45 * safe_cb, 8)
is_high_velocity_burst = 1.0 if safe_vel >= HIGH_RISK_VELOCITY_THRESHOLD else 0.0
return {
"log_amount_ratio": log_amount_ratio,
"risk_velocity_score": risk_velocity_score,
"is_high_velocity_burst": is_high_velocity_burst,
}
def build_feast_definitions() -> dict[str, Any]:
"""Instantiate real Feast FeatureView, PushSource, and OnDemandFeatureView objects.
Executed when applying the repository to a live Feast registry (`feast apply`).
"""
import pandas as pd
from feast import Entity, FeatureView, Field, FileSource, PushSource, RequestSource, ValueType
from feast.on_demand_feature_view import on_demand_feature_view
from feast.types import Float64, Int64
customer = Entity(
name="customer_id",
join_keys=["customer_id"],
value_type=ValueType.STRING,
description="Canonical customer identifier shared across offline and online stores.",
)
customer_risk_batch_source = FileSource(
name="customer_risk_features_parquet_source",
path="data/customer_risk_features.parquet",
timestamp_field="feat_ts",
)
customer_risk_push_source = PushSource(
name="customer_risk_features_push_source",
batch_source=customer_risk_batch_source,
)
tx_request_source = RequestSource(
name="transaction_request_context",
schema=[
Field(name="amount_usd", dtype=Float64),
],
)
customer_risk_fv = FeatureView(
name="customer_risk_features",
entities=[customer],
ttl=timedelta(seconds=FEATURE_TTL_SECONDS),
schema=[
Field(name="tx_velocity_1h", dtype=Float64),
Field(name="amount_ewma", dtype=Float64),
Field(name="chargeback_flag_count", dtype=Int64),
Field(name="acct_age_days", dtype=Float64),
],
online=True,
source=customer_risk_push_source,
tags={"team": "risk-ml", "article": "deep-dive-15"},
)
@on_demand_feature_view(
sources=[customer_risk_fv, tx_request_source],
schema=[
Field(name="log_amount_ratio", dtype=Float64),
Field(name="risk_velocity_score", dtype=Float64),
Field(name="is_high_velocity_burst", dtype=Float64),
],
)
def transformed_risk_features(inputs: pd.DataFrame) -> pd.DataFrame:
rows = [
compute_shared_risk_features(
tx_velocity_1h=row["tx_velocity_1h"] if pd.notna(row["tx_velocity_1h"]) else None,
amount_usd=float(row["amount_usd"]),
amount_ewma=row["amount_ewma"] if pd.notna(row["amount_ewma"]) else None,
chargeback_flag_count=(
float(row["chargeback_flag_count"])
if pd.notna(row["chargeback_flag_count"])
else None
),
)
for _, row in inputs.iterrows()
]
return pd.DataFrame(rows)
return {
"entity": customer,
"push_source": customer_risk_push_source,
"request_source": tx_request_source,
"feature_view": customer_risk_fv,
"on_demand_feature_view": transformed_risk_features,
}
"""FSDS-SOTA-2026 Track 2 Lab 10: Consumption OLAP (SCD2, ClickHouse) & Feast PIT Feature Store."""
from feast_olap_pit_lab.infra_audit import (
FORBIDDEN_UNSAFE_IMPORTS,
audit_clickhouse_sql_ddl,
audit_consumption_infrastructure,
audit_docker_compose,
audit_feast_config_yaml,
audit_feast_repo_ast,
)
from feast_olap_pit_lab.olap_scd_engine import (
generate_star_scd_dataset,
run_scd1_vs_scd2_duckdb_audit,
simulate_clickhouse_mergetree_and_mv,
)
from feast_olap_pit_lab.pit_feature_store import (
audit_offline_online_parity,
build_training_datasets_duckdb_asof,
generate_pit_fraud_stream,
run_leakage_ml_ablation,
)
from feast_olap_pit_lab.telemetry import (
create_in_memory_telemetry,
get_default_telemetry,
summarize_finished_spans,
)
__all__ = [
"FORBIDDEN_UNSAFE_IMPORTS",
"audit_clickhouse_sql_ddl",
"audit_consumption_infrastructure",
"audit_docker_compose",
"audit_feast_config_yaml",
"audit_feast_repo_ast",
"audit_offline_online_parity",
"build_training_datasets_duckdb_asof",
"create_in_memory_telemetry",
"generate_pit_fraud_stream",
"generate_star_scd_dataset",
"get_default_telemetry",
"run_leakage_ml_ablation",
"run_scd1_vs_scd2_duckdb_audit",
"simulate_clickhouse_mergetree_and_mv",
"summarize_finished_spans",
]
"""Dimensional Modeling (SCD Type 1 vs. Type 2) & ClickHouse MergeTree/MV Engine using DuckDB 2.0."""
from __future__ import annotations
import time
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
import duckdb
import numpy as np
import polars as pl
from opentelemetry import trace
from feast_olap_pit_lab.telemetry import get_default_telemetry
def generate_star_scd_dataset(
num_tx: int = 12_000,
num_customers: int = 600,
seed: int = 42,
) -> dict[str, pl.DataFrame]:
"""Generate deterministic Star Schema + SCD2 customer tier transitions over a 90-day horizon.
Out of `num_customers`, 30% upgrade from `Standard` to `VIP` mid-horizon (days 40..70).
Transactions record both immutable ground-truth tier at `tx_ts` and customer join keys.
"""
rng = np.random.default_rng(seed)
base_ts = datetime(2026, 1, 1, 0, 0, 0, tzinfo=UTC)
horizon_sec = 90 * 86_400
num_upgraders = int(num_customers * 0.30)
num_always_vip = int(num_customers * 0.15)
regions = ["VN-SG", "VN-HN", "SG-01", "JP-TYO"]
scd2_rows: list[dict[str, Any]] = []
scd1_rows: list[dict[str, Any]] = []
customer_meta: dict[str, tuple[str, str, datetime | None]] = {}
sk_counter = 1
for cid_idx in range(num_customers):
cid = f"cust_{cid_idx:04d}"
region = regions[cid_idx % len(regions)]
if cid_idx < num_upgraders:
# Upgraded from Standard -> VIP between day 40 and day 70
change_day = float(rng.uniform(40.0, 70.0))
change_ts = base_ts + timedelta(seconds=int(change_day * 86_400))
scd2_rows.append(
{
"customer_sk": sk_counter,
"customer_id": cid,
"segment_tier": "Standard",
"region_code": region,
"valid_from": base_ts,
"valid_to": change_ts,
"is_current": False,
}
)
sk_counter += 1
scd2_rows.append(
{
"customer_sk": sk_counter,
"customer_id": cid,
"segment_tier": "VIP",
"region_code": region,
"valid_from": change_ts,
"valid_to": base_ts + timedelta(days=3650),
"is_current": True,
}
)
sk_counter += 1
scd1_rows.append(
{
"customer_id": cid,
"segment_tier": "VIP",
"region_code": region,
}
)
customer_meta[cid] = ("Standard", "VIP", change_ts)
elif cid_idx < num_upgraders + num_always_vip:
scd2_rows.append(
{
"customer_sk": sk_counter,
"customer_id": cid,
"segment_tier": "VIP",
"region_code": region,
"valid_from": base_ts,
"valid_to": base_ts + timedelta(days=3650),
"is_current": True,
}
)
sk_counter += 1
scd1_rows.append(
{
"customer_id": cid,
"segment_tier": "VIP",
"region_code": region,
}
)
customer_meta[cid] = ("VIP", "VIP", None)
else:
scd2_rows.append(
{
"customer_sk": sk_counter,
"customer_id": cid,
"segment_tier": "Standard",
"region_code": region,
"valid_from": base_ts,
"valid_to": base_ts + timedelta(days=3650),
"is_current": True,
}
)
sk_counter += 1
scd1_rows.append(
{
"customer_id": cid,
"segment_tier": "Standard",
"region_code": region,
}
)
customer_meta[cid] = ("Standard", "Standard", None)
tx_rows: list[dict[str, Any]] = []
cust_indices = rng.integers(0, num_customers, size=num_tx)
offsets_sec = rng.integers(0, horizon_sec, size=num_tx)
base_amounts = rng.lognormal(mean=4.6, sigma=0.55, size=num_tx)
for i in range(num_tx):
cid = f"cust_{int(cust_indices[i]):04d}"
tx_ts = base_ts + timedelta(seconds=int(offsets_sec[i]))
init_tier, final_tier, upgrade_ts = customer_meta[cid]
if upgrade_ts is not None and tx_ts >= upgrade_ts:
true_tier = final_tier
else:
true_tier = init_tier
mult = 1.45 if true_tier == "VIP" else 1.0
amt = round(float(base_amounts[i]) * mult, 2)
tx_rows.append(
{
"tx_id": f"tx_{i:06d}",
"customer_id": cid,
"merchant_id": f"merch_{int(rng.integers(0, 80)):03d}",
"tx_ts": tx_ts,
"amount_usd": amt,
"true_tier_at_tx": true_tier,
}
)
return {
"fact_transactions": pl.DataFrame(tx_rows),
"dim_customer_scd1": pl.DataFrame(scd1_rows),
"dim_customer_scd2": pl.DataFrame(scd2_rows),
}
def run_scd1_vs_scd2_duckdb_audit(
dataset: dict[str, pl.DataFrame],
work_dir: Path,
tracer: trace.Tracer | None = None,
) -> dict[str, Any]:
"""Execute real DuckDB 2.0 Star Schema joins comparing SCD Type 1 overwrite vs SCD Type 2.
Reads from temporary Parquet files inside `work_dir` and quantifies exact USD historical
attribution error by customer tier.
"""
active_tracer = tracer or get_default_telemetry()[2]
with active_tracer.start_as_current_span("lab10.olap.scd1_vs_scd2_audit") as span:
fact_path = work_dir / "fact_transactions.parquet"
scd1_path = work_dir / "dim_customer_scd1.parquet"
scd2_path = work_dir / "dim_customer_scd2.parquet"
dataset["fact_transactions"].write_parquet(fact_path)
dataset["dim_customer_scd1"].write_parquet(scd1_path)
dataset["dim_customer_scd2"].write_parquet(scd2_path)
con = duckdb.connect(":memory:")
try:
gt_rows = con.execute(
f"""
SELECT true_tier_at_tx AS tier, COUNT(*) AS tx_cnt, ROUND(SUM(amount_usd), 2) AS rev
FROM read_parquet('{fact_path.as_posix()}')
GROUP BY 1
ORDER BY 1
"""
).fetchall()
scd1_rows = con.execute(
f"""
SELECT d.segment_tier AS tier, COUNT(*) AS tx_cnt, ROUND(SUM(f.amount_usd), 2) AS rev
FROM read_parquet('{fact_path.as_posix()}') AS f
JOIN read_parquet('{scd1_path.as_posix()}') AS d
ON f.customer_id = d.customer_id
GROUP BY 1
ORDER BY 1
"""
).fetchall()
scd2_rows = con.execute(
f"""
SELECT d.segment_tier AS tier, COUNT(*) AS tx_cnt, ROUND(SUM(f.amount_usd), 2) AS rev
FROM read_parquet('{fact_path.as_posix()}') AS f
JOIN read_parquet('{scd2_path.as_posix()}') AS d
ON f.customer_id = d.customer_id
AND f.tx_ts >= d.valid_from
AND f.tx_ts < d.valid_to
GROUP BY 1
ORDER BY 1
"""
).fetchall()
finally:
con.close()
gt_map = {row[0]: {"tx_count": int(row[1]), "revenue_usd": float(row[2])} for row in gt_rows}
scd1_map = {row[0]: {"tx_count": int(row[1]), "revenue_usd": float(row[2])} for row in scd1_rows}
scd2_map = {row[0]: {"tx_count": int(row[1]), "revenue_usd": float(row[2])} for row in scd2_rows}
total_gt_rev = round(sum(v["revenue_usd"] for v in gt_map.values()), 2)
scd1_abs_distortion = round(
sum(
abs(scd1_map[t]["revenue_usd"] - gt_map[t]["revenue_usd"])
for t in gt_map
),
2,
)
scd2_abs_distortion = round(
sum(
abs(scd2_map[t]["revenue_usd"] - gt_map[t]["revenue_usd"])
for t in gt_map
),
2,
)
scd1_std_misattributed = round(
gt_map["Standard"]["revenue_usd"] - scd1_map["Standard"]["revenue_usd"], 2
)
scd1_distortion_pct = round((scd1_abs_distortion / total_gt_rev) * 100.0, 2)
scd2_distortion_pct = round((scd2_abs_distortion / total_gt_rev) * 100.0, 4)
total_tx = int(sum(v["tx_count"] for v in gt_map.values()))
span.set_attribute("olap.total_transactions", total_tx)
span.set_attribute("olap.scd1_distortion_usd", scd1_abs_distortion)
span.set_attribute("olap.scd1_distortion_pct", scd1_distortion_pct)
span.set_attribute("olap.scd2_distortion_usd", scd2_abs_distortion)
span.set_attribute("olap.scd2_exact_zero_distortion", scd2_abs_distortion == 0.0)
return {
"total_transactions": total_tx,
"total_ground_truth_revenue_usd": total_gt_rev,
"scd2_joined_transactions": int(sum(v["tx_count"] for v in scd2_map.values())),
"ground_truth_by_tier": gt_map,
"scd1_by_tier": scd1_map,
"scd2_by_tier": scd2_map,
"scd1_total_abs_distortion_usd": scd1_abs_distortion,
"scd1_standard_shifted_to_vip_usd": scd1_std_misattributed,
"scd1_distortion_pct": scd1_distortion_pct,
"scd2_total_abs_distortion_usd": scd2_abs_distortion,
"scd2_distortion_pct": scd2_distortion_pct,
"scd2_exact_zero_distortion": scd2_abs_distortion == 0.0,
}
def simulate_clickhouse_mergetree_and_mv(
num_fact_rows: int = 240_000,
seed: int = 42,
work_dir: Path | None = None,
tracer: trace.Tracer | None = None,
) -> dict[str, Any]:
"""Verify ClickHouse MergeTree Granule Pruning, AggregatingMergeTree MV, and ReplacingMergeTree.
Combines an exact DuckDB 2.0 analytical benchmark on `num_fact_rows` (raw scan vs pre-aggregated
hourly rollup + ReplacingMergeTree unmerged duplicates vs argMax deduplication) with the
10M-row ClickHouse `index_granularity = 8192` sparse primary index pruning model.
"""
active_tracer = tracer or get_default_telemetry()[2]
with active_tracer.start_as_current_span("lab10.olap.clickhouse_mergetree_mv") as span:
_ = work_dir
rng = np.random.default_rng(seed)
# 1. Sparse Primary Index Granule Pruning Model (10,000,000 rows, G = 8,192)
total_rows_10m = 10_000_000
granule_size = 8_192
total_granules = (total_rows_10m + granule_size - 1) // granule_size # 1,221
# Query filter: single tenant/customer (1 of 200) across a 7-day window out of 30 days
# Good ORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts): contiguous slice -> ~1 granule
good_key_granules_scanned = max(1, round(total_granules * (1.0 / 200.0) * (7.0 / 30.0)))
# Bad ORDER BY (tx_ts, customer_id): customer rows scattered across all 7 days -> ~285 granules
bad_key_granules_scanned = round(total_granules * (7.0 / 30.0))
good_rows_scanned = good_key_granules_scanned * granule_size
bad_rows_scanned = bad_key_granules_scanned * granule_size
granule_skip_pct = round((1.0 - good_rows_scanned / total_rows_10m) * 100.0, 2)
granule_pruning_speedup_x = round(bad_rows_scanned / good_rows_scanned, 2)
# 2. Real DuckDB Benchmark: Raw Fact Scan vs Pre-Aggregated Materialized View Rollup
# 240,000 raw events rolled up into 50 customers x 48 hours (<= 2,400 rows -> 100x scan cut)
n_customers = 50
n_hours = 48
cust_ids = rng.integers(0, n_customers, size=num_fact_rows)
hour_buckets = rng.integers(0, n_hours, size=num_fact_rows)
merchant_ids = rng.integers(0, 120, size=num_fact_rows)
amounts = np.round(rng.lognormal(mean=4.2, sigma=0.5, size=num_fact_rows), 2)
fact_df = pl.DataFrame(
{
"tx_id": [f"f_{i:06d}" for i in range(num_fact_rows)],
"customer_id": [f"cust_{int(c):04d}" for c in cust_ids],
"merchant_id": [f"merch_{int(m):03d}" for m in merchant_ids],
"hour_bucket": [int(h) for h in hour_buckets],
"amount_usd": amounts,
}
)
# CDC ReplacingMergeTree simulation: 5,000 unique orders + 900 retry/update versions
n_unique_orders = 5_000
n_updates = 900
order_amounts_v1 = np.round(rng.uniform(25.0, 450.0, size=n_unique_orders), 2)
cdc_rows: list[dict[str, Any]] = [
{
"order_id": f"ord_{i:05d}",
"customer_id": f"cust_{i % n_customers:04d}",
"ver": 1,
"amount_usd": float(order_amounts_v1[i]),
}
for i in range(n_unique_orders)
]
true_order_amounts = order_amounts_v1.copy()
for u_idx in range(n_updates):
oid = (u_idx * 5) % n_unique_orders
new_amt = round(float(true_order_amounts[oid]) + 15.0, 2)
true_order_amounts[oid] = new_amt
cdc_rows.append(
{
"order_id": f"ord_{oid:05d}",
"customer_id": f"cust_{oid % n_customers:04d}",
"ver": 2 + (u_idx // n_unique_orders),
"amount_usd": new_amt,
}
)
cdc_df = pl.DataFrame(cdc_rows)
expected_cdc_total_usd = round(float(np.sum(true_order_amounts)), 2)
n_benchmark_queries = 10
con = duckdb.connect(":memory:")
try:
con.register("fact_tbl_view", fact_df.to_arrow())
con.register("cdc_tbl", cdc_df.to_arrow())
con.execute("CREATE TABLE fact_tbl AS SELECT * FROM fact_tbl_view")
# Materialized View pre-aggregated rollup table (AggregatingMergeTree equivalent)
con.execute(
"""
CREATE TABLE mv_hourly_rollup AS
SELECT
customer_id,
hour_bucket,
COUNT(*) AS tx_cnt,
ROUND(SUM(amount_usd), 2) AS rev_sum,
COUNT(DISTINCT merchant_id) AS uniq_merchants
FROM fact_tbl
GROUP BY customer_id, hour_bucket
"""
)
mv_count_row = con.execute("SELECT COUNT(*) FROM mv_hourly_rollup").fetchone()
assert mv_count_row is not None
mv_row_count = int(mv_count_row[0])
raw_sql = """
SELECT
customer_id,
hour_bucket,
COUNT(*) AS tx_cnt,
ROUND(SUM(amount_usd), 2) AS rev_sum,
COUNT(DISTINCT merchant_id) AS uniq_merchants
FROM fact_tbl
WHERE hour_bucket >= 12
GROUP BY customer_id, hour_bucket
ORDER BY customer_id, hour_bucket
"""
mv_sql = """
SELECT customer_id, hour_bucket, tx_cnt, rev_sum, uniq_merchants
FROM mv_hourly_rollup
WHERE hour_bucket >= 12
ORDER BY customer_id, hour_bucket
"""
# Untimed warm-up iteration for both raw and MV queries to avoid cold cache/plan jitter
raw_res = con.execute(raw_sql).fetchall()
mv_res = con.execute(mv_sql).fetchall()
# Compute 10-query latency via median of 3 timed runs for raw scan vs MV
raw_runs_ms: list[float] = []
mv_runs_ms: list[float] = []
for _ in range(3):
t0 = time.perf_counter()
for _ in range(n_benchmark_queries):
raw_res = con.execute(raw_sql).fetchall()
raw_runs_ms.append((time.perf_counter() - t0) * 1000.0)
t1 = time.perf_counter()
for _ in range(n_benchmark_queries):
mv_res = con.execute(mv_sql).fetchall()
mv_runs_ms.append((time.perf_counter() - t1) * 1000.0)
raw_elapsed_ms = float(np.median(raw_runs_ms))
mv_elapsed_ms = float(np.median(mv_runs_ms))
# Verify exact numerical agreement between Raw Scan and Materialized View
raw_total = round(sum(float(r[3]) for r in raw_res), 2)
mv_total = round(sum(float(r[3]) for r in mv_res), 2)
# ReplacingMergeTree unmerged SELECT vs argMax(amount_usd, ver)
unmerged_row = con.execute(
"SELECT COUNT(*), ROUND(SUM(amount_usd), 2) FROM cdc_tbl"
).fetchone()
argmax_row = con.execute(
"""
SELECT COUNT(*), ROUND(SUM(latest_amt), 2)
FROM (
SELECT order_id, argMax(amount_usd, ver) AS latest_amt
FROM cdc_tbl
GROUP BY order_id
)
"""
).fetchone()
assert unmerged_row is not None and argmax_row is not None
finally:
con.close()
unmerged_count, unmerged_sum = int(unmerged_row[0]), float(unmerged_row[1])
argmax_count, argmax_sum = int(argmax_row[0]), float(argmax_row[1])
unmerged_inflation_usd = round(unmerged_sum - expected_cdc_total_usd, 2)
unmerged_inflation_pct = round((unmerged_inflation_usd / expected_cdc_total_usd) * 100.0, 2)
argmax_error_usd = round(abs(argmax_sum - expected_cdc_total_usd), 2)
mv_scan_reduction_x = round(num_fact_rows / max(1, mv_row_count), 2)
mv_latency_speedup_x = round(raw_elapsed_ms / max(0.05, mv_elapsed_ms), 2)
span.set_attribute("clickhouse.granule_skip_pct", granule_skip_pct)
span.set_attribute("clickhouse.mv_benchmark_queries", n_benchmark_queries)
span.set_attribute("clickhouse.mv_scan_reduction_x", mv_scan_reduction_x)
span.set_attribute("clickhouse.mv_latency_speedup_x", mv_latency_speedup_x)
span.set_attribute("clickhouse.argmax_error_usd", argmax_error_usd)
return {
"granule_pruning_10m_model": {
"total_rows": total_rows_10m,
"index_granularity": granule_size,
"total_granules": total_granules,
"good_order_by_granules_hit": good_key_granules_scanned,
"bad_order_by_granules_hit": bad_key_granules_scanned,
"good_order_by_rows_scanned": good_rows_scanned,
"bad_order_by_rows_scanned": bad_rows_scanned,
"granule_skip_pct": granule_skip_pct,
"pruning_speedup_vs_bad_key_x": granule_pruning_speedup_x,
},
"materialized_view_benchmark": {
"query_iterations": n_benchmark_queries,
"raw_fact_rows": num_fact_rows,
"mv_rollup_rows": mv_row_count,
"scan_reduction_x": mv_scan_reduction_x,
"raw_10_queries_ms": round(raw_elapsed_ms, 2),
"mv_10_queries_ms": round(mv_elapsed_ms, 2),
"latency_speedup_x": mv_latency_speedup_x,
"raw_customer_revenue_usd": raw_total,
"mv_customer_revenue_usd": mv_total,
"mv_exact_match": abs(raw_total - mv_total) == 0.0,
},
"replacing_mergetree_dedup": {
"unique_orders": n_unique_orders,
"cdc_update_events": n_updates,
"expected_ground_truth_usd": expected_cdc_total_usd,
"unmerged_raw_rows": unmerged_count,
"unmerged_naive_sum_usd": unmerged_sum,
"unmerged_inflation_usd": unmerged_inflation_usd,
"unmerged_inflation_pct": unmerged_inflation_pct,
"argmax_dedup_rows": argmax_count,
"argmax_dedup_sum_usd": argmax_sum,
"argmax_error_usd": argmax_error_usd,
"argmax_exact_match": argmax_error_usd == 0.0 and argmax_count == n_unique_orders,
},
}
"""Deep-Dive Article #15 Engine: DuckDB 2.0 Point-in-Time ASOF JOIN, TTL, Fraud ML Ablation & Parity."""
from __future__ import annotations
import sys
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
import duckdb
import numpy as np
import polars as pl
from opentelemetry import trace
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
LAB_ROOT = Path(__file__).resolve().parents[2]
if str(LAB_ROOT) not in sys.path:
sys.path.insert(0, str(LAB_ROOT))
from feast_olap_pit_lab.telemetry import get_default_telemetry # noqa: E402
from feast_repo.features import compute_shared_risk_features # noqa: E402
TTL_DEFAULT_SECONDS = 3600
FEATURE_COLUMNS = [
"tx_velocity_1h",
"amount_ewma",
"chargeback_flag_count",
"acct_age_days",
"log_amount_ratio",
"risk_velocity_score",
"is_high_velocity_burst",
]
def generate_pit_fraud_stream(
num_entities: int = 400,
num_labels: int = 2_400,
seed: int = 42,
) -> dict[str, pl.DataFrame]:
"""Generate causal feature snapshot history + temporal fraud labels (Train + OOT Serving).
Key causal dynamics (Deep-Dive Article #15):
- Pre-event snapshots (`t_feat <= t_label`) reflect real pre-fraud risk (elevated velocity &
amount spike vs EWMA, lower account age, zero post-event chargebacks).
- Post-fraud operational reaction (`t_label + 1h..6h`) freezes the card (`tx_velocity_1h -> 0`)
and increments `chargeback_flag_count` (`1..3`). A Naive latest/same-day join pulls these
post-event artifacts backwards in time, creating a massive offline ROC-AUC mirage and
collapsing when evaluated on true causal Out-of-Time (OOT) serving!
- Roughly 10% of labels intentionally have their closest prior snapshot older than `TTL=3600s`
to verify TTL expiration semantics (`NULL` instead of stale feature revival).
"""
rng = np.random.default_rng(seed)
base_ts = datetime(2026, 1, 1, 0, 0, 0, tzinfo=UTC)
# Split labels: 1,600 Train (days 2..58) and 800 Out-of-Time Serving Holdout (days 60..88)
n_train = int(num_labels * 2 / 3)
n_oot = num_labels - n_train
train_days = np.sort(rng.uniform(2.0, 58.0, size=n_train))
oot_days = np.sort(rng.uniform(60.0, 88.0, size=n_oot))
all_days = np.concatenate([train_days, oot_days])
label_rows: list[dict[str, Any]] = []
feature_rows: list[dict[str, Any]] = []
# Account base profiles per entity
acct_ages_base = rng.uniform(30.0, 900.0, size=num_entities)
ewma_base = rng.uniform(45.0, 220.0, size=num_entities)
# Background regular snapshots (~30 snapshots per entity across 90 days = 12,000 baseline rows)
for eid in range(num_entities):
cid = f"cust_{eid:04d}"
bg_days = np.sort(rng.uniform(0.5, 89.5, size=30))
for d in bg_days:
feat_ts = base_ts + timedelta(seconds=int(float(d) * 86_400))
feature_rows.append(
{
"customer_id": cid,
"feat_ts": feat_ts,
"tx_velocity_1h": round(float(rng.uniform(0.3, 2.4)), 4),
"amount_ewma": round(float(ewma_base[eid] * rng.uniform(0.85, 1.15)), 2),
"chargeback_flag_count": 0,
"acct_age_days": round(float(acct_ages_base[eid] + d), 1),
}
)
# Generate labels + causal pre-event snapshots + post-event fraud operational snapshots
for idx in range(num_labels):
split_name = "train" if idx < n_train else "oot_serving"
day_val = float(all_days[idx])
event_ts = base_ts + timedelta(seconds=int(day_val * 86_400))
eid = int(rng.integers(0, num_entities))
cid = f"cust_{eid:04d}"
# True latent fraud propensity driven by pre-event velocity, amount spike, and account age
base_ewma = float(ewma_base[eid])
acct_age = float(acct_ages_base[eid] + day_val)
latent_risk = rng.normal(0.0, 1.0)
is_fraud = 1 if (latent_risk > 1.05 or (acct_age < 150.0 and latent_risk > 0.45)) else 0
if is_fraud == 1:
pre_vel = round(float(rng.uniform(1.5, 5.2)), 4)
tx_amount = round(float(base_ewma * rng.uniform(1.1, 3.2)), 2)
else:
pre_vel = round(float(rng.uniform(0.4, 3.5)), 4)
tx_amount = round(float(base_ewma * rng.uniform(0.45, 2.2)), 2)
# ~10% of labels receive stale snapshots (> 3600s prior, e.g. 5400..9000s prior)
# while 90% receive a fresh causal snapshot inside (event_ts - 2400s .. event_ts - 30s)
is_stale_ttl_case = (idx % 10) == 0
if is_stale_ttl_case:
# Ensure no snapshot inside TTL window by placing nearest pre-snapshot at -7200s
# (and note: rare background snapshot might exist; we keep labels deterministic)
pre_offset_sec = int(rng.integers(5400, 10800))
else:
pre_offset_sec = int(rng.integers(30, 2400))
pre_feat_ts = event_ts - timedelta(seconds=pre_offset_sec)
feature_rows.append(
{
"customer_id": cid,
"feat_ts": pre_feat_ts,
"tx_velocity_1h": pre_vel,
"amount_ewma": round(base_ewma, 2),
"chargeback_flag_count": 0,
"acct_age_days": round(acct_age, 1),
}
)
# Post-event reaction (FUTURE LEAKAGE TRAP if Naive join picks post-event snapshot!):
# Fraud -> +30m..+4h later ops freezes card (velocity=0.05) and raises chargeback flags (1..3)
# 75% of Legitimate -> normal post-event snapshot (+30m..+4h later)
post_offset_sec = int(rng.integers(1800, 14400))
post_feat_ts = event_ts + timedelta(seconds=post_offset_sec)
if is_fraud == 1:
feature_rows.append(
{
"customer_id": cid,
"feat_ts": post_feat_ts,
"tx_velocity_1h": round(float(rng.uniform(0.0, 0.2)), 4),
"amount_ewma": round(base_ewma, 2),
"chargeback_flag_count": int(rng.integers(1, 4)),
"acct_age_days": round(acct_age, 1),
}
)
elif (idx % 4) != 0:
feature_rows.append(
{
"customer_id": cid,
"feat_ts": post_feat_ts,
"tx_velocity_1h": round(float(rng.uniform(0.8, 2.5)), 4),
"amount_ewma": round(base_ewma, 2),
"chargeback_flag_count": 0,
"acct_age_days": round(acct_age, 1),
}
)
label_rows.append(
{
"label_id": f"lbl_{idx:05d}",
"customer_id": cid,
"event_ts": event_ts,
"amount_usd": tx_amount,
"is_fraud": is_fraud,
"split": split_name,
"intended_stale_ttl": is_stale_ttl_case,
}
)
labels_df = pl.DataFrame(label_rows).sort(["event_ts", "label_id"])
features_df = pl.DataFrame(feature_rows).sort(["customer_id", "feat_ts"])
return {
"labels": labels_df,
"features": features_df,
}
def _apply_shared_ondemand_transforms(df: pl.DataFrame) -> pl.DataFrame:
"""Apply Feast OnDemandFeatureView shared kernel identically across rows."""
out_records: list[dict[str, float | None]] = []
for row in df.iter_rows(named=True):
out_records.append(
compute_shared_risk_features(
tx_velocity_1h=row["tx_velocity_1h"],
amount_usd=float(row["amount_usd"]),
amount_ewma=row["amount_ewma"],
chargeback_flag_count=(
float(row["chargeback_flag_count"])
if row["chargeback_flag_count"] is not None
else None
),
)
)
odf = pl.DataFrame(out_records)
return df.hstack(odf)
def build_training_datasets_duckdb_asof(
stream_bundle: dict[str, pl.DataFrame],
work_dir: Path,
ttl_seconds: int = TTL_DEFAULT_SECONDS,
tracer: trace.Tracer | None = None,
) -> dict[str, Any]:
"""Build Naive vs DuckDB 2.0 Point-in-Time ASOF JOIN (+ TTL) datasets from Parquet files."""
active_tracer = tracer or get_default_telemetry()[2]
with active_tracer.start_as_current_span("lab10.pit.duckdb_asof_join") as span:
labels_path = work_dir / "fraud_labels.parquet"
feats_path = work_dir / "customer_risk_features.parquet"
stream_bundle["labels"].write_parquet(labels_path)
stream_bundle["features"].write_parquet(feats_path)
con = duckdb.connect(":memory:")
try:
# 1. Naive Unbounded / Same-Day-Window Latest Snapshot Join (Look-Ahead Leakage Bug!)
# Picks latest snapshot within [event_ts - 6h, event_ts + 6h] (unaligned join)
naive_arrow = con.sql(
f"""
WITH candidates AS (
SELECT
l.label_id,
l.customer_id,
l.event_ts,
l.amount_usd,
l.is_fraud,
l.split,
l.intended_stale_ttl,
f.feat_ts,
f.tx_velocity_1h,
f.amount_ewma,
f.chargeback_flag_count,
f.acct_age_days,
ROW_NUMBER() OVER (
PARTITION BY l.label_id
ORDER BY f.feat_ts DESC
) AS rn
FROM read_parquet('{labels_path.as_posix()}') AS l
LEFT JOIN read_parquet('{feats_path.as_posix()}') AS f
ON l.customer_id = f.customer_id
AND f.feat_ts >= l.event_ts - INTERVAL '6 hours'
AND f.feat_ts <= l.event_ts + INTERVAL '6 hours'
)
SELECT
label_id, customer_id, event_ts, amount_usd, is_fraud, split, intended_stale_ttl,
feat_ts, tx_velocity_1h, amount_ewma, chargeback_flag_count, acct_age_days
FROM candidates
WHERE rn = 1
ORDER BY event_ts, label_id
"""
).to_arrow_table()
# 2. Causal Point-in-Time DuckDB 2.0 ASOF LEFT JOIN + Freshness TTL Enforcement
pit_arrow = con.sql(
f"""
SELECT
l.label_id,
l.customer_id,
l.event_ts,
l.amount_usd,
l.is_fraud,
l.split,
l.intended_stale_ttl,
f.feat_ts,
CASE
WHEN f.feat_ts IS NOT NULL
AND EPOCH(l.event_ts) - EPOCH(f.feat_ts) <= {int(ttl_seconds)}
THEN f.tx_velocity_1h
ELSE NULL
END AS tx_velocity_1h,
CASE
WHEN f.feat_ts IS NOT NULL
AND EPOCH(l.event_ts) - EPOCH(f.feat_ts) <= {int(ttl_seconds)}
THEN f.amount_ewma
ELSE NULL
END AS amount_ewma,
CASE
WHEN f.feat_ts IS NOT NULL
AND EPOCH(l.event_ts) - EPOCH(f.feat_ts) <= {int(ttl_seconds)}
THEN f.chargeback_flag_count
ELSE NULL
END AS chargeback_flag_count,
CASE
WHEN f.feat_ts IS NOT NULL
AND EPOCH(l.event_ts) - EPOCH(f.feat_ts) <= {int(ttl_seconds)}
THEN f.acct_age_days
ELSE NULL
END AS acct_age_days,
CASE
WHEN f.feat_ts IS NOT NULL
THEN EPOCH(l.event_ts) - EPOCH(f.feat_ts)
ELSE NULL
END AS feature_age_sec
FROM read_parquet('{labels_path.as_posix()}') AS l
ASOF LEFT JOIN read_parquet('{feats_path.as_posix()}') AS f
ON l.customer_id = f.customer_id
AND l.event_ts >= f.feat_ts
ORDER BY l.event_ts, l.label_id
"""
).to_arrow_table()
finally:
con.close()
naive_raw = pl.from_arrow(naive_arrow)
pit_raw = pl.from_arrow(pit_arrow)
assert isinstance(naive_raw, pl.DataFrame)
assert isinstance(pit_raw, pl.DataFrame)
naive_df = _apply_shared_ondemand_transforms(naive_raw)
pit_df = _apply_shared_ondemand_transforms(pit_raw)
naive_leak_cnt = int(naive_df.filter(pl.col("feat_ts") > pl.col("event_ts")).height)
pit_leak_cnt = int(pit_df.filter(pl.col("feat_ts") > pl.col("event_ts")).height)
total_rows = int(pit_df.height)
ttl_expired_null_cnt = int(pit_df.filter(pl.col("tx_velocity_1h").is_null()).height)
ttl_stale_matched_cnt = int(
pit_df.filter(
pl.col("feature_age_sec").is_not_null() & (pl.col("feature_age_sec") > ttl_seconds)
).height
)
ttl_stale_all_null = bool(
pit_df.filter(
pl.col("feature_age_sec").is_not_null() & (pl.col("feature_age_sec") > ttl_seconds)
)["tx_velocity_1h"]
.is_null()
.all()
)
span.set_attribute("pit.ttl_seconds", ttl_seconds)
span.set_attribute("pit.total_labels", total_rows)
span.set_attribute("pit.naive_future_leak_count", naive_leak_cnt)
span.set_attribute("pit.future_leak_count", pit_leak_cnt)
span.set_attribute("pit.ttl_expired_null_count", ttl_expired_null_cnt)
return {
"ttl_seconds": ttl_seconds,
"total_labels": total_rows,
"total_feature_snapshots": int(stream_bundle["features"].height),
"naive_future_leak_count": naive_leak_cnt,
"naive_future_leak_rate_pct": round((naive_leak_cnt / total_rows) * 100.0, 2),
"pit_future_leak_count": pit_leak_cnt,
"pit_future_leak_rate_pct": round((pit_leak_cnt / total_rows) * 100.0, 4),
"ttl_expired_null_count": ttl_expired_null_cnt,
"ttl_stale_matched_count": ttl_stale_matched_cnt,
"ttl_expired_properly_nulled": ttl_stale_all_null and ttl_expired_null_cnt > 0,
"naive_df": naive_df,
"pit_df": pit_df,
}
def _make_fraud_pipeline() -> Pipeline:
"""Create deterministic leakage-safe sklearn Pipeline (imputer + scaler fit only on Train)."""
return Pipeline(
steps=[
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("clf", LogisticRegression(C=1.0, max_iter=500, random_state=42)),
]
)
def run_leakage_ml_ablation(datasets: dict[str, Any]) -> dict[str, Any]:
"""Train identical LogisticRegression models on Naive-Joined vs PIT-ASOF-Joined Train sets.
Evaluates both models on:
1. Their own offline OOT slice (showing Naive's offline ROC-AUC mirage).
2. True Causal Online Serving OOT (`pit_df` where `split == 'oot_serving'`), proving
the Naive model collapses catastrophically when future signals vanish at serving time,
while the PIT ASOF model exhibits virtually zero mirage gap and dominates production!
"""
naive_df: pl.DataFrame = datasets["naive_df"]
pit_df: pl.DataFrame = datasets["pit_df"]
naive_train = naive_df.filter(pl.col("split") == "train")
naive_eval = naive_df.filter(pl.col("split") == "oot_serving")
pit_train = pit_df.filter(pl.col("split") == "train")
causal_serving_oot = pit_df.filter(pl.col("split") == "oot_serving")
x_naive_tr = naive_train.select(FEATURE_COLUMNS).to_numpy()
y_naive_tr = naive_train["is_fraud"].to_numpy()
x_naive_ev = naive_eval.select(FEATURE_COLUMNS).to_numpy()
y_naive_ev = naive_eval["is_fraud"].to_numpy()
x_pit_tr = pit_train.select(FEATURE_COLUMNS).to_numpy()
y_pit_tr = pit_train["is_fraud"].to_numpy()
x_serving = causal_serving_oot.select(FEATURE_COLUMNS).to_numpy()
y_serving = causal_serving_oot["is_fraud"].to_numpy()
naive_model = _make_fraud_pipeline().fit(x_naive_tr, y_naive_tr)
pit_model = _make_fraud_pipeline().fit(x_pit_tr, y_pit_tr)
naive_offline_probs = naive_model.predict_proba(x_naive_ev)[:, 1]
naive_serving_probs = naive_model.predict_proba(x_serving)[:, 1]
pit_serving_probs = pit_model.predict_proba(x_serving)[:, 1]
# Out-of-sample 5-fold CV offline validation on PIT training set (no training-set optimism)
cv = StratifiedKFold(n_splits=5, shuffle=False)
pit_cv_probs = cross_val_predict(
_make_fraud_pipeline(),
x_pit_tr,
y_pit_tr,
cv=cv,
method="predict_proba",
)[:, 1]
pit_offline_auc = float(roc_auc_score(y_pit_tr, pit_cv_probs))
naive_offline_auc = float(roc_auc_score(y_naive_ev, naive_offline_probs))
naive_serving_auc = float(roc_auc_score(y_serving, naive_serving_probs))
pit_serving_auc = float(roc_auc_score(y_serving, pit_serving_probs))
naive_offline_prauc = float(average_precision_score(y_naive_ev, naive_offline_probs))
naive_serving_prauc = float(average_precision_score(y_serving, naive_serving_probs))
pit_serving_prauc = float(average_precision_score(y_serving, pit_serving_probs))
naive_mirage_drop = round(naive_offline_auc - naive_serving_auc, 4)
pit_parity_gap = round(abs(pit_offline_auc - pit_serving_auc), 4)
serving_auc_gain = round(pit_serving_auc - naive_serving_auc, 4)
return {
"train_samples": int(pit_train.height),
"oot_serving_samples": int(causal_serving_oot.height),
"naive_offline_mirage_roc_auc": round(naive_offline_auc, 4),
"naive_offline_mirage_pr_auc": round(naive_offline_prauc, 4),
"naive_true_serving_roc_auc": round(naive_serving_auc, 4),
"naive_true_serving_pr_auc": round(naive_serving_prauc, 4),
"naive_mirage_collapse_auc": naive_mirage_drop,
"pit_offline_roc_auc": round(pit_offline_auc, 4),
"pit_true_serving_roc_auc": round(pit_serving_auc, 4),
"pit_true_serving_pr_auc": round(pit_serving_prauc, 4),
"pit_offline_vs_serving_gap_auc": pit_parity_gap,
"pit_serving_gain_over_naive_auc": serving_auc_gain,
}
def audit_offline_online_parity(
pit_df: pl.DataFrame,
sample_size: int = 500,
seed: int = 42,
tracer: trace.Tracer | None = None,
) -> dict[str, Any]:
"""Verify Offline PIT features vs Simulated Redis Online KV Store across 500 serving requests.
Compares:
1. Broken Re-Implemented Online Service: unit-scaling bug (`amount / 100`), missing Redis TTL
cutoff (serves stale old snapshot instead of NULL), and unaligned NULL->0.0 fallback.
2. Unified Feast Parity Pipeline (`OnDemandFeatureView` shared kernel + synchronized TTL):
achieves exact 0.0 difference (`100%` parity) across all numeric features and NULL masks.
"""
active_tracer = tracer or get_default_telemetry()[2]
with active_tracer.start_as_current_span("lab10.feast.offline_online_parity") as span:
oot_rows = pit_df.filter(pl.col("split") == "oot_serving")
n_audit = min(sample_size, int(oot_rows.height))
audit_slice = oot_rows.head(n_audit)
# Simulated Online Redis KV Store storing latest materialized values + updated_ts
# Broken pipeline forgets TTL expiration and re-implements transforms differently
broken_violations = 0
broken_max_diff = 0.0
broken_null_mismatches = 0
unified_violations = 0
unified_max_diff = 0.0
unified_null_mismatches = 0
rng = np.random.default_rng(seed)
tolerance = 1e-6
for row in audit_slice.iter_rows(named=True):
off_ratio = row["log_amount_ratio"]
off_score = row["risk_velocity_score"]
off_burst = row["is_high_velocity_burst"]
is_off_null = off_ratio is None
# Simulate stale online KV value when offline expired via TTL
if is_off_null:
stale_vel = round(float(rng.uniform(0.5, 2.0)), 4)
stale_ewma = 120.0
stale_cb = 0.0
else:
stale_vel = float(row["tx_velocity_1h"])
stale_ewma = float(row["amount_ewma"])
stale_cb = float(row["chargeback_flag_count"])
# --- Branch A: Broken Re-Implemented Online Handler ---
# Bug 1: Ignores TTL -> never returns None for stale entries
# Bug 2: Uses `amount / 100.0` instead of `log1p(amount / ewma)`
# Bug 3: Scales velocity score differently
broken_ratio = round(float(row["amount_usd"]) / 100.0, 8)
broken_score = round(0.5 * stale_vel + 0.5 * stale_cb, 8)
if is_off_null:
broken_null_mismatches += 1
broken_violations += 1
broken_max_diff = max(broken_max_diff, abs(broken_ratio))
else:
diff = max(
abs(float(off_ratio) - broken_ratio),
abs(float(off_score) - broken_score),
)
if diff > tolerance:
broken_violations += 1
broken_max_diff = max(broken_max_diff, diff)
# --- Branch B: Unified Feast OnDemandFeatureView + Synchronized TTL ---
online_ttl_valid = not is_off_null
unified_out = compute_shared_risk_features(
tx_velocity_1h=stale_vel if online_ttl_valid else None,
amount_usd=float(row["amount_usd"]),
amount_ewma=stale_ewma if online_ttl_valid else None,
chargeback_flag_count=stale_cb if online_ttl_valid else None,
)
u_ratio = unified_out["log_amount_ratio"]
u_score = unified_out["risk_velocity_score"]
u_burst = unified_out["is_high_velocity_burst"]
if (u_ratio is None) != is_off_null:
unified_null_mismatches += 1
unified_violations += 1
elif not is_off_null:
assert u_ratio is not None and u_score is not None and u_burst is not None
assert off_score is not None and off_burst is not None
u_diff = max(
abs(float(off_ratio) - u_ratio),
abs(float(off_score) - u_score),
abs(float(off_burst) - u_burst),
)
unified_max_diff = max(unified_max_diff, u_diff)
if u_diff > tolerance:
unified_violations += 1
unified_max_rounded = round(unified_max_diff, 10)
unified_passed = unified_violations == 0 and unified_null_mismatches == 0
span.set_attribute("parity.audited_requests", n_audit)
span.set_attribute("parity.broken_violations_count", broken_violations)
span.set_attribute("parity.unified_violations_count", unified_violations)
span.set_attribute("parity.unified_max_abs_diff", unified_max_rounded)
span.set_attribute("parity.unified_passed", unified_passed)
return {
"audited_requests": n_audit,
"tolerance": tolerance,
"broken_online_pipeline": {
"violations_count": broken_violations,
"parity_pass_rate_pct": round((1.0 - broken_violations / n_audit) * 100.0, 2),
"null_ttl_mismatches": broken_null_mismatches,
"max_abs_diff": round(broken_max_diff, 6),
},
"unified_feast_pipeline": {
"violations_count": unified_violations,
"parity_pass_rate_pct": round((1.0 - unified_violations / n_audit) * 100.0, 2),
"null_ttl_mismatches": unified_null_mismatches,
"max_abs_diff": unified_max_rounded,
"parity_passed": unified_passed,
},
}
def main() -> None:
"""Quick CLI smoke entry point executing PIT & Parity verification."""
import tempfile
bundle = generate_pit_fraud_stream(num_entities=400, num_labels=2_400, seed=42)
with tempfile.TemporaryDirectory(prefix="fsds_lab10_pit_") as tmp:
ds = build_training_datasets_duckdb_asof(bundle, Path(tmp))
ablation = run_leakage_ml_ablation(ds)
parity = audit_offline_online_parity(ds["pit_df"])
print(f"PIT future leak rate: {ds['pit_future_leak_rate_pct']}% | Ablation: {ablation}")
print(f"Unified parity pass rate: {parity['unified_feast_pipeline']['parity_pass_rate_pct']}%")
"""OpenTelemetry SDK span instrumentation for Track 2 Lab 10 (`feast_olap_pit_lab`)."""
from __future__ import annotations
from typing import Any
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
try:
from opentelemetry.sdk.trace.export import InMemorySpanExporter # type: ignore[attr-defined]
except ImportError:
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def create_in_memory_telemetry(
service_name: str = "fsds-lab10-feast-olap-pit",
) -> tuple[TracerProvider, InMemorySpanExporter, trace.Tracer]:
"""Create a TracerProvider backed by SimpleSpanProcessor & InMemorySpanExporter."""
exporter = InMemorySpanExporter()
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("feast_olap_pit_lab")
return provider, exporter, tracer
_DEFAULT_PROVIDER, _DEFAULT_EXPORTER, _DEFAULT_TRACER = create_in_memory_telemetry()
def get_default_telemetry() -> tuple[TracerProvider, InMemorySpanExporter, trace.Tracer]:
"""Return the shared in-memory OpenTelemetry TracerProvider, exporter, and tracer."""
return _DEFAULT_PROVIDER, _DEFAULT_EXPORTER, _DEFAULT_TRACER
def summarize_finished_spans(exporter: InMemorySpanExporter) -> dict[str, Any]:
"""Serialize captured OpenTelemetry spans from InMemorySpanExporter for artifact reporting."""
spans = exporter.get_finished_spans()
return {
"span_count": len(spans),
"span_names": [span.name for span in spans],
"spans": [
{
"name": span.name,
"status": span.status.status_code.name,
"attributes": dict(span.attributes or {}),
}
for span in spans
],
}
"""Static infrastructure, ClickHouse SQL DDL, Feast YAML & Python AST auditor for Lab 10."""
from __future__ import annotations
import ast
from pathlib import Path
from typing import Any
import yaml
FORBIDDEN_UNSAFE_IMPORTS = frozenset(
{"pickle", "_pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
)
def audit_docker_compose(compose_path: Path) -> dict[str, Any]:
"""Audit docker-compose.yml for ClickHouse/Redis/Postgres/Feast pins, health & isolation."""
data = yaml.safe_load(compose_path.read_text(encoding="utf-8"))
services: dict[str, Any] = data.get("services", {})
expected_services = {
"clickhouse",
"redis",
"postgres-offline",
"feast-feature-server",
}
present_services = set(services.keys())
all_pinned = True
all_healthchecks = True
all_resource_limits = True
dependencies_wait_healthy = True
for svc_name, svc in services.items():
image = str(svc.get("image", ""))
if not image or ":latest" in image or ":" not in image:
all_pinned = False
if "healthcheck" not in svc:
all_healthchecks = False
limits = svc.get("deploy", {}).get("resources", {}).get("limits", {})
if not limits.get("memory") or not limits.get("cpus"):
all_resource_limits = False
if svc_name == "feast-feature-server":
deps = svc.get("depends_on", {})
for dep_name in ("postgres-offline", "redis", "clickhouse"):
if deps.get(dep_name, {}).get("condition") != "service_healthy":
dependencies_wait_healthy = False
has_isolated_network = "consumption_net" in data.get("networks", {})
passed = (
expected_services.issubset(present_services)
and all_pinned
and all_healthchecks
and all_resource_limits
and dependencies_wait_healthy
and has_isolated_network
)
return {
"services_count": len(services),
"expected_services_present": expected_services.issubset(present_services),
"all_images_pinned": all_pinned,
"all_healthchecks_defined": all_healthchecks,
"all_resource_limits_defined": all_resource_limits,
"dependencies_wait_healthy": dependencies_wait_healthy,
"isolated_network_consumption_net": has_isolated_network,
"passed": passed,
}
def audit_clickhouse_sql_ddl(sql_path: Path) -> dict[str, Any]:
"""Verify ClickHouse DDL includes SCD2, MergeTree, ReplacingMT, AggregatingMT, MV & ASOF."""
sql_text = sql_path.read_text(encoding="utf-8")
upper_sql = sql_text.upper()
checks = {
"has_dim_customer_scd2": "DIM_CUSTOMER_SCD2" in upper_sql and "VALID_FROM" in upper_sql,
"has_mergetree_granularity_8192": (
"MERGETREE()" in upper_sql and "INDEX_GRANULARITY = 8192" in upper_sql
),
"has_replacing_mergetree_with_argmax": (
"REPLACINGMERGETREE(VER)" in upper_sql and "ARGMAX(" in upper_sql
),
"has_aggregating_mergetree_and_mv": (
"AGGREGATINGMERGETREE()" in upper_sql
and "CREATE MATERIALIZED VIEW" in upper_sql
and "SUMSTATE(" in upper_sql
and "UNIQSTATE(" in upper_sql
),
"has_asof_left_join_pit": (
"ASOF LEFT JOIN" in upper_sql and "DATEDIFF(" in upper_sql
),
"zero_destructive_drop": "DROP TABLE" not in upper_sql and "TRUNCATE TABLE" not in upper_sql,
}
return {
"checks_count": len(checks),
"checks": checks,
"passed": all(checks.values()),
}
def audit_feast_config_yaml(conf_path: Path) -> dict[str, Any]:
"""Verify configs/feature_store.yaml defines project, Redis online store & offline store."""
cfg = yaml.safe_load(conf_path.read_text(encoding="utf-8"))
if not isinstance(cfg, dict):
raise ValueError("feature_store.yaml must parse to a YAML mapping.")
online_cfg = cfg.get("online_store", {})
offline_cfg = cfg.get("offline_store", {})
flags_cfg = cfg.get("flags", {})
checks = {
"project_defined": bool(cfg.get("project")),
"entity_key_v3": cfg.get("entity_key_serialization_version") == 3,
"online_store_redis": isinstance(online_cfg, dict) and online_cfg.get("type") == "redis",
"offline_store_duckdb_or_ch": (
isinstance(offline_cfg, dict)
and offline_cfg.get("type") in {"duckdb", "clickhouse", "postgres"}
),
"on_demand_transforms_enabled": (
isinstance(flags_cfg, dict) and flags_cfg.get("on_demand_transforms") is True
),
}
return {
"checks_count": len(checks),
"checks": checks,
"passed": all(checks.values()),
}
def audit_feast_repo_ast(repo_path: Path) -> dict[str, Any]:
"""Audit feast_repo/features.py via AST without importing Feast server dependencies."""
source = repo_path.read_text(encoding="utf-8")
tree = ast.parse(source, filename=str(repo_path))
unsafe_imports: list[str] = []
called_names: set[str] = set()
defined_funcs: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.split(".")[0]
if root in FORBIDDEN_UNSAFE_IMPORTS:
unsafe_imports.append(root)
elif isinstance(node, ast.ImportFrom) and node.module:
root = node.module.split(".")[0]
if root in FORBIDDEN_UNSAFE_IMPORTS:
unsafe_imports.append(root)
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
called_names.add(node.func.id)
elif isinstance(node, ast.FunctionDef):
defined_funcs.add(node.name)
has_eval_exec = "eval" in called_names or "exec" in called_names
has_entity = "Entity" in called_names
has_push_source = "PushSource" in called_names
has_request_source = "RequestSource" in called_names
has_feature_view_with_ttl = "FeatureView" in called_names and "ttl=timedelta" in source
has_on_demand_fv = (
"on_demand_feature_view" in source and "compute_shared_risk_features" in defined_funcs
)
passed = (
len(unsafe_imports) == 0
and not has_eval_exec
and has_entity
and has_push_source
and has_request_source
and has_feature_view_with_ttl
and has_on_demand_fv
)
return {
"unsafe_imports": unsafe_imports,
"zero_eval_exec": not has_eval_exec,
"has_entity": has_entity,
"has_push_source": has_push_source,
"has_request_source": has_request_source,
"has_feature_view_with_ttl": has_feature_view_with_ttl,
"has_on_demand_fv": has_on_demand_fv,
"passed": passed,
}
def audit_consumption_infrastructure(lab_root: Path) -> dict[str, Any]:
"""Run all 4 static infrastructure, ClickHouse SQL & Feast repository audits."""
compose = audit_docker_compose(lab_root / "docker-compose.yml")
sql_ddl = audit_clickhouse_sql_ddl(lab_root / "sql" / "01_clickhouse_star_scd2_mv.sql")
feast_yaml = audit_feast_config_yaml(lab_root / "configs" / "feature_store.yaml")
feast_ast = audit_feast_repo_ast(lab_root / "feast_repo" / "features.py")
return {
"docker_compose": compose,
"clickhouse_sql_ddl": sql_ddl,
"feast_config_yaml": feast_yaml,
"feast_repo_ast": feast_ast,
"all_infra_checks_passed": bool(
compose["passed"] and sql_ddl["passed"] and feast_yaml["passed"] and feast_ast["passed"]
),
}
"""CLI runner for Track 2 Lab 10 (`feast_olap_pit_lab`) generating verified JSON artifacts."""
from __future__ import annotations
import argparse
import json
import sys
import tempfile
from pathlib import Path
from typing import Any
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from feast_olap_pit_lab.infra_audit import audit_consumption_infrastructure # noqa: E402
from feast_olap_pit_lab.olap_scd_engine import ( # noqa: E402
generate_star_scd_dataset,
run_scd1_vs_scd2_duckdb_audit,
simulate_clickhouse_mergetree_and_mv,
)
from feast_olap_pit_lab.pit_feature_store import ( # noqa: E402
audit_offline_online_parity,
build_training_datasets_duckdb_asof,
generate_pit_fraud_stream,
run_leakage_ml_ablation,
)
from feast_olap_pit_lab.telemetry import ( # noqa: E402
create_in_memory_telemetry,
summarize_finished_spans,
)
def build_workbench_panels(
scd_audit: dict[str, Any],
olap_ch: dict[str, Any],
pit_ds: dict[str, Any],
ml_ablation: dict[str, Any],
parity: dict[str, Any],
infra: dict[str, Any],
) -> dict[str, Any]:
"""Assemble standardized 6-KPI, 4-Bar, 4-Table workbench payload for the web platform."""
gp = olap_ch["granule_pruning_10m_model"]
mv = olap_ch["materialized_view_benchmark"]
rmt = olap_ch["replacing_mergetree_dedup"]
broken_p = parity["broken_online_pipeline"]
unified_p = parity["unified_feast_pipeline"]
kpis = [
{
"id": "kpi_scd2_vs_scd1_accuracy",
"label": "SCD Type 2 vs SCD Type 1 Historical Error (DuckDB)",
"value": (
f"{scd_audit['scd2_total_abs_distortion_usd']} USD vs "
f"{scd_audit['scd1_total_abs_distortion_usd']:,.0f} USD"
),
"unit": f"SCD1 shifts {scd_audit['scd1_distortion_pct']}% rev",
"status": "ok",
"detail": (
f"Across {scd_audit['total_transactions']:,} tx "
f"({scd_audit['total_ground_truth_revenue_usd']:,.2f} USD): SCD Type 1 overwrite "
f"misattributes {scd_audit['scd1_standard_shifted_to_vip_usd']:,.2f} USD "
"Standard -> VIP; SCD Type 2 interval join achieves exact 0.0 USD error."
),
},
{
"id": "kpi_clickhouse_mergetree_mv",
"label": "ClickHouse Granule Pruning & AggregatingMergeTree MV",
"value": f"{mv['scan_reduction_x']}x scan | {mv['latency_speedup_x']}x faster",
"unit": f"{gp['granule_skip_pct']}% granules skipped",
"status": "ok",
"detail": (
f"Sparse primary key (G=8,192 on 10M rows) prunes {gp['granule_skip_pct']}% "
f"granules ({gp['pruning_speedup_vs_bad_key_x']}x vs bad sort); "
f"AggregatingMergeTree MV cuts scanned rows {mv['raw_fact_rows']:,} -> "
f"{mv['mv_rollup_rows']:,} with exact match."
),
},
{
"id": "kpi_replacing_mergetree_dedup",
"label": "ReplacingMergeTree Pre-Merge Hazard vs argMax()",
"value": f"0.0 USD vs +{rmt['unmerged_inflation_pct']}%",
"unit": f"+{rmt['unmerged_inflation_usd']:,.0f} USD unmerged",
"status": "ok",
"detail": (
f"Before background merge, {rmt['cdc_update_events']} CDC updates inflate raw "
f"SELECT by +{rmt['unmerged_inflation_usd']:,.2f} USD; argMax(amount, ver) "
f"recovers exact {rmt['expected_ground_truth_usd']:,.2f} USD "
f"({rmt['unique_orders']:,} orders)."
),
},
{
"id": "kpi_pit_asof_zero_leakage",
"label": "DuckDB ASOF Point-in-Time Future Leakage & TTL",
"value": (
f"{pit_ds['pit_future_leak_rate_pct']}% vs "
f"{pit_ds['naive_future_leak_rate_pct']}%"
),
"unit": f"{pit_ds['ttl_expired_null_count']} stale TTL -> NULL",
"status": "ok",
"detail": (
f"Naive latest join leaks future snapshots on "
f"{pit_ds['naive_future_leak_count']:,}/{pit_ds['total_labels']:,} labels; "
"DuckDB ASOF (t_feat <= t_label, TTL=3600s) guarantees 0 future leaks and nulls "
f"{pit_ds['ttl_expired_null_count']} stale rows."
),
},
{
"id": "kpi_ml_mirage_vs_oot_serving",
"label": "OOT Online Serving ROC-AUC: PIT ASOF vs Naive Mirage",
"value": (
f"{ml_ablation['pit_true_serving_roc_auc']:.3f} vs "
f"{ml_ablation['naive_true_serving_roc_auc']:.3f}"
),
"unit": f"Naive drops -{ml_ablation['naive_mirage_collapse_auc']:.3f} AUC",
"status": "ok",
"detail": (
f"Naive Offline Mirage AUC={ml_ablation['naive_offline_mirage_roc_auc']:.4f} "
f"collapses to {ml_ablation['naive_true_serving_roc_auc']:.4f} on OOT Serving; "
f"PIT ASOF holds offline {ml_ablation['pit_offline_roc_auc']:.4f} -> serving "
f"{ml_ablation['pit_true_serving_roc_auc']:.4f} "
f"(+{ml_ablation['pit_serving_gain_over_naive_auc']:.3f} gain)."
),
},
{
"id": "kpi_feast_offline_online_parity",
"label": "Feast Offline-Online Parity & Infra Static Audits",
"value": (
f"{unified_p['parity_pass_rate_pct']}% vs "
f"{broken_p['parity_pass_rate_pct']}%"
),
"unit": "4/4 Infra Audits PASS",
"status": "ok",
"detail": (
f"Shared OnDemandFeatureView + TTL yields {unified_p['violations_count']}/"
f"{parity['audited_requests']} skew violations (max diff "
f"{unified_p['max_abs_diff']}); broken online code fails "
f"{broken_p['violations_count']} requests."
),
},
]
bars = [
{
"id": "bar_scd1_vs_scd2_distortion",
"title": (
"Historical Tier Revenue Distortion (USD): "
"SCD Type 1 Overwrite vs SCD Type 2"
),
"metric_label": "Absolute Tier Attribution Error (USD)",
"items": [
{
"label": "scd2_temporal_interval_join",
"value": scd_audit["scd2_total_abs_distortion_usd"],
"display": "0.00 USD (0.00% exact historical truth)",
"css_class": "is-fast",
},
{
"label": "scd1_overwrite_corrupted",
"value": scd_audit["scd1_total_abs_distortion_usd"],
"display": (
f"{scd_audit['scd1_total_abs_distortion_usd']:,.2f} USD "
f"({scd_audit['scd1_distortion_pct']}% shifted Standard <-> VIP)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_clickhouse_mv_scan_rows",
"title": "OLAP Analytical Scan Rows: AggregatingMergeTree MV vs Raw Fact Scan",
"metric_label": "Rows Scanned per Query",
"items": [
{
"label": "aggregating_mergetree_mv",
"value": mv["mv_rollup_rows"],
"display": (
f"{mv['mv_rollup_rows']:,} rollup rows "
f"({mv['scan_reduction_x']}x smaller, {mv['latency_speedup_x']}x faster)"
),
"css_class": "is-fast",
},
{
"label": "raw_fact_full_scan",
"value": mv["raw_fact_rows"],
"display": f"{mv['raw_fact_rows']:,} raw rows (baseline 1x)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_pit_vs_naive_serving_auc",
"title": (
"Deep-Dive #15: Fraud ROC-AUC Mirage "
"(Naive Offline vs Naive Serving vs PIT ASOF)"
),
"metric_label": "ROC-AUC Score",
"items": [
{
"label": "pit_asof_true_oot_serving",
"value": ml_ablation["pit_true_serving_roc_auc"],
"display": (
f"{ml_ablation['pit_true_serving_roc_auc']:.4f} OOT Serving "
f"(Offline {ml_ablation['pit_offline_roc_auc']:.4f}, zero mirage)"
),
"css_class": "is-fast",
},
{
"label": "naive_offline_mirage_leaked",
"value": ml_ablation["naive_offline_mirage_roc_auc"],
"display": (
f"{ml_ablation['naive_offline_mirage_roc_auc']:.4f} Offline Mirage "
f"({pit_ds['naive_future_leak_rate_pct']}% future leak)"
),
"css_class": "is-mid",
},
{
"label": "naive_true_oot_serving_collapse",
"value": ml_ablation["naive_true_serving_roc_auc"],
"display": (
f"{ml_ablation['naive_true_serving_roc_auc']:.4f} OOT Serving Collapse "
f"(-{ml_ablation['naive_mirage_collapse_auc']:.4f} drop!)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_offline_online_parity_pass",
"title": (
"Training-Serving Feature Parity Pass Rate "
"(% of 500 Audited Serving Requests)"
),
"metric_label": "Exact Parity Pass Rate (%)",
"items": [
{
"label": "unified_feast_ondemand_ttl",
"value": unified_p["parity_pass_rate_pct"],
"display": (
f"{unified_p['parity_pass_rate_pct']}% exact parity "
f"({unified_p['violations_count']} violations, max diff 0.0)"
),
"css_class": "is-fast",
},
{
"label": "broken_reimplemented_online",
"value": broken_p["parity_pass_rate_pct"],
"display": (
f"{broken_p['parity_pass_rate_pct']}% pass "
f"({broken_p['violations_count']} skew + "
f"{broken_p['null_ttl_mismatches']} TTL bugs)"
),
"css_class": "is-slow",
},
],
},
]
tables = [
{
"id": "table_scd1_vs_scd2_duckdb_reconciliation",
"title": (
"Dimensional Modeling: SCD Type 1 Overwrite vs "
"SCD Type 2 Temporal Interval Join"
),
"columns": [
"segment_tier",
"ground_truth_usd",
"scd1_overwrite_usd",
"scd2_interval_usd",
],
"rows": [
[
tier,
f"{scd_audit['ground_truth_by_tier'][tier]['revenue_usd']:,.2f}",
f"{scd_audit['scd1_by_tier'][tier]['revenue_usd']:,.2f}",
f"{scd_audit['scd2_by_tier'][tier]['revenue_usd']:,.2f}",
]
for tier in sorted(scd_audit["ground_truth_by_tier"].keys())
]
+ [
[
"TOTAL ABS DISTORTION",
"0.00",
(
f"{scd_audit['scd1_total_abs_distortion_usd']:,.2f} "
f"({scd_audit['scd1_distortion_pct']}%)"
),
f"{scd_audit['scd2_total_abs_distortion_usd']:.2f} (EXACT)",
]
],
},
{
"id": "table_clickhouse_mergetree_and_mv",
"title": "ClickHouse Sparse Primary Index, AggregatingMergeTree MV & ReplacingMergeTree",
"columns": ["mechanism", "naive_baseline", "sota_clickhouse", "verdict"],
"rows": [
[
"Granule Pruning (10M rows, G=8,192)",
f"Bad sort key: {gp['bad_order_by_rows_scanned']:,} rows",
(
f"Good sort key: {gp['good_order_by_rows_scanned']:,} rows "
f"({gp['granule_skip_pct']}% skip)"
),
f"{gp['pruning_speedup_vs_bad_key_x']}x fewer rows",
],
[
"Incremental Materialized View (10 queries)",
f"Raw scan {mv['raw_fact_rows']:,} rows ({mv['raw_10_queries_ms']} ms)",
f"AggMT MV {mv['mv_rollup_rows']:,} rows ({mv['mv_10_queries_ms']} ms)",
f"{mv['latency_speedup_x']}x faster, exact match",
],
[
"ReplacingMergeTree(ver) CDC Upsert",
(
f"Unmerged SELECT: {rmt['unmerged_raw_rows']:,} rows "
f"(+{rmt['unmerged_inflation_pct']}%)"
),
(
f"argMax(amount, ver): {rmt['argmax_dedup_rows']:,} rows "
f"(err {rmt['argmax_error_usd']} USD)"
),
"PASS (0.0 USD dedup err)",
],
],
},
{
"id": "table_article15_pit_leakage_ablation",
"title": "Deep-Dive Article #15: Look-Ahead Leakage Mirage vs DuckDB ASOF Point-in-Time",
"columns": [
"pipeline_variant",
"future_leak_rate",
"offline_eval_auc",
"true_oot_serving_auc",
],
"rows": [
[
"Naive Latest-Window Join (Look-Ahead Bug)",
(
f"{pit_ds['naive_future_leak_rate_pct']}% "
f"({pit_ds['naive_future_leak_count']:,} leaked)"
),
f"{ml_ablation['naive_offline_mirage_roc_auc']:.4f} (Mirage!)",
(
f"{ml_ablation['naive_true_serving_roc_auc']:.4f} "
f"(-{ml_ablation['naive_mirage_collapse_auc']:.4f} crash)"
),
],
[
"DuckDB ASOF PIT Join + TTL=3600s",
(
f"{pit_ds['pit_future_leak_rate_pct']}% "
f"(0 leaked, {pit_ds['ttl_expired_null_count']} TTL NULL)"
),
f"{ml_ablation['pit_offline_roc_auc']:.4f} (5-fold CV)",
(
f"{ml_ablation['pit_true_serving_roc_auc']:.4f} "
f"(+{ml_ablation['pit_serving_gain_over_naive_auc']:.4f} vs Naive)"
),
],
[
"Offline-Online Parity (500 requests)",
f"Broken online: {broken_p['violations_count']} violations",
f"Unified Feast: {unified_p['violations_count']} violations",
"100.0% EXACT PARITY" if unified_p["parity_passed"] else "FAIL",
],
],
},
{
"id": "table_consumption_infra_static_audits",
"title": "Deployable ClickHouse + Feast + Redis + Postgres Stack Static Audits",
"columns": ["artifact", "verified_properties", "status"],
"rows": [
[
"docker-compose.yml",
(
f"{infra['docker_compose']['services_count']} services "
"(clickhouse, redis, postgres-offline, feast-feature-server)"
),
"PASS" if infra["docker_compose"]["passed"] else "FAIL",
],
[
"sql/01_clickhouse_star_scd2_mv.sql",
(
f"{infra['clickhouse_sql_ddl']['checks_count']}/"
f"{infra['clickhouse_sql_ddl']['checks_count']} checks "
"(SCD2, MergeTree 8192, ReplacingMT+argMax, AggMT MV, ASOF)"
),
"PASS" if infra["clickhouse_sql_ddl"]["passed"] else "FAIL",
],
[
"configs/feature_store.yaml",
(
f"{infra['feast_config_yaml']['checks_count']}/"
f"{infra['feast_config_yaml']['checks_count']} checks "
"(Redis online, DuckDB offline, entity_key v3, on-demand flag)"
),
"PASS" if infra["feast_config_yaml"]["passed"] else "FAIL",
],
[
"feast_repo/features.py (AST)",
(
"Entity + PushSource + RequestSource + FeatureView(ttl) + "
"OnDemandFeatureView (0 unsafe imports)"
),
"PASS" if infra["feast_repo_ast"]["passed"] else "FAIL",
],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def run_all_benchmarks(
num_tx: int = 12_000,
num_labels: int = 2_400,
seed: int = 42,
) -> dict[str, Any]:
"""Execute full Tier 1 + Tier 2 Lab 10 benchmark suite cleanly inside a temporary directory."""
star_ds = generate_star_scd_dataset(num_tx=num_tx, num_customers=600, seed=seed)
pit_stream = generate_pit_fraud_stream(num_entities=400, num_labels=num_labels, seed=seed)
provider, exporter, tracer = create_in_memory_telemetry("fsds-lab10-demo")
with tracer.start_as_current_span(
"lab10.benchmark.suite",
attributes={"lab.seed": seed, "lab.num_tx": num_tx, "lab.num_labels": num_labels},
):
with tempfile.TemporaryDirectory(prefix="fsds_lab10_demo_") as tmp_dir:
tmp_path = Path(tmp_dir)
scd_audit = run_scd1_vs_scd2_duckdb_audit(star_ds, work_dir=tmp_path, tracer=tracer)
olap_ch = simulate_clickhouse_mergetree_and_mv(
num_fact_rows=240_000,
seed=seed,
work_dir=tmp_path,
tracer=tracer,
)
pit_ds = build_training_datasets_duckdb_asof(
pit_stream,
work_dir=tmp_path,
ttl_seconds=3600,
tracer=tracer,
)
ml_ablation = run_leakage_ml_ablation(pit_ds)
parity = audit_offline_online_parity(
pit_ds["pit_df"], sample_size=500, seed=seed, tracer=tracer
)
infra = audit_consumption_infrastructure(LAB_ROOT)
provider.force_flush()
otel_telemetry = summarize_finished_spans(exporter)
provider.shutdown()
pit_summary = {k: v for k, v in pit_ds.items() if k not in {"naive_df", "pit_df"}}
panels = build_workbench_panels(
scd_audit=scd_audit,
olap_ch=olap_ch,
pit_ds=pit_summary,
ml_ablation=ml_ablation,
parity=parity,
infra=infra,
)
return {
"unit_id": "T2-P2-U05",
"lab_id": "lab-10-feast-clickhouse-pit-feature-store",
"seed": seed,
"scd1_vs_scd2_audit": scd_audit,
"clickhouse_olap_mergetree": olap_ch,
"pit_asof_feature_retrieval": pit_summary,
"fraud_leakage_ml_ablation": ml_ablation,
"offline_online_parity_audit": parity,
"consumption_infrastructure_audit": infra,
"otel_telemetry": otel_telemetry,
"workbench_panels": panels,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run Track 2 Lab 10 Consumption OLAP & Feast PIT Feature Store demo"
)
parser.add_argument("--tx", type=int, default=12_000, help="Star schema transactions")
parser.add_argument("--labels", type=int, default=2_400, help="Fraud labels for PIT ablation")
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed")
parser.add_argument(
"--output",
type=Path,
default=LAB_ROOT / "artifacts" / "t2_ch11_lab10_results.json",
help="Output JSON artifact path",
)
args = parser.parse_args()
payload = run_all_benchmarks(num_tx=args.tx, num_labels=args.labels, seed=args.seed)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"Wrote verified Lab 10 artifact -> {args.output}")
if __name__ == "__main__":
main()
"""17-Test Deterministic Offline Verification Suite for Track 2 Lab 10 (`feast_olap_pit_lab`)."""
from __future__ import annotations
import ast
import importlib.util
import tempfile
from pathlib import Path
from typing import Any
import polars as pl
import pytest
from feast_olap_pit_lab.infra_audit import (
FORBIDDEN_UNSAFE_IMPORTS,
audit_clickhouse_sql_ddl,
audit_docker_compose,
audit_feast_config_yaml,
audit_feast_repo_ast,
)
from feast_olap_pit_lab.olap_scd_engine import (
generate_star_scd_dataset,
run_scd1_vs_scd2_duckdb_audit,
simulate_clickhouse_mergetree_and_mv,
)
from feast_olap_pit_lab.pit_feature_store import (
audit_offline_online_parity,
build_training_datasets_duckdb_asof,
generate_pit_fraud_stream,
run_leakage_ml_ablation,
)
from feast_olap_pit_lab.telemetry import create_in_memory_telemetry
from feast_repo.features import compute_shared_risk_features
LAB_ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(scope="module")
def pit_bundle() -> dict[str, Any]:
"""Build Naive vs DuckDB ASOF Point-in-Time datasets once in a temporary directory."""
stream = generate_pit_fraud_stream(num_entities=400, num_labels=2_400, seed=42)
with tempfile.TemporaryDirectory(prefix="fsds_lab10_pit_test_") as tmp_dir:
ds = build_training_datasets_duckdb_asof(
stream,
work_dir=Path(tmp_dir),
ttl_seconds=3600,
)
return ds
def test_01_ast_forbids_unsafe_deserializers() -> None:
"""Scan AST across src/, scripts/, and feast_repo/ banning unsafe deserializers."""
py_files = [
*list((LAB_ROOT / "src").rglob("*.py")),
*list((LAB_ROOT / "scripts").rglob("*.py")),
*list((LAB_ROOT / "feast_repo").rglob("*.py")),
]
assert len(py_files) >= 5
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:
root = alias.name.split(".")[0]
if root in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{path.name}: import {root}")
elif isinstance(node, ast.ImportFrom) and node.module:
root = node.module.split(".")[0]
if root in FORBIDDEN_UNSAFE_IMPORTS:
violations.append(f"{path.name}: from {root}")
assert violations == [], f"Forbidden unsafe deserializers found: {violations}"
def test_02_deterministic_star_scd_generator() -> None:
"""Verify deterministic Star Schema + SCD2 dataset with 12,000 tx & 600 customers."""
ds_a = generate_star_scd_dataset(num_tx=12_000, num_customers=600, seed=42)
ds_b = generate_star_scd_dataset(num_tx=12_000, num_customers=600, seed=42)
assert ds_a["fact_transactions"].height == 12_000
assert ds_a["dim_customer_scd1"].height == 600
assert ds_a["dim_customer_scd2"].height == 600 + 180 # 180 customers upgraded Standard -> VIP
assert ds_a["fact_transactions"].equals(ds_b["fact_transactions"])
assert ds_a["dim_customer_scd2"].equals(ds_b["dim_customer_scd2"])
def test_03_scd1_retroactive_distortion_vs_scd2_zero_error() -> None:
"""SCD Type 1 corrupts historical revenue attribution; SCD Type 2 achieves 0.0 USD error."""
star_ds = generate_star_scd_dataset(num_tx=12_000, num_customers=600, seed=42)
with tempfile.TemporaryDirectory(prefix="fsds_lab10_scd_") as tmp_dir:
res = run_scd1_vs_scd2_duckdb_audit(star_ds, work_dir=Path(tmp_dir))
assert res["total_transactions"] == 12_000
assert res["scd2_joined_transactions"] == 12_000
assert res["scd2_exact_zero_distortion"] is True
assert res["scd2_total_abs_distortion_usd"] == 0.0
assert res["scd2_distortion_pct"] == 0.0
# SCD Type 1 retroactively shifts Standard historical revenue into VIP
assert res["scd1_standard_shifted_to_vip_usd"] > 100_000.0
assert res["scd1_total_abs_distortion_usd"] > 200_000.0
assert res["scd1_distortion_pct"] > 10.0
def test_04_clickhouse_mergetree_granule_pruning_and_mv_speedup() -> None:
"""Sparse primary key skips >95% granules & AggregatingMergeTree MV cuts scanned rows >=50x."""
with tempfile.TemporaryDirectory(prefix="fsds_lab10_ch_") as tmp_dir:
res = simulate_clickhouse_mergetree_and_mv(
num_fact_rows=240_000,
seed=42,
work_dir=Path(tmp_dir),
)
gp = res["granule_pruning_10m_model"]
mv = res["materialized_view_benchmark"]
assert gp["index_granularity"] == 8_192
assert gp["granule_skip_pct"] > 95.0
assert gp["pruning_speedup_vs_bad_key_x"] > 50.0
assert mv["query_iterations"] == 10
assert "raw_10_queries_ms" in mv and "mv_10_queries_ms" in mv
assert "raw_20_queries_ms" not in mv and "mv_20_queries_ms" not in mv
assert mv["mv_exact_match"] is True
assert mv["scan_reduction_x"] >= 50.0
assert mv["latency_speedup_x"] > 2.5
def test_05_replacing_mergetree_unmerged_hazard_vs_argmax() -> None:
"""Unmerged ReplacingMergeTree SELECT inflates revenue; argMax(amount, ver) matches 0.0 USD."""
with tempfile.TemporaryDirectory(prefix="fsds_lab10_rmt_") as tmp_dir:
res = simulate_clickhouse_mergetree_and_mv(
num_fact_rows=240_000,
seed=42,
work_dir=Path(tmp_dir),
)
rmt = res["replacing_mergetree_dedup"]
assert rmt["unmerged_raw_rows"] == rmt["unique_orders"] + rmt["cdc_update_events"]
assert rmt["unmerged_inflation_usd"] > 50_000.0
assert rmt["unmerged_inflation_pct"] > 10.0
assert rmt["argmax_dedup_rows"] == rmt["unique_orders"]
assert rmt["argmax_error_usd"] == 0.0
assert rmt["argmax_exact_match"] is True
def test_06_deterministic_pit_fraud_stream_generator() -> None:
"""Verify deterministic generation of >=15k feature snapshots and 2,400 fraud labels."""
st_a = generate_pit_fraud_stream(num_entities=400, num_labels=2_400, seed=42)
st_b = generate_pit_fraud_stream(num_entities=400, num_labels=2_400, seed=42)
assert st_a["labels"].height == 2_400
assert st_a["features"].height >= 15_000
assert st_a["labels"].filter(pl.col("split") == "train").height == 1_600
assert st_a["labels"].filter(pl.col("split") == "oot_serving").height == 800
assert st_a["labels"].equals(st_b["labels"])
assert st_a["features"].equals(st_b["features"])
def test_07_duckdb_asof_zero_future_leakage_vs_naive(pit_bundle: dict[str, Any]) -> None:
"""Naive join suffers heavy look-ahead leakage; DuckDB ASOF JOIN guarantees 0 future leaks."""
assert pit_bundle["naive_future_leak_count"] > 1_000
assert pit_bundle["naive_future_leak_rate_pct"] > 40.0
assert pit_bundle["pit_future_leak_count"] == 0
assert pit_bundle["pit_future_leak_rate_pct"] == 0.0
def test_08_pit_ttl_expiration_returns_null(pit_bundle: dict[str, Any]) -> None:
"""Stale historical snapshots older than TTL=3600s must resolve to NULL in PIT ASOF."""
assert pit_bundle["ttl_seconds"] == 3600
assert pit_bundle["ttl_stale_matched_count"] > 100
assert pit_bundle["ttl_expired_null_count"] >= pit_bundle["ttl_stale_matched_count"]
assert pit_bundle["ttl_expired_properly_nulled"] is True
def test_09_ml_leakage_mirage_vs_true_oot_serving_parity(pit_bundle: dict[str, Any]) -> None:
"""Naive model achieves high offline mirage AUC then crashes on OOT; PIT ASOF wins serving."""
ablation = run_leakage_ml_ablation(pit_bundle)
assert ablation["naive_offline_mirage_roc_auc"] > 0.90
assert ablation["naive_mirage_collapse_auc"] > 0.15
assert ablation["pit_true_serving_roc_auc"] > 0.80
assert ablation["pit_offline_vs_serving_gap_auc"] < 0.05
assert ablation["pit_serving_gain_over_naive_auc"] > 0.10
def test_10_offline_online_parity_skew_detection_vs_unified(pit_bundle: dict[str, Any]) -> None:
"""Broken online logic produces skew & TTL violations; unified Feast OnDemand has 0.0 diff."""
parity = audit_offline_online_parity(pit_bundle["pit_df"], sample_size=500, seed=42)
broken = parity["broken_online_pipeline"]
unified = parity["unified_feast_pipeline"]
assert parity["audited_requests"] == 500
assert broken["violations_count"] > 400
assert broken["null_ttl_mismatches"] > 10
assert broken["parity_pass_rate_pct"] < 20.0
assert unified["violations_count"] == 0
assert unified["null_ttl_mismatches"] == 0
assert unified["max_abs_diff"] == 0.0
assert unified["parity_pass_rate_pct"] == 100.0
assert unified["parity_passed"] is True
def test_11_docker_compose_consumption_stack_audit() -> None:
"""Validate docker-compose.yml ClickHouse/Redis/Postgres/Feast pins, health & limits."""
res = audit_docker_compose(LAB_ROOT / "docker-compose.yml")
assert res["services_count"] == 4
assert res["expected_services_present"] is True
assert res["all_images_pinned"] is True
assert res["all_healthchecks_defined"] is True
assert res["all_resource_limits_defined"] is True
assert res["dependencies_wait_healthy"] is True
assert res["isolated_network_consumption_net"] is True
assert res["passed"] is True
def test_12_clickhouse_sql_ddl_audit() -> None:
"""Validate ClickHouse DDL SCD2, MergeTree 8192, ReplacingMT, AggMT MV & ASOF JOIN."""
res = audit_clickhouse_sql_ddl(LAB_ROOT / "sql" / "01_clickhouse_star_scd2_mv.sql")
assert res["checks_count"] == 6
assert all(res["checks"].values())
assert res["passed"] is True
def test_13_feast_config_yaml_audit() -> None:
"""Validate configs/feature_store.yaml Redis online store, offline store & v3 key ser."""
res = audit_feast_config_yaml(LAB_ROOT / "configs" / "feature_store.yaml")
assert res["checks_count"] == 5
assert all(res["checks"].values())
assert res["passed"] is True
def test_14_feast_repo_ast_audit() -> None:
"""Validate feast_repo/features.py via AST without requiring Feast server runtime."""
res = audit_feast_repo_ast(LAB_ROOT / "feast_repo" / "features.py")
assert res["unsafe_imports"] == []
assert res["zero_eval_exec"] is True
assert res["has_entity"] is True
assert res["has_push_source"] is True
assert res["has_request_source"] is True
assert res["has_feature_view_with_ttl"] is True
assert res["has_on_demand_fv"] is True
assert res["passed"] is True
def test_15_ondemand_shared_transform_determinism() -> None:
"""Verify OnDemandFeatureView pure kernel handles numeric & expired NULL values deterministically."""
valid_a = compute_shared_risk_features(
tx_velocity_1h=5.0,
amount_usd=300.0,
amount_ewma=100.0,
chargeback_flag_count=0.0,
)
valid_b = compute_shared_risk_features(
tx_velocity_1h=5.0,
amount_usd=300.0,
amount_ewma=100.0,
chargeback_flag_count=0.0,
)
assert valid_a == valid_b
assert valid_a["is_high_velocity_burst"] == 1.0
assert valid_a["log_amount_ratio"] == round(float(pl.Series([3.0]).log1p()[0]), 8)
expired = compute_shared_risk_features(
tx_velocity_1h=None,
amount_usd=300.0,
amount_ewma=None,
chargeback_flag_count=None,
)
assert expired == {
"log_amount_ratio": None,
"risk_velocity_score": None,
"is_high_velocity_burst": None,
}
def test_16_cli_artifact_and_workbench_panels_schema() -> None:
"""Run CLI in-process, check 6-KPI/4-Bar/4-Table schema, and verify 0 leftover scratch files."""
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
spec = importlib.util.spec_from_file_location("run_lab10_demo_mod", script_path)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
payload = mod.run_all_benchmarks(num_tx=12_000, num_labels=2_400, seed=42)
assert payload["unit_id"] == "T2-P2-U05"
assert payload["consumption_infrastructure_audit"]["all_infra_checks_passed"] is True
assert payload["otel_telemetry"]["span_count"] == 5
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for kpi in panels["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"}.issubset(kpi.keys())
for bar in panels["bars"]:
assert {"id", "title", "metric_label", "items"}.issubset(bar.keys())
assert len(bar["items"]) >= 2
for tbl in panels["tables"]:
assert {"id", "title", "columns", "rows"}.issubset(tbl.keys())
assert len(tbl["rows"]) >= 3
leftover_parquets = list(LAB_ROOT.rglob("*.parquet"))
leftover_duckdbs = list(LAB_ROOT.rglob("*.duckdb*"))
assert leftover_parquets == [], f"Unexpected leftover parquet files: {leftover_parquets}"
assert leftover_duckdbs == [], f"Unexpected leftover duckdb files: {leftover_duckdbs}"
def test_17_opentelemetry_sdk_spans_and_attributes() -> None:
"""Verify real TracerProvider + SimpleSpanProcessor + InMemorySpanExporter captures spans."""
provider, exporter, tracer = create_in_memory_telemetry("fsds-lab10-pytest")
star_ds = generate_star_scd_dataset(num_tx=1_000, num_customers=100, seed=42)
pit_stream = generate_pit_fraud_stream(num_entities=50, num_labels=150, seed=42)
with tempfile.TemporaryDirectory(prefix="fsds_lab10_otel_") as tmp_dir:
tmp_path = Path(tmp_dir)
run_scd1_vs_scd2_duckdb_audit(star_ds, work_dir=tmp_path, tracer=tracer)
simulate_clickhouse_mergetree_and_mv(
num_fact_rows=24_000, seed=42, work_dir=tmp_path, tracer=tracer
)
pit_ds = build_training_datasets_duckdb_asof(
pit_stream, work_dir=tmp_path, ttl_seconds=3600, tracer=tracer
)
audit_offline_online_parity(pit_ds["pit_df"], sample_size=50, seed=42, tracer=tracer)
provider.force_flush()
spans = exporter.get_finished_spans()
provider.shutdown()
by_name = {span.name: dict(span.attributes or {}) for span in spans}
assert set(by_name.keys()) == {
"lab10.olap.scd1_vs_scd2_audit",
"lab10.olap.clickhouse_mergetree_mv",
"lab10.pit.duckdb_asof_join",
"lab10.feast.offline_online_parity",
}
assert by_name["lab10.olap.scd1_vs_scd2_audit"]["olap.total_transactions"] == 1_000
assert by_name["lab10.olap.scd1_vs_scd2_audit"]["olap.scd2_exact_zero_distortion"] is True
assert by_name["lab10.olap.clickhouse_mergetree_mv"]["clickhouse.mv_benchmark_queries"] == 10
assert by_name["lab10.pit.duckdb_asof_join"]["pit.future_leak_count"] == 0
assert by_name["lab10.feast.offline_online_parity"]["parity.unified_passed"] is True
assert by_name["lab10.feast.offline_online_parity"]["parity.unified_max_abs_diff"] == 0.0
assert list(LAB_ROOT.rglob("*.parquet")) == []
assert list(LAB_ROOT.rglob("*.duckdb*")) == []
12,000 giao dịch (1,575,346.92 USD, 600 khách hàng với 180 người nâng hạng từ Standard lên VIP vào giữa kỳ) trong Lab 10 (test_03), chuyện gì xảy ra khi nối bằng SCD Type 1 so với SCD Type 2 trên DuckDB 2.0?test_03 (artifacts/t2_ch11_lab10_results.json): SCD Type 2 bảo toàn 12,000/12,000 giao dịch với sai số 0.0 USD (Standard: 1,031,469.37 USD, VIP: 543,877.55 USD), còn SCD Type 1 gây sai lệch 537,917.64 USD (34.15%).
ClickHouse MergeTree chứa 10,000,000 dòng (index_granularity = 8,192, gồm 1,221 granules) phục vụ truy vấn lọc theo customer_id trong cửa sổ 7 ngày (test_04). Thiết kế khóa ORDER BY nào tối ưu nhất và mang lại kết quả ra sao?test_04: Đặt cột lọc chọn lọc cao customer_id làm tiền tố ORDER BY cho phép Sparse Primary Index (8,192 dòng/granule) bỏ qua 99.92% granules và giảm lượng dòng đọc 285.0x.
Tests 04–05), nhận định nào ĐÚNG về Incremental Materialized View (AggregatingMergeTree) và cạm bẫy của ReplacingMergeTree(ver)?Tests 04–05: MV cắt 100.0x số dòng quét và tăng tốc 12.14x; ReplacingMergeTree trước lúc merge phình +217,979.90 USD (+18.19%), còn argMax(amount_usd, ver) thu đúng 5,000 đơn (1,198,102.88 USD, sai số 0.0 USD).
> 15,000 QPS đồng thời trên luồng Kafka Upsert với độ trễ P99 < 20 ms, cơ chế nào của Apache Pinot nổi bật so với kiến trúc thuần ClickHouse / Trino?Apache Pinot tối ưu hóa đặc biệt cho concurrency cực cao (Star-Tree giới hạn số dòng quét ở lá + Kafka Realtime Upsert), trong khi ClickHouse mạnh về ad-hoc SQL, nén cao, Incremental/Refreshable MV và ASOF JOIN.
Tests 07–08), phép nối Point-in-Time chuẩn xác \(t^*(e_i, t_{\text{label}, i}) = \max \{ t_j \le t_{\text{label}, i} \land (t_{\text{label}, i} - t_j) \le \text{TTL} \}\) thực thi qua DuckDB 2.0 ASOF LEFT JOIN (TTL = 3,600s) mang lại kết quả gì trên 2,400 nhãn gian lận?Tests 07–08: DuckDB ASOF LEFT JOIN đạt 0.0% (0/2,400) rò rỉ tương lai so với 81.75% (1,962/2,400) của Naive join, và khóa đúng 232 dòng quá hạn TTL = 3,600s thành NULL.
test_09), mô hình LogisticRegression huấn luyện bằng Naive Join đạt ROC-AUC = 0.9853 (PR-AUC = 0.9752) ở kiểm định offline nhưng lại rơi tự do xuống 0.5143 (-0.4710 AUC) khi chấm trên tập phục vụ nhân quả thực tế (OOT Serving)?test_09: Naive tạo ảo giác 0.9853 nhưng sụp xuống 0.5143 OOT (-0.4710 collapse, PR-AUC = 0.2060); ngược lại PIT ASOF giữ vững 0.8953 CV -> 0.8858 OOT (PR-AUC = 0.7569, chênh lệch chỉ 0.0095, thắng Naive +0.3715 AUC).
500 yêu cầu phục vụ trực tuyến của Lab 10 (test_10), cơ chế kỹ thuật nào nâng tỷ lệ đồng nhất từ 0.0% (500 vi phạm, 48 lỗi TTL, max_abs_diff = 4.79) lên 100.0% (0 vi phạm, max_abs_diff = 0.0)?Tests 10, 15: Chia sẻ cùng một hàm biến đổi OnDemandFeatureView và đồng bộ quy tắc TTL -> NULL triệt tiêu 100% Training–Serving Skew (0/500 vi phạm, max_abs_diff = 0.0).
ClickHouse + Redis + Postgres + Feast trong Lab 10 (Tests 11–14, 16) sẵn sàng vận hành và an toàn bảo mật ngay cả khi kiểm định tự động trong CI không có Docker daemon, bộ kiểm toán tĩnh infra_audit.py xác minh những bất biến nào?Tests 01, 11–14, 16: Toàn bộ 4/4 tạo tác hạ tầng đạt PASS, AST 0 unsafe deserializers, 0 lỗi ruff/mypy, và 0 tệp .parquet/.duckdb rác.
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 — Mô hình hóa Đa chiều & SCD Type 1 vs. SCD Type 2
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết điều kiện phân hoạch nửa mở \([t_{\text{from}}, t_{\text{to}})\) của SCD Type 2 và thay các giá trị doanh thu từng phân khúc vào công thức độ méo hồi tố \(\Delta R_{\text{SCD1}}(c)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm chứng bằng pytest -k "test_02 or test_03" -v và đối chiếu mục scd1_vs_scd2_audit trong artifacts/t2_ch11_lab10_results.json.
Tiêu chí Đáp án & Số đối chứng
Trên 12,000 giao dịch (1,575,346.92 USD, 180 khách nâng hạng Standard -> VIP), SCD Type 1 dịch chuyển oan 268,958.82 USD từ Standard sang VIP (tổng méo tuyệt đối 537,917.64 USD = 34.15%); SCD Type 2 nối theo khoảng [valid_from, valid_to) đạt sai số tuyệt đối 0.0 USD (0.0%).
Bài tập 2 — ClickHouse MergeTree Granule Pruning, AggregatingMergeTree MV & ReplacingMergeTree
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính số granules \(N_g = \lceil 10{,}000{,}000 / 8{,}192 \rceil = 1{,}221\) và giải thích cơ chế INSERT Trigger của AggregatingMergeTree MV kèm bẫy chưa merge nền trên ReplacingMergeTree(ver).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_04 or test_05" -v và đọc cấu trúc DDL trong sql/01_clickhouse_star_scd2_mv.sql.
Tiêu chí Đáp án & Số đối chứng
Đặt ORDER BY (customer_id, toStartOfHour(tx_ts), tx_ts) bỏ qua 99.92% granules (1 vs 285 granules = 285.0x); AggregatingMergeTree MV cắt dòng quét 240,000 -> 2,400 (100.0x) và tăng tốc 12.14x (344.08 -> 28.35 ms / 10 truy vấn); ReplacingMergeTree chưa merge phình +217,979.90 USD (+18.19%), còn argMax(amount_usd, ver) đạt 0.0 USD sai số.
Bài tập 3 — Chuyên đề Sâu #15: Toán học Point-in-Time ASOF JOIN & Hết hạn TTL
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích hai điều kiện đồng thời \(t_j \le t_{\text{label}}\) và \(t_{\text{label}} - t_j \le \text{TTL}\) trong truy vấn ASOF LEFT JOIN của DuckDB 2.0 (src/feast_olap_pit_lab/pit_feature_store.py).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_06 or test_07 or test_08" -v và kiểm tra giá trị naive_future_leak_rate_pct, pit_future_leak_rate_pct và ttl_expired_null_count.
Tiêu chí Đáp án & Số đối chứng
Naive Latest-Window Join làm rò rỉ tương lai trên 81.75% (1,962 / 2,400) nhãn; DuckDB ASOF LEFT JOIN kết hợp khóa hạn TTL = 3,600s đạt 0.0% (0 rò rỉ) và đưa chính xác 232 nhãn quá hạn TTL về NULL.
Bài tập 4 — Giải phẫu Thảm họa Offline Mirage -> Production Collapse
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi hành vi của chargeback_flag_count và tx_velocity_1h trong khoảng 30 phút – 4 giờ sau giao dịch gian lận, giải thích vì sao mô hình Naive học trọng số bị đầu độc.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k test_09 -v và đối chiếu đồng thời cả ROC-AUC lẫn PR-AUC giữa Naive và PIT ASOF trong fraud_leakage_ml_ablation.
Tiêu chí Đáp án & Số đối chứng
Naive đạt ảo giác ROC-AUC = 0.9853 (PR-AUC = 0.9752) rồi rơi xuống 0.5143 (PR-AUC = 0.2060, tụt -0.4710) trên OOT Serving; PIT ASOF giữ vững 0.8953 CV -> 0.8858 OOT (PR-AUC = 0.7569, chênh 0.0095, thắng Naive +0.3715 ROC-AUC).
Bài tập 5 — Kiểm toán Training–Serving Parity & Feast OnDemandFeatureView
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh hàm compute_shared_risk_features trong feast_repo/features.py với 3 lỗi kinh điển trong nhánh broken_online_pipeline của audit_offline_online_parity.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_15" -v để kiểm chứng 500 yêu cầu audit và bảo toàn giá trị None khi hết hạn TTL.
Tiêu chí Đáp án & Số đối chứng
Nhánh viết tay tách rời vi phạm 500 / 500 (0.0% pass, 48 lỗi lệch TTL, max_abs_diff = 4.789989); nhánh hợp nhất OnDemandFeatureView + đồng bộ TTL đạt 0 / 500 vi phạm (100.0% parity, max_abs_diff = 0.0).
Bài tập 6 — Thiết kế Kiến trúc ClickHouse + Feast + Redis, Telemetry OpenTelemetry & Kiểm toán Toàn phần
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dựa vào Playbook Trụ cột 2 (§2.2) để phân định khi nào chọn ClickHouse vs Apache Pinot, Batch materialize vs PushSource, và rà soát 4 kiểm toán tĩnh trong infra_audit.py cùng 5 span OpenTelemetry.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy đầy đủ ruff check src tests scripts feast_repo, mypy src, và pytest -p no:cacheprovider -v (17/17 tests).
Tiêu chí Đáp án & Số đối chứng
4/4 kiểm toán hạ tầng (docker-compose.yml 4 services, 01_clickhouse_star_scd2_mv.sql 6/6, feature_store.yaml 5/5, feast_repo/features.py AST 0 unsafe imports) đều PASS; 5 OpenTelemetry spans xác thực (Test 17), 17/17 pytest (0 skip), 0 lỗi ruff/mypy, 0 tệp .parquet/.duckdb rác.