Chương 08 — Tầng Lưu trữ Open Lakehouse (Object Storage, Parquet Zone Maps, Delta Lake vs. Apache Iceberg, OCC, Liquid Clustering, VACUUM) & Engine Truy vấn (Trino, Open Catalogs, DuckDB / Polars)
Từ Parquet Zstd (3.47x, 75.28% Column Pruning) & Zone Maps (0%->85% RG skip) đến Delta Lake thật (Bronze->Silver->Gold, Time Travel, Compaction 12->1 & VACUUM >=169h), Iceberg Hidden Partitioning (98.75% skip), Liquid Clustering (3.34x ít WA) & DuckDB vs Polars (0.0 diff).
Unit ID:
T2-P2-U02
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 (R30): Bài 8 Data Engineering — Storage Layer (Introduction to storage layer,From Data Lake to Data Swamp,Lake House,Multi-hop architecture,Lab: Constructing a Lakehouse from scratch [Delta Lake, Trino, Hive, MinIO]) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 07):labs/lab-07-open-lakehouse-delta-iceberg-trino/(lakehouse_storage_lab)
Tình huống Mở đầu: Năm Thảm họa Tầng Lưu trữ Khi Biến Object Storage Thành "Đầm lầy Dữ liệu" (Data Swamp)#
Sau khi hoàn thiện đường ống nhập luồng Kafka/Debezium ở Chương 07, một đội kỹ sư Dữ liệu đổ thẳng hàng triệu sự kiện đơn hàng dưới dạng CSV/Parquet rời rạc lên bucket S3/MinIO không có tầng siêu dữ liệu giao dịch (Open Table Format). Chỉ sau ba tháng vận hành sản xuất, năm thảm họa kinh điển lập tức bùng phát:
- Hóa đơn Lưu trữ & Quét Toàn bảng Bùng nổ (
3.47xDung lượng,0.0%Bỏ qua Row Group): Lưu trữ thô không cột (CSV) hoặc ghi tệp Parquet không sắp xếp theo khóa lọc khiến mọi Row Group đều chứa toàn bộ biên độ thời gian[0, 59]. Trên thực nghiệm50,000đơn hàng củalakehouse_storage_lab, chuyển sang ParquetZstd+ Dictionary/RLE cắt dung lượng từ3,381,970 Bxuống974,275 B(3.47xnhỏ hơn), cắt tỉa2/10cột tiết kiệm75.28%I/O, và sắp xếp theoday_offsetnâng tỷ lệ bỏ qua Row Group qua Zone Maps Min/Max từ0.0%(20/20RG đọc) lên85.0%(3/20RG đọc, giảm6.67x). - Đọc Dữ liệu Dở dang & Nhiễm độc Lược đồ (
Data Swamp): Khi một job ETL sập giữa chừng lúc đang ghi50tệp Parquet lên S3 (nơi không có lệnhrename()thư mục nguyên tử), bảng BI đọc phải dữ liệu nửa vời; đồng thời một dịch vụ nguồn tự ý thêm cột lỗi làm vỡ hàng loạt pipeline hạ lưu do thiếu Schema Enforcement. TrênDelta Lakethật trong Lab 07, hệ thống lập tức chặn lô dữ liệu sai bằngSchemaMismatchError, cho phép tiến hóa có kiểm duyệt (schema_mode="merge"thêmloyalty_tier), và tầngSilverlọc sạch11,534bản ghi trùng lặp/hủy/âm tiền để giữ chuẩn38,469đơn hàng hợp lệ. - Bão Tệp Nhỏ (
Small-File Storm) Đốt Sạch IOPS S3/MinIO: Pipeline micro-batch ghi mỗi phút một tệp nhỏ vài trăm KB tạo ra hàng chục nghìn đối tượng: thời gianS3 LIST/HEADvà đọc Footer lớn hơn cả thời gian tính toán thực. Trong Lab 07, chạydt.optimize.compact()gom gọn12tệp nhỏ xuống đúng1tệp Parquet tối ưu (12.0xgiảm tệp) mà bảo toàn100%dòng dữ liệu. - Sập Toàn bộ Truy vấn Đang Chạy Vì
VACUUM RETAIN 0 HOURS: Một kỹ sư chạy xóa tệp vật lý vớiretention_hours = 0nhằm tiết kiệm đĩa ngay khi truy vấn Trino kéo dài4giờ đang đọc snapshot cũ, gây lỗiFileNotFoundExceptionhàng loạt và phá hủy hoàn toàn quyền quay ngược thời gian (Time Travel) theo SLA168giờ. Bộ kiểm định bất đẳng thức an toànVACUUMtrong Lab 07 khóa cứng ngưỡng tối thiểu169.0giờ (max(4, 168) + 1). - Khuếch đại Ghi Compaction Khổng lồ (
WA = 5.14x) & Bẫy Phân vùng Hive (80.0xChậm): Sắp xếp từ điểnORDER BY (x, y)sụp đổ hoàn toàn về0.0%skip khi người dùng chỉ lọc theo cột thứ haiy; cònZ-Orderingcổ điển buộc viết lại toàn bộ phân vùng sau mỗi lô dữ liệu mới (WA = 5.14x). Chuyển sangLiquid Clusteringgiữ nguyên tỷ lệ cắt tỉa 2D93.75%(79.69%cho riêng cột 2) đồng thời hạ khuếch đại ghi xuống1.54x(3.34xthấp hơn); vàApache IcebergHidden Partitioning (days(event_ts)) bỏ qua98.75%tệp (237/240), nhanh hơn80.0xso với bẫy quên cột phân vùng trên bảng Hive cũ.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 08 và lakehouse_storage_lab (Lab 07), kỹ sư Dữ liệu & AI nắm vững:
- Nội tại Object Storage & Định dạng Cột
Apache Parquet: Giải thích không gian tên phẳng, tính bất biến, giới hạn IOPS/prefix, phương trình băng thông hiệu dụng \(B_{\text{eff}}(S)\) của bài toán tệp nhỏ, cấu trúc vật lýRow Group -> Column Chunk -> Data Page -> Thrift Footer, mã hóaDictionary/RLE/Delta, và toán học Column Pruning + Zone-Map Row-Group Skipping. - Chuyển hóa
Data Lake -> Lakehouse& Kiến trúcMedallionĐa chặng: Nhận diện nguyên nhân gốc rễ sinh Data Swamp và thiết kế chuẩn hợp đồng dữ liệu 3 tầngBronze -> Silver -> Goldvới khử trùng lặp, Schema Enforcement và Schema Evolution an toàn. - Kiến trúc Nội tại Open Table Formats (
Delta Lakevs.Apache Iceberg+UniForm/XTable): Đối chiếu nhật ký giao dịch tuyến tính_delta_log/*.json+ Parquet Checkpoint với cây siêu dữ liệu 3 tầng Iceberg (metadata.json -> manifest-list -> manifest-file -> data-file), Hidden Partitioning, Optimistic Concurrency Control (OCC), và Time Travel. - Tối ưu Bố cục Vật lý & An toàn Vận hành: Thiết lập
OPTIMIZEbin-packing, phân biệt toán học đường cong Morton Z-Ordering với Liquid Clustering (khuếch đại ghi \(\text{WA}\)), và cưỡng chế bất đẳng thức cửa sổ an toànVACUUM. - Hệ sinh thái Engine Truy vấn & Open Catalog 2026: Hiểu kiến trúc MPP không-đĩa của
Trino+ sự chuyển dịch từHive Metastoresang REST Open Catalogs (Apache Polaris,Unity Catalog,Nessie), kết hợp thực thi vectorized đơn nút siêu tốc trênDuckDB 2.xvàPolars 2.xkiểm chứng qua16/16 pytest100% offline.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P2-U02, R30)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R30) |
Nâng cấp Chuẩn SOTA 2026 (ch-08) |
Mục trong Chương 08 | Tạo tác & Kiểm thử (lakehouse_storage_lab) |
|---|---|---|---|
1. Introduction to storage layer (R30) |
Nội tại Object Storage (MinIO/S3/GCS): flat namespace, strong consistency, multipart upload, Small-File Roofline \(B_{\text{eff}}(S)\); nội tại Apache Parquet: Row Group, Column Chunk, Dictionary/RLE/Delta, Thrift Footer, Zone Maps & Bloom Filters |
Trụ cột 1 (§1.1–§1.2) + Widget 1 | parquet_engine.py (generate_order_events, benchmark_csv_vs_parquet, benchmark_parquet_zone_map_pruning), Tests 02, 03, 04 |
2. From Data Lake to Data Swamp (R30) |
Phân tích 4 điểm gãy cấu trúc Data Lake (không ACID, mất kiểm soát lược đồ, bất khả thi GDPR Delete, lệch số liệu Lake–Warehouse) & cơ chế chặn từ gốc bằng Schema Enforcement | Trụ cột 1 (§1.3) + Trụ cột 3 (Case 3, 4) | delta_medallion.py (SchemaMismatchError enforcement & Silver contract), Tests 05, 06 |
3. Lake House (R30) |
Open Table Formats (Delta Lake vs. Apache Iceberg + UniForm/XTable): _delta_log vs 3-tier Avro manifests, OCC (WriteSerializable/Serializable), Time Travel, Hidden Partitioning, Z-Ordering vs. Liquid Clustering, VACUUM Safety; Query Engines (Trino, Polaris/Unity, DuckDB/Polars) |
Trụ cột 1 (§1.4–§1.6) + Trụ cột 2 (§2.1–§2.3) + Mermaid 2, 3 + Widget 2, 3 | delta_medallion.py, iceberg_occ_sim.py, query_engines.py, Tests 07–14 |
4. Multi-hop architecture (R30) |
Thiết kế Medallion (Bronze -> Silver -> Gold) với hợp đồng chất lượng, cửa sổ khử trùng lặp ROW_NUMBER(), bảo toàn bất biến tổng doanh thu và bảo trì OPTIMIZE |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1) + Mermaid 1 | delta_medallion.py + sql/01_medallion_trino.sql, Tests 06, 15 |
5. Lab: Constructing a Lakehouse from scratch (R30: Delta Lake, Trino, Hive, MinIO) |
Stack triển khai thật docker-compose.yml (MinIO, PostgreSQL, Hive Metastore, Trino) + trino_delta_catalog.properties + 01_medallion_trino.sql song hành thực thi thật PyArrow + Delta Lake 1.6 + DuckDB 2.0 + Polars 2.1 offline 100% |
Trụ cột 3 (Mã thực thi) + Trụ cột 4 (§4.1–§4.3) | Toàn bộ lab-07-open-lakehouse-delta-iceberg-trino/ (16/16 pytest PASS, 0 skip, ruff, mypy, artifacts/t2_ch08_lab07_results.json) |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 08 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 08 & lakehouse_storage_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(R_{\text{comp}}\) | \(\mathbb{R}_{> 0}\) | Tỷ số nén lưu trữ \(S_{\text{CSV}} / S_{\text{Parquet}}\) | Đo trực tiếp trên đĩa với codec Snappy (2.51x) và Zstd (3.47x) |
| \(B_{\text{eff}}(S)\) | \(\text{MB/s}\) | Băng thông đọc hiệu dụng của tệp cỡ \(S\) trên Object Storage có độ trễ RPC \(t_{\text{req}}\) và băng thông đỉnh \(B\) | \(B_{\text{eff}}(S) = S / (t_{\text{req}} + S / B)\) — tụt mạnh khi \(S \ll B \cdot t_{\text{req}}\) |
| \(\rho_{\text{skip}}, \rho_{\text{io}}\) | \([0, 1]\) | Tỷ lệ bỏ qua Row Group (\(G_{\text{skipped}} / G_{\text{total}}\)) và tổng tỷ lệ giảm I/O kết hợp Column Pruning + Skipping | Bỏ qua Row Group \(g \iff \max_g < a \lor \min_g > b\) |
| \(v, s_t\) | \(\mathbb{N}_{\ge 0}\) | Số phiên bản commit Delta (0000...v.json) hoặc mã Snapshot Iceberg tại thời điểm \(t\) |
Truy vấn version=v tái tạo chính xác trạng thái bảng bất biến (Time Travel) |
| \(Z(x, y)\) | uint64 |
Khóa đường cong không gian Morton Z-Order đan xen \(k\) bit tọa độ \(x, y\) | \(Z(x,y) = \sum_{i=0}^{k-1}(x_i 2^{2i} + y_i 2^{2i+1})\) |
| \(\text{WA}_{\text{compact}}\) | \(\mathbb{R}_{\ge 1}\) | Hệ số khuếch đại ghi của các vòng nén/gom cụm vật lý | \(1 + B_{\text{rewritten}} / B_{\text{initial}}\); Liquid Clustering hạ từ 5.14x xuống 1.54x |
| \(T_{\text{retention}}\) | Giờ (hours) |
Ngưỡng tuổi giữ tệp đã bị remove trước khi VACUUM xóa vĩnh viễn trên Object Storage |
Bắt buộc \(T_{\text{retention}} \ge \max(T_{\text{query\_max}}, T_{\text{time\_travel\_SLA}}) + \delta_{\text{clock}}\) |
Trụ cột 1 — Nguyên lý Gốc: Object Storage, Nội tại Parquet, Medallion, Open Table Formats (Delta/Iceberg), OCC, Liquid Clustering & Engine Truy vấn#
1.1 Object Storage (MinIO / S3 / GCS) & Toán học Bài toán Tệp Nhỏ (Small-File Problem)#
Khác với hệ thống tệp POSIX cục bộ hay HDFS vốn duy trì cây thư mục inode hỗ trợ đổi tên thư mục nguyên tử trong \(O(1)\), Object Storage vận hành theo mô hình khóa–giá trị bất biến trên không gian tên phẳng (flat namespace): (bucket, key) -> (immutable_bytes, metadata).
-
Ba Hệ quả Kiến trúc Không thể Bỏ qua:
- Không có
rename()nguyên tử: Đường dẫnsilver/orders/dt=2026-03-01/part-000.parquetchỉ là chuỗi tiền tố (prefix), không phải thư mục thật. Đổi tên một phân vùng \(K\) tệp tốn \(K\) thao tácCOPY+ \(K\) thao tácDELETE(\(O(K)\) RPC và nhân đôi lưu lượng mạng) — nguyên nhân lịch sử gây ra bảng hỏng khi Spark cổ điển sập giữa pha commit. - Strong Read-After-Write Consistency (nhưng không có Multi-Object ACID): Từ cuối năm 2020, AWS S3 (cũng như GCS và MinIO) bảo đảm nhất quán đọc-sau-ghi mạnh cho mọi thao tác
PUT/DELETE/LISTđơn lẻ và hỗ trợConditional Put (If-None-Match)từ 2024. Tuy nhiên, nếu một bảng trải rộng trên50tệp Parquet, Object Storage bản thân nó không thể cam kết nguyên tử cả50tệp cùng lúc — vai trò đó thuộc về Open Table Format. - Multipart Upload & Prefix IOPS: Tệp lớn (
> 100 MB) được tách thành các mảnh5 MB–5 GiBtải lên song song; còn lưu lượng truy cập bị giới hạn theo prefix (~3,500 PUT/s,~5,500 GET/smỗi prefix trên S3).
- Không có
-
Phương trình Roofline I/O của Bài toán Tệp Nhỏ: Giả sử mỗi yêu cầu HTTP
GETtrên Object Storage chịu độ trễ cố định \(t_{\text{req}}\) (kết nối TLS, định tuyến, đọc Parquet Footer) và băng thông truyền dữ liệu đỉnh \(B\). Khi đọc một tệp kích thước \(S\), thời gian tổng là \(T(S) = t_{\text{req}} + S / B\), cho ra băng thông hiệu dụng:\[B_{\text{eff}}(S) = \frac{S}{t_{\text{req}} + S / B} = \frac{B}{1 + \frac{B \cdot t_{\text{req}}}{S}}\]Đặt kích thước giao điểm \(S^* = B \cdot t_{\text{req}}\). Với \(B = 125\text{ MB/s}\) và \(t_{\text{req}} = 25\text{ ms}\), ta có \(S^* = 3.125\text{ MB}\):
- Nếu pipeline streaming tạo tệp nhỏ \(S = 0.5\text{ MB}\), băng thông hiệu dụng rơi xuống \(B_{\text{eff}} \approx 17.2\text{ MB/s}\) (lãng phí
86%băng thông và bùng nổ chi phíS3 GET/LIST). - Nếu gom compaction về kích thước tối ưu \(S \in [128\text{ MB}, 512\text{ MB}]\), ta có \(S \gg S^*\) nên \(B_{\text{eff}}(256\text{ MB}) \approx 123.5\text{ MB/s}\) (
98.8%băng thông đỉnh).
- Nếu pipeline streaming tạo tệp nhỏ \(S = 0.5\text{ MB}\), băng thông hiệu dụng rơi xuống \(B_{\text{eff}} \approx 17.2\text{ MB/s}\) (lãng phí
1.2 Cấu trúc Vật lý Apache Parquet, Mã hóa Cột & Toán học Zone-Map Pruning#
Apache Parquet là định dạng lưu trữ lai ngang–dọc (PAX — Partition Attributes Across): chia bảng theo chiều ngang thành các Row Group (128 MB–512 MB), rồi bên trong mỗi Row Group lưu dữ liệu theo chiều dọc thành các Column Chunk và Data Page (~1 MB), kết thúc bằng File Footer mã hóa Apache Thrift nằm ở cuối tệp ([Magic "PAR1"] ... [Footer][FooterLen 4B]["PAR1"]).
-
Ba Cơ chế Mã hóa Đẩy Hệ số Nén \(R_{\text{comp}} = S_{\text{CSV}} / S_{\text{Parquet}}\):
- Dictionary Encoding: Thay các chuỗi lặp (
region,category,status) bằng mảng từ điển nhỏ và dãy mã nguyênint8/int16. - RLE / Bit-Packing Hybrid: Nén các chuỗi giá trị giống nhau liên tiếp (cực mạnh sau khi sắp xếp) và mã hóa
Definition/Repetition Levelscho giá trịNULL/lồng nhau theo mô hình Google Dremel. - Delta Encoding (
DELTA_BINARY_PACKED) + Block Compression (Snappy/Zstd): Lưu hiệu \(\Delta_i = x_i - x_{i-1}\) cho khóa đơn điệu (order_id,event_ts) rồi nén khối bằngZstd(nén chặt hơnSnappy20%–35%với tốc độ giải nén rất cao). Trên50,000đơn hàng trong Lab 07:CSV = 3,381,970 B\(\to\)Parquet Snappy = 1,347,579 B(2.51x) \(\to\)Parquet Zstd = 974,275 B(3.47x) và tốc độ đọc chọn lọc nhanh hơn6.9x.
- Dictionary Encoding: Thay các chuỗi lặp (
-
Phương trình Giảm I/O Từ Column Pruning + Row-Group Zone-Map Skipping: Engine truy vấn chỉ cần đọc
Footerở cuối tệp bằng một lệnhHTTP Range GET, sau đó áp dụng đồng thời hai phép cắt tỉa:- Column Pruning (Projection Pushdown): Chỉ tải các
Column Chunkthuộc tập cột truy vấn \(Q \subset \{1, \dots, C\}\). Trong Lab 07, đọc2/10cột (region,amount_usd) cắt giảm75.28%byte nén phải đọc. - Predicate Pushdown / Row-Group Skipping (Zone Maps): Mỗi Column Chunk trong Footer lưu thống kê \([\min_g, \max_g]\) và
null_count. Với vị từ khoảngcol BETWEEN a AND b, Row Group \(g\) bị bỏ qua hoàn toàn (0byte dữ liệu đọc) nếu và chỉ nếu:\[\max_g < a \quad \lor \quad \min_g > b\]
Kết hợp cả hai kỹ thuật, tỷ lệ cắt giảm I/O tổng hợp trên tổng byte nén của tệp là:
\[\rho_{\text{skip}} = \frac{G_{\text{skipped}}}{G_{\text{total}}}, \qquad \rho_{\text{io}} = 1 - \left(\frac{\sum_{j \in Q} B_j}{\sum_{i=1}^{C} B_i}\right)\!\cdot\!\left(1 - \rho_{\text{skip}}\right)\]- Bẫy Dữ liệu Không Sắp xếp: Trong Lab 07 (
20Row Group, mỗi RG2,500dòng), khi dữ liệu đến theo thứ tự ngẫu nhiên, mọi Row Group đều có \([\min_g, \max_g] = [0, 59]\) nên với truy vấnday_offset BETWEEN 52 AND 56, tỷ lệ bỏ qua là0.0%(20/20RG đọc). Khi sắp xếp trước theoday_offset, các khoảng Zone Map tách rời ([0, 3], [3, 6], ...), đẩy \(\rho_{\text{skip}}\) lên85.0%(17/20RG bị bỏ qua, chỉ đọc3/20RG — giảm6.67x)! - Split-Block Bloom Filters & Page Index (
ColumnIndex/OffsetIndex): Với cột định danh phân phối đều (order_id,uuid) nơi khoảng Min/Max luôn rộng, Parquet cho phép đính kèm Bloom Filter ở mức Column Chunk để trả lời truy vấn bằng (WHERE order_id = k) với0%âm tính giả và \(\epsilon \approx 1\%\) dương tính giả. Ngoài ra, từ chuẩn Parquet1.11+, Page-Level Zone Maps (ColumnIndex) cho phép engine bỏ qua từng Data Page (~1 MB) nằm bên trong một Row Group chưa bị loại — giảm thêm I/O giải nén CPU ngay cả với tệp lớn512 MB.
- Column Pruning (Projection Pushdown): Chỉ tải các
-
Biểu diễn Dữ liệu Lồng nhau &
NULLTheo Thuật toán Google Dremel (Definition&Repetition Levels): Một câu hỏi kinh điển khi lưu JSON/Protobuf lồng nhau (ví dụ mảngitems[].sku_idcó thểNULLở nhiều tầng) vào định dạng cột phẳng là: làm sao tái dựng đúng cấu trúc cây lồng nhau mà không lưu khóa cha lặp lại? Apache Parquet sử dụng cặp số nguyên rất nhỏ (nén mạnh bằng RLE/Bit-Packing):Definition Level (d): Đếm số trường tùy chọn (optional/repeated) trên đường dẫn từ gốc xuống lá thực sự khácNULL. Nếu \(d < d_{\max}\), giá trị lá làNULLtại đúng cấp \(d\) và không ghi bất kỳ byte giá trị nào vào luồng dữ liệu chính (cực kỳ tiết kiệm cho cột thưa trong bảng đặc trưng ML).Repetition Level (r): Cho biết ở độ sâu lặp nào của đường dẫn, một giá trị mới bắt đầu danh sách con mới (\(r = 0\) đánh dấu bắt đầu một bản ghi mới hoàn toàn).- Late Materialization (Vật chất hóa Muộn): Thay vì giải nén đồng loạt toàn bộ các cột của một Row Group rồi mới lọc
WHERE region = 'APAC', các engine vectorized hiện đại (DuckDB,Polars,Trino,Velox) chỉ giải nén cột lọcregiontrước, tạo một Selection Vector (mảng chỉ số dòng khớp), rồi chỉ giải nén các Data Page chứa đúng các chỉ số đó trên cộtamount_usd— cắt mạnh băng thông bộ nhớ RAM và chu kỳ giải mã CPU.
1.3 Từ Data Lake Tới Data Swamp, Kiến trúc Lakehouse & Mô hình Đa chặng Medallion#
Data Lake thế hệ đầu (lưu tệp thô trực tiếp trên HDFS/S3) thất bại ở quy mô doanh nghiệp và thoái hóa thành Data Swamp vì bốn thiếu hụt cấu trúc: (1) thiếu giao dịch ACID dẫn đến đọc dở dang khi job sập; (2) thiếu Schema Enforcement cho phép dữ liệu lỗi/đổi kiểu tràn vào bảng phân tích; (3) không thể UPDATE/DELETE hiệu quả (gây bế tắc tuân thủ GDPR/CCPA và CDC upsert); và (4) buộc duy trì kiến trúc hai tầng Lake + Warehouse đắt đỏ, nhân đôi lưu trữ và gây lệch KPI giữa ML với BI.
Kiến trúc Lakehouse (Armbrust et al., CIDR 2021) gắn một Open Table Format (Delta Lake / Apache Iceberg) trực tiếp lên Object Storage + Parquet, kết hợp mô hình tổ chức chất lượng Multi-Hop Medallion:
Tầng Medallion |
Bản chất & Bất biến Dữ liệu | Chế độ Ghi & Kiểm soát Lược đồ | Ví dụ Thực thi Trong Lab 07 (50,000 Đơn hàng) |
|---|---|---|---|
Bronze (Raw) |
Nối đuôi bất biến, giữ nguyên lịch sử gốc kèm siêu dữ liệu nhập để tái xử lý (replay) bất cứ lúc nào | Append-only + Schema Enforcement chặn cột rác (SchemaMismatchError); chỉ tiến hóa bằng schema_mode="merge" có kiểm duyệt |
v0 = 50,000 dòng (10 cột) \(\to\) chặn lô sai \(\to\) v1 = 50,003 dòng (11 cột thêm loyalty_tier) |
Silver (Conformed) |
Đã làm sạch, chuẩn hóa kiểu, khử trùng lặp theo order_id mới nhất, loại đơn hủy & giá trị âm |
MERGE INTO / Overwrite ACID + OPTIMIZE compaction / Liquid Clustering |
Lọc bỏ 11,534 dòng trùng/hủy/âm \(\to\) giữ 38,469 đơn hàng chuẩn (3,395,566.59 USD) |
Gold (Business Mart) |
Bảng tổng hợp nghiệp vụ (Star Schema, KPI doanh thu theo vùng/danh mục, bảng đặc trưng ML) |
Bảng nhỏ gọn đọc dưới vài chục mili-giây bởi Trino, DuckDB, Polars, BI |
24 nhóm (4 vùng \(\times\) 6 danh mục), tổng doanh thu khớp tuyệt đối 3,395,566.59 USD |
1.4 So sánh Nội tại Open Table Formats: Delta Lake vs. Apache Iceberg (+ UniForm / XTable)#
Hai chuẩn bảng mở thống trị hệ sinh thái Lakehouse 2026 giải bài toán ACID trên Object Storage bằng hai cấu trúc siêu dữ liệu khác biệt sâu sắc:
| Tiêu chí Kỹ thuật | Delta Lake (3.x / 4.0 + delta-rs) |
Apache Iceberg (v2 / v3) |
Hội tụ 2026 (UniForm & Apache XTable) |
|---|---|---|---|
| Cấu trúc Siêu dữ liệu | Log Tuyến tính (_delta_log/000...v.json) chứa actions protocol, metaData, add, remove, commitInfo + Parquet Checkpoint mỗi 10–100 commit |
Cây 3 Tầng Bất biến: Catalog Pointer (CAS) \(\to\) vN.metadata.json \(\to\) Manifest List (Avro) \(\to\) Manifest File (Avro) \(\to\) Data/Delete Files |
Delta UniForm sinh song song metadata Iceberg lúc commit; Apache XTable dịch siêu dữ liệu 2 chiều không nhân đôi Parquet |
| Cơ chế Commit Nguyên tử | PUT If-None-Match (Conditional Put S3/GCS) hoặc Lock/Catalog Coordinator chọn duy nhất 1 tệp v+1.json |
Phép Compare-and-Swap (CAS) con trỏ current-metadata-location tại REST Catalog (Polaris/Unity/HMS) |
Một giao dịch ghi duy nhất, nhiều engine (Trino, Snowflake, Spark, DuckDB) cùng đọc |
| Phân vùng & Tiến hóa | Phân vùng truyền thống hoặc Liquid Clustering (thay thế hoàn toàn phân vùng vật lý) | Hidden Partitioning (days(event_ts), bucket(16, id)) + Partition Evolution không viết lại dữ liệu cũ |
Triệt tiêu hoàn toàn bẫy quên cột phân vùng của Hive (80.0x trong Lab 07) |
| Cập nhật Dòng Nhỏ (MoR) | Deletion Vectors (Roaring Bitmap đánh dấu dòng đã xóa không cần viết lại cả tệp Parquet) | Positional Delete Files & Equality Delete Files (Iceberg v3 thêm Deletion Vectors thống nhất) | Cả hai định dạng đều hội tụ về Roaring Bitmap Deletion Vectors ở thế hệ 2025–2026 |
Cơ chế Vận hành Sâu Bên trong Cả Hai Định dạng#
-
Nhật ký Giao dịch
_delta_log&S3 Conditional Put(Delta Lake):- Mỗi phiên bản \(v\) là một tệp NDJSON bất biến tên cố định 20 chữ số (
00000000000000000000.json,00000000000000000001.json, ...). Khi hai writer cùng cố ghi phiên bảnv+1lên AWS S3 / GCS / MinIO, lệnhPUTkèm tiêu đềIf-None-Match: *bảo đảm chính xác một writer nhận200 OKvà writer còn lại nhận412 Precondition Failedđể kích hoạt pha kiểm tra xung độtOCC— loại bỏ hoàn toàn nhu cầu bảng khóa DynamoDB bên ngoài trong kiến trúc cũ. - Để tránh việc đọc lại hàng nghìn tệp JSON sau nhiều tháng chạy streaming, Delta tạo định kỳ V2 Checkpoint Parquet (chứa trạng thái hợp nhất của mọi tệp
addđang hoạt động kèm thống kê Min/Max) và cập nhật tệp con trỏ_last_checkpoint. Nhờ vậy, reader chỉ cần đọc1checkpoint + tối đa vài tệp JSON mới nhất trong \(O(1)\). - Copy-on-Write (
CoW) vs. Merge-on-Read (MoR— Deletion Vectors): Khi xóa9dòng trên tệp Parquet256 MB, chế độCoWbuộc đọc và viết lại toàn bộ256 MB(tốn CPU & khuếch đại ghi lớn). BậtDeletion Vectors(Roaring Bitmap nén chỉ vài trăm byte gắn cùng hành độngadd) cho phép đánh dấu9vị trí dòng đã bị xóa ngay lập tức trong vài mili-giây; reader tự lọc bỏ các bit đánh dấu khi đọc, và lệnhOPTIMIZEđịnh kỳ mới hợp nhất vật lý về sau.
- Mỗi phiên bản \(v\) là một tệp NDJSON bất biến tên cố định 20 chữ số (
-
Cây Siêu dữ liệu Ba Tầng &
Hidden Partitioning(Apache Iceberg):- Tầng 1 (
Catalog -> metadata.json): Catalog giữ con trỏ nguyên tử trỏ tới tệp JSON mô tả lược đồ (dùngField IDcố định thay vì tên cột, giúp đổi tên/sắp xếp lại cột an toàn 100%), lịch sửpartition-specs, và danh sách cácsnapshots. - Tầng 2 (
Manifest List, tệp Avro): Mỗi snapshot trỏ tới một tệpManifest Listduy nhất chứa danh sách cácManifest Filekèm biên độ phân vùnglower_bound/upper_bound. Trong Lab 07 (test_11), chỉ đọc1tệp Manifest List đã loại thẳng3/4Manifest (75.0%) mà không cần mở chúng ra. - Tầng 3 (
Manifest File -> Data Files): CácManifest Filecòn lại chứa thống kê cột chi tiết (lower_bounds,upper_bounds,null_value_counts) của từng tệp Parquet, giúp cắt tỉa237/240tệp dữ liệu (98.75%skip) trước khi mở bất kỳ Parquet Footer nào! - Partition Evolution Không Viết lại Lịch sử: Khác với Hive (đổi phân vùng từ
monthsangdayđòi hỏi tạo bảng mới và di trú toàn bộ petabyte dữ liệu), Iceberg gắnspec_idriêng cho từng tệp dữ liệu trong Manifest. Dữ liệu cũ giữspec_id = 0(months(ts)), dữ liệu mới ghi theospec_id = 1(days(ts)), và bộ lập kế hoạch truy vấn tự cắt tỉa chính xác trên cả haispec_idtrong cùng một câu SQL.
- Tầng 1 (
1.5 Giao dịch ACID, OCC, Time Travel & Bất đẳng thức An toàn VACUUM#
-
Optimistic Concurrency Control (
OCC): Thay vì khóa bi quan toàn bảng (làm nghẽn pipeline lớn), mỗi writer đọc phiên bản \(v_0\), ghi tệp Parquet mới song song lên Object Storage, rồi thực hiện commit nguyên tử vào \(v_0 + 1\). Nếu một giao dịch \(T_1\) đã chiếm \(v_0 + 1\), giao dịch \(T_2\) chạy phân giải xung đột:Append+Append: Hai luồng ghi tệp rời nhau không sửa tệp cũ \(\to\) tự động rebase lên \(v_0 + 2\) (retry = False).Delete+Overwritetrên cùng tệp (part-0042.parquet): Đụng độ xóa kép (ConcurrentDeleteDeleteException) hoặc đọc tệp vừa bị xóa (ConcurrentDeleteReadException) \(\to\) bắt buộc hủy commit, nạp lại snapshot mới và thử lại (retry = True).- Mức cô lập
WriteSerializablevs.Serializable:WriteSerializable(mặc định tối ưu thông lượng của Delta) cho phép một lệnhAPPENDchen vào phân vùng không ảnh hưởng tập tệp đã xóa củaUPDATE, trong khiSerializablechặn sạch mọiAPPENDrơi vào miền vị từ đọc (ConcurrentAppendException) để ngăn bóng ma (phantom reads).
-
Time Travel (Snapshot Isolation): Nhờ tính bất biến của Parquet và đánh dấu
removelogic trong_delta_log(chỉ xóa tệp khỏi trạng thái hiện tại chứ chưa xóa vật lý trên S3), câu lệnhDeltaTable(uri, version=0)hoặcTIMESTAMP AS OFtái tạo từng bit dữ liệu quá khứ — nền tảng cho tái lập tập huấn luyện ML, kiểm toán tài chính, vàRESTORE TABLE. - Bất đẳng thức An toàn
VACUUM: Để thu hồi chi phí lưu trữ từ các tệp đã bịremovesau compaction/update, kỹ sư chạyVACUUM. Nếu xóa tệp vật lý khi một truy vấn dài hạn (\(T_{\text{query\_max}}\)) vẫn đang đọc snapshot cũ, reader lập tức sập vớiFileNotFoundException. Ngưỡng giữ tệp tối thiểu bắt buộc tuân thủ:\[T_{\text{retention}} \ge \max\!\left(T_{\text{query\_max}},\; T_{\text{time\_travel\_SLA}}\right) + \delta_{\text{clock}}\]Mặc định công nghiệp là168giờ (7ngày). Với \(T_{\text{query\_max}} = 4\text{ h}\), \(T_{\text{time\_travel\_SLA}} = 168\text{ h}\) và biên lệch đồng hồ \(\delta_{\text{clock}} = 1\text{ h}\), ngưỡng an toàn tối thiểu là169.0giờ: mọi lệnhVACUUMở0hbị phân loạiCRITICAL_CONCURRENT_READER_FILE_NOT_FOUND, ở24hbị phân loạiVIOLATES_TIME_TRAVEL_SLA, và chỉ an toàn từ169.0h+(172h -> SAFE).
1.6 Tối ưu Bố cục Vật lý: OPTIMIZE, Đường cong Morton Z-Ordering vs. Liquid Clustering & Engine Truy vấn 2026#
-
Đường cong Morton (
Z-Ordering) cho Lọc Đa chiều: Sắp xếp từ điểnORDER BY (x, y)chỉ tối ưu hóa Zone Maps cho cột đầu tiên \(x\); khi người dùng lọc đơn lẻ theo cột thứ haiWHERE y BETWEEN 128 AND 159, mọi tệp đều trải rộng gần như toàn bộ miền \(y\) nên tỷ lệ bỏ qua sụp xuống0.0%(Lab 07). Z-Ordering biến đổi cặp tọa độ \(k\)-bit \((x, y)\) thành khóa 1D bằng phép đan xen bit (bit interleaving):\[Z(x, y) = \sum_{i=0}^{k-1} \left( x_i \cdot 2^{2i} + y_i \cdot 2^{2i+1} \right)\]Bảo toàn tính cục bộ không gian theo cả hai chiều, giúp Lab 07 đạt
93.75%bỏ qua tệp cho truy vấn hộp 2D và79.69%cho truy vấn riêng cột thứ hai \(y\)! -
Khuếch đại Ghi Compaction (\(\text{WA}_{\text{compact}}\)) & Bước nhảy
Liquid Clustering: Hệ số khuếch đại ghi sau \(R\) vòng nạp dữ liệu gia tăng được định nghĩa bởi:\[\text{WA}_{\text{compact}} = \frac{B_{\text{initial}} + B_{\text{rewritten}}}{B_{\text{initial}}} = 1 + \frac{B_{\text{rewritten}}}{B_{\text{initial}}}\]Z-Orderingcổ điển trên phân vùng Hive: Mỗi lần thêm15%dữ liệu mới vào phân vùng,OPTIMIZE ... ZORDER BYphải viết lại toàn bộ phân vùng đó để tái lập thứ tự toàn cục. Qua5vòng (1,750 MBtổng nạp trong Lab 07), tổng dung lượng viết lại phình lên7,250.0 MB(WA = 5.14x).Liquid Clustering(Delta 3.x+ / Iceberg Adaptive Clustering): Loại bỏ Hive Partitioning, chia không gian thành các khối Z-cube / Hilbert phân cấp. Khi thêm dữ liệu mới, chỉ các tệp mới chưa gom cụm và các khối biên bị tái tổ chức — tổng dung lượng viết lại trong Lab 07 chỉ còn937.5 MB(WA = 1.54x, thấp hơn3.34x), đồng thời giữ nguyên hiệu quả cắt tỉa93.75%(2D) /79.69%(col-2) và cho phép đổi khóaCLUSTER BYtrực tuyến không cần backfill.
-
Engine Truy vấn 2026:
TrinoMPP + Open Catalogs vs.DuckDB/Polars:TrinoMPP (Coordinator + Workers + Connector SPI): Khi nhận câu SQL, Coordinator phân tích cú pháp, lấy thống kê bảng từ Open Catalog / Delta log / Iceberg Manifests, chạy bộ tối ưu theo chi phí (Cost-Based Optimizer — CBO chọn thứ tựJOINvà Broadcast vs. Partitioned Hash Join), rồi chia nhỏ các tệp Parquet còn lại thành hàng nghìnSplitgiao cho đội ngũ Workers thực thi pipelined in-memory vectorized (không ghi dữ liệu trung gian xuống đĩa như MapReduce hay Spark shuffle mặc định). Qua Connector SPI, một truy vấn Trino duy nhất có thể nối trực tiếp bảng lịch sửdelta.silver.orders_cleantrên MinIO/S3 với bảng danh mục nóng trênPostgreSQLhoặc luồng thời gian thực từKafka.-
Tiến hóa Catalog (
Hive Metastore\(\to\) REST Open Catalogs):Hive Metastore (HMS)phụ thuộc giao thức Thrift cũ và DB quan hệ tập trung dễ nghẽn kết nối khi hàng trăm worker gọi đồng thời, thiếu phân quyền tinh mịn cấp cột/hàng (fine-grained RBAC) và thiếu cấp phát khóa tạm (credential vending). Chuẩn SOTA 2025–2026 hội tụ về giao thức REST Catalog mở:Apache Polaris(Incubating): Hiện thực tham chiếu chuẩn mở của Iceberg REST Catalog, cấp phát STS token tạm thời (vended credentials) để Worker truy cập trực tiếp S3 theo đúng quyền từng bảng.Unity Catalog OSS: Catalog mở đa định dạng hỗ trợ thống nhất bảngDelta,Iceberg(quaUniForm), tập tệp phi cấu trúc (Volumes) và tài sản AI/ML (mô hình, hàm UDF) kèm phả hệ cột (column-level lineage).Project Nessie: Mang mô hình phân nhánh Git (CREATE BRANCH exp,MERGE,TAG) vào dữ liệu Lakehouse — cho phép kỹ sư kiểm thử pipeline ETL trên nhánh cô lập không ảnh hưởng dữ liệumainrồi hợp nhất nguyên tử đa bảng (multi-table atomic commit).
-
DuckDB 2.x&Polars 2.x(Single-Node Vectorized Powerhouse): Tận dụng CPU SIMD hiện đại, bộ nhớ RAM lớn (64–512 GB) và trao đổi Apache Arrow Zero-Copy, thực thi truy vấn phân tích trên dữ liệu< 500 GBtrong vài mili-giây (0độ trễ khởi động cụm JVM,0chi phí mạng shuffle). Trong Lab 07, trên cùng tập Silver38,469dòng,DuckDB 2.0.1vàPolars 2.1.0Lazy đạt độ trễ trung vị12.22 ms/4.27 msvới sai lệch doanh thu0.0 USD(100%parity).
| So sánh Open Catalog 2026 | Giao thức & Triển khai | Hỗ trợ Định dạng | Phân quyền & Cấp Token | Tính năng Nổi bật |
|---|---|---|---|---|
Hive Metastore (HMS 4.0) |
Apache Thrift + PostgreSQL backend | Hive, Delta, Iceberg | Hạn chế (cần Ranger/Sentry ngoài) | Tương thích rộng hệ sinh thái di sản (dùng trong docker-compose.yml Lab 07) |
Apache Polaris |
Iceberg REST Catalog API | Iceberg gốc (đa engine) | RBAC chuẩn + Credential Vending | Chuẩn mở nhẹ, tách rời hoàn toàn compute với quyền IAM bucket S3 |
Unity Catalog OSS |
REST API thống nhất | Delta + Iceberg (UniForm) + Volumes + ML |
RBAC/ABAC cấp bảng, cột, hàng | Quản trị toàn diện cả dữ liệu có cấu trúc lẫn tệp/mô hình AI |
Project Nessie |
REST API + Git-like commit graph | Iceberg / Delta | RBAC theo nhánh (branch) | Kiểm thử Write–Audit–Publish (WAP) & giao dịch nguyên tử đa bảng |
Principal Industrial Tip #9 — Bảo trì Lakehouse & Chuẩn Định dạng 2025–2026 (Puffin, Variant, _row_id, DuckLake 1.1, Vortex, Compaction, Deletion Vectors & Orphan File GC):
- Đánh đổi Compaction (
rewrite_data_files/OPTIMIZE) & Thống kêPuffin: Luôn tách tác vụ nén tệp (128–512 MB/file) thành job bảo trì bất đồng bộ theo lịch (hourly/daily) kèm giới hạnmax-concurrent-file-group-rewritesthay vì chạy sau mỗi micro-batch để tránh xung đột OCCConcurrentDeleteReadExceptionvới các job streamingMERGE INTOđang ghi. Với bảng lớn nạp gia tăng đa chiều, ưu tiênLiquid Clustering(WA = 1.54x) thay choZ-Orderingtoàn phân vùng (WA = 5.14x). Song song, kích hoạt tệp sidecarPuffincủa Iceberg lưu Apache DataSketches (Theta/NDV) cho từng cột giúp CBO củaTrino/Sparkước lượng chính xác lực lượng tập hợp không cần quét Parquet — lưu ý failure mode: chạy streaming append dài ngày mà quên làm mớiPuffinkhiến CBO dùng thống kê cũ, chọn nhầmBroadcastHashJoinlên bảng thực tế đã phình to và làm sậpExecutor OOM! VariantShredding &_row_id(Iceberg v3 / Parquet Semi-Structured & Row-Level Lineage): KiểuVariantcho phép lưu payload JSON/webhook bán cấu trúc trong Parquet/Iceberg v3 và tự động băm nhỏ cột con (shredding) các trường phổ biến để đạt tốc độ quét cột và cắt tỉa Min/Max gần bằng cột phẳng; tuy nhiên nếu khóa JSON có cardinality hỗn loạn (dynamic unbounded keys), cơ chế shredding làm phình lớn Parquet Footer và kéo tụt tốc độ lập kế hoạch. Ở tầng CDC/cập nhật, Deletion Vectors (MoR) biến thao tác viết lại256 MBthành bitmap vài trăm byte kết hợp siêu dữ liệu_row_id(Iceberg v3 row-level lineage) cấp định danh ổn định cho từng dòng xuyên qua compaction để pipeline hạ lưu tiêu thụ gia tăng không cần tự join khóa rộng; vẫn phải đặt ngưỡngrewrite_data_files(min-deletes-per-file) khi tỷ lệ xóa vượt10%–15%để tránh thuế hợp nhất lúc đọc (read-side merge penalty).- Đánh đổi Catalog
DuckLake 1.1& Định dạng CộtVortex:DuckLake 1.1đưa toàn bộ cây siêu dữ liệu ACID (snapshots, lược đồ, thống kê Min/Max, inlined small inserts) vào một CSDL SQL chuẩn (PostgreSQL/DuckDB) trỏ tới tệp Parquet trên S3, xóa bỏ hàng chục vòng gọi tệp JSON/Avro nhỏ — đổi lại yêu cầu một điểm điều phối SQL catalog thay vì hệ sinh thái đa engine mở nhưApache Polaris/Iceberg REST. Ở tầng lưu trữ vật lý,Vortex(định dạng cột mở rộng tương thích Apache Arrow zero-copy) cho phép chạy bộ lọc trực tiếp trên mảng nén (compressed execution) và truyền zero-copy thẳng sang CPU SIMD lẫn GPU VRAM nhanh vượt trội Parquet truyền thống, nhưng hệ sinh thái đọc bên ngoài vẫn đang thu hẹp khoảng cách độ phủ so với Parquet. - Vòng đời
expire_snapshots&remove_orphan_files(Failure Modes): Không bao giờ đặtretain_last=1hay xóa snapshot/VACUUM dưới trần \(\max(T_{\text{query\_max}}, T_{\text{SLA}}) + \delta_{\text{clock}}\) (169h), nếu không truy vấn BI đang mở sẽ sập ngay bằngFileNotFoundException. Đặc biệt, khi chạyOrphan File GC(remove_orphan_files), bắt buộc khóaolder_than >= 72h(lớn hơn thời gian tối đa của mọi giao dịch ghi đang chạy dở) để tuyệt đối không xóa nhầm các tệp Parquet vừa được writer đẩy lên S3 trước khi ghi nhận vàometadata.json/_delta_log!
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất (Production Systems Architecture)#
2.1 Kiến trúc Open Lakehouse Đa chặng Medallion Trên Object Storage & Đa Engine Truy vấn#
- Ngân sách Hiệu năng & SLA Tầng Lưu trữ:
- Kích thước tệp Parquet mục tiêu:
128 MB–512 MB(giữ băng thông hiệu dụng \(B_{\text{eff}} > 97\%\) trên S3/MinIO); cảnh báo ngay khi kích thước trung bình tệp rơi xuống< 32 MB. - Độ trễ lập kế hoạch truy vấn (Query Planning):
< 500 msnhờ đọc Parquet Checkpoint (Delta) hoặc Avro Manifest List (Iceberg) thay vìS3 LISTtoàn bucket. - Chính sách giữ lịch sử (
Retention SLA):delta.logRetentionDuration = 30 days,delta.deletedFileRetentionDuration = 7 days (168h)làm rào chắn tối thiểu chốngFileNotFoundException.
- Kích thước tệp Parquet mục tiêu:
2.2 Đối chiếu Siêu dữ liệu Nội tại Delta Lake vs. Apache Iceberg & Cầu nối UniForm / XTable#
2.3 Giao thức Xung đột OCC & Cửa sổ An toàn VACUUM Bảo vệ Concurrent Reader#
Trụ cột 3 — Công nghệ 2026, Ca Sản xuất Thực tế, Bảng Quyết định & Mã Nguồn Thực thi#
3.1 Bốn Ca Kiến trúc & Sự cố Quy mô Lớn Trong Sản xuất#
Netflix&Apple— Kiến tạoApache IcebergKhắc phục Nút thắtS3 LIST& Bẫy Phân vùng Hive: Ở quy mô hàng trăm PB trên S3, bảng Hive truyền thống buộc gọi hàng chục nghìn lệnhS3 LISTlúc lập kế hoạch truy vấn và dính bẫy full-table scan mỗi khi người phân tích lọc trực tiếp trênevent_timestampmà quên cột phân vùngdateint. Iceberg thay toàn bộS3 LISTbằng cây Avro Manifest List/File (rút thời gian planning xuống< 1 s) và dùng Hidden Partitioning (days(event_ts)) tự động cắt tỉa — tương tự kết quả98.75%skip (80.0x) trong Lab 07.Walmart&Databricks—Delta Liquid ClusteringCắt Giảm Chi phí Bảo trì Compaction: Bảng bán lẻ đa chiều lọc theo(store_id, order_date, category)bị phân mảnh tệp nhỏ khi phân vùng Hive và gánh khuếch đại ghi rất lớn khi chạy lạiZ-Ordertoàn phân vùng. Chuyển sangLiquid Clusteringgom cụm gia tăng cắt mạnh Write Amplification (5.14x -> 1.54x, giảm3.34xtrong Lab 07) và cho phép đổi khóa phân cụm khi nhu cầu kinh doanh thay đổi mà không phải viết lại dữ liệu lịch sử.Cloudflare&Shopify— Kiến trúc LaiTrinoMPP +DuckDB/Polars: Kết hợpTrinocho truy vấn liên kết đa bảng quy mô hàng chục TB vàDuckDB/Polarscho phân tích cục bộ/theo tenant dưới500 GBgiúp loại bỏ chi phí shuffle mạng, hạ độ trễp95từ nhiều giây xuống hàng chục mili-giây và giảm60%–80%hóa đơn cụm compute.- Post-Mortem Kinh điển —
FileNotFoundExceptionTừVACUUM RETAIN 0& Lệch Lược đồ Data Swamp: ChạyVACUUMvớiretention = 0trong giờ cao điểm làm gãy toàn bộ dashboard BI và xóa sổ khả năngRESTORE TABLE; còn tắt Schema Enforcement làm lỗi kiểu dữ liệu từ upstream đổ vỡ dây chuyền ở tầng Gold. Quy chuẩn bắt buộc: giữretention >= 168h, chạydry_run=Truetrước khi dọn tệp, và khóa chặt Schema Enforcement tại tầng Bronze/Silver.
3.2 Hai Bảng Quyết định Kỹ thuật (Production Decision Playbooks)#
Playbook A — Lựa chọn Open Table Format & Chiến lược Bố cục Vật lý#
| Nhu cầu Hệ thống | Lựa chọn Khuyến nghị 2026 | Lý do Kiến trúc & Ràng buộc |
|---|---|---|
Hệ sinh thái Spark/Databricks + Python delta-rs gọn nhẹ |
Delta Lake (+ bật UniForm) |
Giao dịch _delta_log tối giản, Liquid Clustering mạnh, UniForm mở khóa đọc gốc bằng Iceberg cho Trino/Snowflake |
Đa Engine Mở (Trino, Flink, Snowflake, BigQuery) + Hidden Partitioning |
Apache Iceberg + Apache Polaris REST Catalog |
Cây 3 tầng cắt tỉa Manifest cực nhanh, hỗ trợ Partition Evolution không viết lại dữ liệu cũ, quản trị chuẩn REST |
Bảng < 1 TB, lọc 1 chiều thời gian rõ ràng |
Parquet/Delta sắp xếp theo order_date + OPTIMIZE |
Đơn giản, đạt > 85% Zone-Map Row-Group skipping với chi phí vận hành gần như bằng 0 |
Bảng lớn > 1 TB, lọc đa chiều & nạp gia tăng liên tục |
Liquid Clustering (CLUSTER BY (c1, c2, c3)) |
Giữ > 90% data skipping đa chiều, cắt 3x–10x Write Amplification so với Z-Order toàn phân vùng |
Playbook B — Lựa chọn Engine Truy vấn (DuckDB/Polars vs. Trino vs. Spark)#
| Quy mô & Hình thái Tải | Engine Tối ưu | Điểm Gãy Cần Tránh |
|---|---|---|
Dữ liệu < 500 GB, CI/CD, ETL đơn nút, phân tích tương tác nhanh |
DuckDB 2.x (SQL) hoặc Polars 2.x (Lazy DataFrame) |
Tránh tràn RAM nếu join nhiều bảng trăm GB không bật spill-to-disk |
BI đồng thời hàng trăm user, truy vấn liên kết (Delta + Postgres + Kafka), 1–100 TB |
Trino MPP (Pipelined In-Memory) |
Không phù hợp cho các job ETL chạy hàng giờ cần fault-tolerance mức stage (như Spark) |
Biến đổi batch khổng lồ > 50 TB, ML feature engineering nặng, chịu lỗi stage |
Apache Spark (AQE — Chương 09) |
Độ trễ khởi động cao (vài giây), lãng phí tài nguyên cho truy vấn BI nhỏ dưới 1 s |
3.3 Mã Nguồn Thực thi Chuẩn (PyArrow Zone Maps + Delta Lake ACID & DuckDB/Polars)#
Đoạn mã sau trích trực tiếp mẫu thiết kế cốt lõi từ lakehouse_storage_lab (chạy hoàn chỉnh 100% trên .venv Python 3.12):
from pathlib import Path
import duckdb
import polars as pl
import pyarrow.parquet as pq
from deltalake import DeltaTable, write_deltalake
def verify_lakehouse_core(table_dir: Path, batch_v0, batch_v1_evolved) -> dict[str, object]:
# 1. Ghi Bronze v0 -> Evolution v1 bằng schema_mode="merge"
write_deltalake(str(table_dir), batch_v0, mode="overwrite")
write_deltalake(str(table_dir), batch_v1_evolved, mode="append", schema_mode="merge")
# 2. Time Travel đọc chính xác v0 vs v1 & nén tệp nhỏ
v0_rows = DeltaTable(str(table_dir), version=0).to_pyarrow_table().num_rows
dt_latest = DeltaTable(str(table_dir))
compact_stats = dt_latest.optimize.compact()
arrow_tbl = DeltaTable(str(table_dir)).to_pyarrow_table()
# 3. Đối chiếu Zero-Copy Arrow trên DuckDB 2.x và Polars 2.x Lazy
con = duckdb.connect(":memory:")
duck_rev = con.execute("SELECT ROUND(SUM(amount_usd), 2) FROM arrow_tbl").fetchone()[0]
polars_rev = (
pl.from_arrow(arrow_tbl).lazy()
.select(pl.col("amount_usd").sum().round(2))
.collect().item()
)
return {
"v0_rows": v0_rows,
"latest_rows": arrow_tbl.num_rows,
"compacted_removed_files": compact_stats["numFilesRemoved"],
"revenue_parity_ok": abs(float(duck_rev) - float(polars_rev)) <= 0.01,
}
Trụ cột 4 — Thực hành Công nghiệp (Lab 07: lakehouse_storage_lab) & Bảng Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Của Lab 07 (labs/lab-07-open-lakehouse-delta-iceberg-trino/)#
-
Tầng Hạ tầng Triển khai Thật (Kiểm toán tĩnh trong
infra_audit.py):docker-compose.yml: Cụm 5 dịch vụ gắn tag cố định (minio,minio-init,postgres-metastore,hive-metastore,trino), đủhealthcheck,depends_on: condition: service_healthy, mạng cô lậplakehouse_net, không hardcode bí mật production (${MINIO_ROOT_USER:-...},${METASTORE_PASSWORD:-...}).configs/trino_delta_catalog.properties: Kết nốiconnector.name=delta_laketớiminio:9000(s3.path-style-access=true),hive-metastore:9083, nénZSTD, và chốt cứng rào an toàndelta.vacuum.min-retention=168h.sql/01_medallion_trino.sql: Định nghĩa schemadelta.bronze,delta.silver,delta.gold, cửa sổ khử trùng lặpROW_NUMBER() OVER (PARTITION BY order_id ORDER BY event_ts DESC), bảngdaily_revenue_mart, và lệnh bảo trìALTER TABLE ... EXECUTE optimize(file_size_threshold => '128MB').
-
Tầng Thực thi Dữ liệu Thật Cục bộ (100% Offline,
0Tệp.parquetRác Để lại Repo): Chạy thậtpyarrow==26.0.1,deltalake==1.6.6,duckdb==2.0.1, vàpolars==2.1.0trongtempfile.TemporaryDirectory(), xuất duy nhất báo cáo kiểm chứng tạiartifacts/t2_ch08_lab07_results.jsonvớiworkbench_panelschuẩn hóa (6KPIs,4biểu đồ thanh,4bảng kiểm định).
Danh sách 16 Kiểm thử Nghiệm thu (tests/test_lakehouse_storage_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 & Dữ liệu | test_01, test_02 |
Quét AST cấm pickle/joblib/cloudpickle/dill/shelve/marshal; xác minh bộ sinh đơn hàng tái lập xác định |
| Parquet & Zone Maps | test_03, test_04 |
So sánh nén CSV vs. Snappy/Zstd, Column Pruning > 60% I/O, và Zone-Map Row-Group Skipping (0.0% -> 85.0%) |
| Delta Medallion & Log | test_05, test_06, test_07 |
Chặn cột sai (SchemaMismatchError), schema_mode="merge", Time Travel v0 vs v1, audit _delta_log/*.json, khớp doanh thu Silver–Gold |
| Compaction & VACUUM | test_08, test_09 |
dt.optimize.compact() gom 12 -> 1 tệp (12.0x), vacuum(dry_run=True) phát hiện 12 tệp cũ, chặn 0h/24h vs duyệt 172h |
| Query Engines & Iceberg | test_10, test_11, test_12 |
Khớp 100% KPI DuckDB 2.x vs Polars 2.x; Iceberg 3-tier pruning (98.75%); ma trận xung đột OCC 4 kịch bản |
| Bố cục 2D & Hạ tầng | test_13–test_16 |
Đan xen bit Morton Z(x,y); Z-Order vs Liquid Clustering (WA giảm 3.34x); kiểm toán Compose/Trino/SQL; CLI artifact schema |
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch08_lab07_results.json)#
Thực nghiệm (lakehouse_storage_lab) |
Thông số Đo được (Xác định, seed=42) |
Bất biến Được Chứng minh |
|---|---|---|
CSV vs. Parquet (50,000 dòng) |
CSV 3,381,970 B \(\to\) Snappy 1,347,579 B (2.51x) \(\to\) Zstd 974,275 B (3.47x); Column Pruning 2/10 cột tiết kiệm 75.28% I/O |
Nén cột + cắt tỉa cột giảm mạnh đồng thời lưu trữ và I/O đọc |
| Zone-Map Row-Group Skipping | day_offset BETWEEN 52 AND 56 (20 RGs): Unsorted 0.0% (20/20 RG đọc) vs. Sorted 85.0% (3/20 RG đọc, giảm 6.67x) |
Sắp xếp theo khóa lọc mở khóa Zone Maps Min/Max thật trong Parquet Footer |
| Delta Lake ACID & Time Travel | Chặn lô sai (SchemaMismatchError); merge thêm loyalty_tier; v0=50,000 vs v1=50,003; Silver 38,469 dòng (lọc 11,534), Gold khớp 3,395,566.59 USD |
Kiểm chứng _delta_log/*.json thật (protocol, metaData, add, remove) |
| Compaction & VACUUM Safety | optimize.compact() gom 12 tệp \(\to\) 1 tệp (12.0x), vacuum(dry_run=True) phát hiện 12 tệp cũ; chặn 0h (CRITICAL) vs duyệt 172h (SAFE, ngưỡng 169.0h) |
Triệt tiêu Small-File Problem mà không phá hỏng Concurrent Reader |
| DuckDB 2.x vs. Polars 2.x | 12 nhóm (12,443 đơn lọc, 1,477,312.45 USD), sai lệch 0.0 USD (100% parity), độ trễ vài mili-giây |
Khớp kết quả tuyệt đối giữa SQL vectorized và Rust Lazy DataFrame |
| Iceberg Pruning, OCC & Liquid | Iceberg cắt tỉa 98.75% tệp (80.0x so với bẫy Hive); OCC phân tách Append+Append vs Delete+Overwrite; Liquid Clustering 93.75% skip 2D & WA = 1.54x vs Z-Order 5.14x (3.34x thấp hơn) |
Chứng minh ưu thế Hidden Partitioning và gom cụm gia tăng SOTA 2026 |
4.3 Quy trình Kiểm định Tự động (16/16 pytest)#
cd 03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-07-open-lakehouse-delta-iceberg-trino
python scripts/run_lab_demo.py --rows 50000 --output artifacts/t2_ch08_lab07_results.json
ruff check src tests scripts
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#
- Armbrust, M. et al. (2020). "Delta Lake: High-Performance ACID Table Storage over Cloud Object Stores." Proceedings of the VLDB Endowment (PVLDB), 13(12), 3411–3424. — Bài báo gốc về
_delta_log, OCC, checkpoint và data skipping trên S3. - Armbrust, M., Ghodsi, A., Xin, R., & Zaharia, M. (2021). "Lakehouse: A New Generation of Open Platforms that Unify Data Warehousing and Advanced Analytics." CIDR 2021. — Khai sinh khái niệm Lakehouse hợp nhất BI và ML trên một nguồn chân lý mở.
- Apache Iceberg Specification (v2 & v3, 2024–2026). "Table Spec: Hidden Partitioning, Snapshots, Manifest Lists, Deletion Vectors & REST Catalog." — Chuẩn kỹ thuật mở cho cây siêu dữ liệu 3 tầng và
Apache Polaris. - Raasveldt, M., & Mühleisen, H. (2019–2025). "DuckDB: an Embeddable Analytical Database." SIGMOD & DuckDB 1.x–2.x Architecture Notes. — Nguyên lý thực thi vectorized in-process và giao tiếp Apache Arrow zero-copy.
- Sethi, R. et al. (2019–2025). "Presto / Trino: SQL on Everything." ICDE & Trino Modern Architecture. — Kiến trúc MPP pipelined in-memory và Connector SPI cho truy vấn liên kết trên Open Lakehouse.
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%) — Toán học Object Storage, Small-File Roofline & NénParquet(Zstd+ Column Pruning): Dẫn xuất phương trình băng thông hiệu dụng \(B_{\text{eff}}(S) = \frac{S}{t_{\text{req}} + S / B}\), tính tỷ lệ suy hao khi tệp nhỏ \(0.5\text{ MB}\) so với \(256\text{ MB}\) (\(B = 125\text{ MB/s}, t_{\text{req}} = 25\text{ ms}\)), và thực thibenchmark_csv_vs_parquet(test_03) giải thích lý doZstd+ Dictionary/RLE cắt3.47xdung lượng và đọc2/10cột tiết kiệm75.28%I/O. Thang điểm: Đúng công thức & định lượng Roofline (5%), giải thích mã hóa Dictionary/RLE/Delta (5%), chạy passtest_03(5%). -
Bài tập 2 (
ex2, 15%) — Kiểm chứng ParquetZone MapsMin/Max Row-Group Skipping: Viết điều kiện bỏ qua Row Group \(\max_g < a \lor \min_g > b\), giải thích vì sao tệp Parquet chưa sắp xếp rơi về0.0%bỏ qua, chạybenchmark_parquet_zone_map_pruning(test_04) và phân tích lý do cần thêm Split-Block Bloom Filter cho cột độ phân giải cao nhưorder_id. Thang điểm: Chứng minh điều kiện bỏ qua & công thức \(\rho_{\text{io}}\) (5%), phân tích Unsorted vs Sorted (0.0% -> 85.0%,6.67x) (5%), giải thích vai trò Bloom Filter & passtest_04(5%). -
Bài tập 3 (
ex3, 20%) — PipelineDelta LakeMedallion (Bronze -> Silver -> Gold), Schema Evolution &Time Travel: Chạyrun_delta_medallion_pipeline(Tests 05, 06, 07), kiểm toán các tệp JSON thật trong_delta_log/, giải thích cơ chế Schema Enforcement chặn cột lỗi (SchemaMismatchError),schema_mode="merge"thêmloyalty_tier, và chứng minh bất biến tổng doanh thu giữaSilver(38,469dòng) vớiGold(3,395,566.59 USD). Thang điểm: Phân tích cấu trúc_delta_log/*.json(7%), chứng minh Time Travelv0vsv1(7%), passTests 05–07(6%). -
Bài tập 4 (
ex4, 15%) —OPTIMIZECompaction, Bất đẳng thức An toànVACUUM& Xung độtOCC: ChạyTests 08, 09, 12, phân tích kết quảdt.optimize.compact()(12 -> 1tệp) vàvacuum(dry_run=True)(12tệp cũ), chứng minh bất đẳng thức \(T_{\text{retention}} \ge \max(T_{\text{query\_max}}, T_{\text{time\_travel\_SLA}}) + \delta_{\text{clock}}\), và giải thích ma trận xung độtOCC(Append+AppendvsDelete+OverwritevsSerializable). Thang điểm: Giải thíchremovetombstone &VACUUM(5%), phân tích 4 caOCC(5%), passTests 08, 09, 12(5%). -
Bài tập 5 (
ex5, 15%) —Apache IcebergHidden Partitioning, Đường cong MortonZ-Ordervs.Liquid Clustering: Chứng minh công thức đan xen bit \(Z(x, y)\) (kiểm chứngmorton_zorder_2d(0b101, 0b011) == 0b011011), giải thích vì sao Lexicographical Sort sụp xuống0.0%khi lọc riêng cột 2 trong khi Z-Order/Liquid đạt79.69%, và dẫn xuất mức giảm khuếch đại ghi \(\text{WA}\) (5.14x -> 1.54x,3.34x) của Liquid Clustering cùng mức cắt tỉa98.75%của Iceberg Hidden Partitioning (Tests 11, 13, 14). Thang điểm: Đúng toán học Morton & \(\text{WA}\) (5%), giải thích Hidden Partitioning vs Hive (5%), passTests 11, 13, 14(5%). -
Bài tập 6 (
ex6, 20%) — Đối chiếuDuckDB 2.xvs.Polars 2.x, Kiểm toán Hạ tầngMinIO/HMS/Trino& Cổng16/16 pytest: Thực thibenchmark_duckdb_vs_polars(test_10) kiểm chứng khớp0.0 USDsai lệch trên12,443đơn lọc (1,477,312.45 USD), kiểm toándocker-compose.yml,trino_delta_catalog.properties,01_medallion_trino.sql(test_15), và hoàn thành sạchruff,mypy,run_lab_demo.py,16/16 pytest(test_01,test_16). Thang điểm: Đối chiếu DuckDB/Polars & Arrow zero-copy (7%), kiểm toán Compose/Trino/SQL (7%), đạt xanh16/16 pytest+ruff/mypy0lỗi (6%).
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— Object Storage & Small-File Roofline): Vì sao lưu100,000tệp0.5 MBtrên Object Storage S3/MinIO làm suy sụp hiệu năng truy vấn dù tổng dung lượng chỉ50 GB? - (
q2— Parquet Column Pruning & Zone-Map Skipping): Tronglakehouse_storage_lab, vì sao truy vấnday_offset BETWEEN 52 AND 56trên tệp Parquet chưa sắp xếp bỏ qua0.0%Row Group còn tệp đã sắp xếp bỏ qua85.0%(6.67x)? - (
q3— Data Swamp vs. Medallion & Schema Enforcement): TầngBronze -> Silver -> Goldcùng cơ chế Schema Enforcement trên Delta Lake giải quyết những lỗi sản xuất nào trong Lab 07? - (
q4— Delta_delta_logvs. Apache Iceberg 3-Tier Metadata & Hidden Partitioning): Điểm khác biệt cốt lõi giữa_delta_logcủa Delta Lake và cây siêu dữ liệu 3 tầng kèm Hidden Partitioning của Apache Iceberg là gì? - (
q5— Optimistic Concurrency ControlOCC): Trong ma trậnOCC, cặp giao dịch đồng thời nào tự động rebase thành công và cặp nào bắt buộc hủy commit để retry? - (
q6—OPTIMIZECompaction & Bất đẳng thức An toànVACUUM): Điều gì xảy ra nếu chạyVACUUM RETAIN 0 HOURSkhi có truy vấn kéo dài4giờ đang chạy và SLA Time Travel là168giờ? - (
q7— Lexicographical Sort vs.Z-Orderingvs.Liquid Clustering): Vì sao Liquid Clustering vượt trội hơn cả Lexicographical Sort lẫn Z-Ordering cổ điển trên bảng lớn nạp dữ liệu gia tăng? - (
q8—TrinoMPP, Open Catalogs &DuckDB/Polars): Khi nào nên chọnDuckDB/Polarsso vớiTrinoMPP, và vì sao các doanh nghiệp 2026 chuyển từHive MetastoresangApache Polaris/Unity Catalog?
50,000 Order Events On-Disk Size (KB): CSV vs Parquet Snappy vs Zstd
Parquet Row-Group Zone-Map Skipping (%): Unsorted vs Sorted by Filter Key
Delta Lake Compaction: Active Parquet Files Before vs After optimize.compact()
5-Round Incremental Write Amplification (WA): Liquid Clustering vs Z-Order
Real Delta Lake Multi-Hop Medallion Execution (Bronze -> Silver -> Gold)
| layer | rows | active_files | key_invariant | status |
|---|---|---|---|---|
| Bronze v0 (Raw Append) | 50000 | 1 | Schema Enforcement rejected (SchemaMismatchError) | PASS |
| Bronze v1 (Schema Merge) | 50003 | 2 | Added loyalty_tier; Time Travel v0 preserved without loyalty_tier | PASS |
| Silver (Deduplicated Clean) | 38469 | 1 | Filtered 11534 dup/bad rows | PASS |
| Gold (Revenue Mart) | 24 | 1 | Revenue 3,395,566.59 USD matches Silver | PASS |
Optimistic Concurrency Control (OCC) Matrix & VACUUM Retention Guard
| scenario | mechanism | outcome | retry_or_risk |
|---|---|---|---|
| Append + Append | WriteSerializable OCC | AUTO_REBASED_COMMIT | retry=False |
| Delete + Overwrite (Same File) | WriteSerializable OCC | CONFLICT_RETRY_REQUIRED | retry=True |
| Append + Update (Scanned Range) | Serializable OCC | CONFLICT_RETRY_REQUIRED | retry=True |
| VACUUM 0h vs 172h (SLA 168h) | Retention Inequality Guard | 0h=False | 172h=True | CRITICAL_CONCURRENT_READER_FILE_NOT_FOUND |
Physical Data Layout: 2D Box Skipping, Col-2 Skipping & Write Amplification
| layout_strategy | box_2d_skip_pct | col2_only_skip_pct | wa_5_rounds |
|---|---|---|---|
| Unsorted Raw Files | 0.0% | 0.0% | 1.0x (no optimize) |
| Lexicographical Sort (x, y) | 85.94% | 0.0% | 5.14x (full rewrite) |
| Z-Ordering (Morton Curve) | 93.75% | 79.69% | 5.14x (full rewrite) |
| Liquid Clustering (Incremental) | 93.75% | 79.69% | 1.54x (3.34x lower WA) |
Deployable Lakehouse Infrastructure Audit (MinIO, Hive Metastore, Trino, SQL)
| artifact | verified_components | security_and_sla | audit_status |
|---|---|---|---|
| docker-compose.yml | hive-metastore, minio, minio-init, postgres-metastore, trino | pinned=True, healthy=True | PASS |
| configs/trino_delta_catalog.properties | connector=delta_lake, s3=http://minio:9000 | vacuum_min=168h, env_secrets=True | PASS |
| sql/01_medallion_trino.sql | bronze/silver/gold schemas + ROW_NUMBER dedup + daily_revenue_mart | optimize_proc=True | PASS |
03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-07-open-lakehouse-delta-iceberg-trino
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "lakehouse-storage-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 07: Open Lakehouse Storage (PyArrow Parquet Zone Maps, Delta Lake ACID Medallion & Time Travel, Apache Iceberg OCC & Liquid Clustering, DuckDB/Polars & Trino/MinIO Infra)"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"duckdb>=2.0.0",
"pyarrow>=20.0.0",
"deltalake>=1.6.0",
"polars>=2.0.0",
"pydantic>=2.0.0",
"pyyaml>=6.0.0",
"numpy>=2.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.8",
"mypy>=1.10",
]
[project.scripts]
fsds-lakehouse-lab = "lakehouse_storage_lab.delta_medallion: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", "deltalake", "deltalake.*", "pyarrow", "pyarrow.*", "duckdb", "polars"]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
services:
minio:
image: minio/minio:RELEASE.2025-02-28T09-55-16Z
container_name: fsds-lab07-minio
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-lakehouse_admin}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-local_minio_dev_pass}
ports:
- "127.0.0.1:9000:9000"
- "127.0.0.1:9001:9001"
volumes:
- miniodata:/data
networks:
- lakehouse_net
healthcheck:
test: ["CMD-SHELL", "mc ready local || curl -sf http://localhost:9000/minio/health/live || exit 1"]
interval: 10s
timeout: 5s
retries: 10
start_period: 10s
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
minio-init:
image: minio/mc:RELEASE.2025-02-21T16-00-46Z
container_name: fsds-lab07-minio-init
depends_on:
minio:
condition: service_healthy
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-lakehouse_admin}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-local_minio_dev_pass}
entrypoint: >
/bin/sh -c "
mc alias set local http://minio:9000 $${MINIO_ROOT_USER} $${MINIO_ROOT_PASSWORD} &&
mc mb --ignore-existing local/lakehouse &&
mc mb --ignore-existing local/lakehouse-bronze &&
mc mb --ignore-existing local/lakehouse-silver &&
mc mb --ignore-existing local/lakehouse-gold
"
networks:
- lakehouse_net
security_opt:
- no-new-privileges:true
postgres-metastore:
image: postgres:16.8-alpine
container_name: fsds-lab07-postgres-metastore
environment:
POSTGRES_DB: ${METASTORE_DB:-metastore_db}
POSTGRES_USER: ${METASTORE_USER:-hive_metastore}
POSTGRES_PASSWORD: ${METASTORE_PASSWORD:-local_hms_dev_pass}
volumes:
- pgmetastore:/var/lib/postgresql/data
networks:
- lakehouse_net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${METASTORE_USER:-hive_metastore} -d ${METASTORE_DB:-metastore_db}"]
interval: 5s
timeout: 5s
retries: 10
start_period: 10s
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.75"
memory: 512M
hive-metastore:
image: apache/hive:4.0.1
container_name: fsds-lab07-hive-metastore
depends_on:
postgres-metastore:
condition: service_healthy
minio:
condition: service_healthy
environment:
SERVICE_NAME: metastore
DB_DRIVER: postgres
SERVICE_OPTS: >
-Djavax.jdo.option.ConnectionDriverName=org.postgresql.Driver
-Djavax.jdo.option.ConnectionURL=jdbc:postgresql://postgres-metastore:5432/${METASTORE_DB:-metastore_db}
-Djavax.jdo.option.ConnectionUserName=${METASTORE_USER:-hive_metastore}
-Djavax.jdo.option.ConnectionPassword=${METASTORE_PASSWORD:-local_hms_dev_pass}
ports:
- "127.0.0.1:9083:9083"
networks:
- lakehouse_net
healthcheck:
test: ["CMD-SHELL", "bash -c 'echo > /dev/tcp/localhost/9083' || exit 1"]
interval: 10s
timeout: 5s
retries: 12
start_period: 25s
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "1.0"
memory: 1024M
trino:
image: trinodb/trino:471
container_name: fsds-lab07-trino
depends_on:
hive-metastore:
condition: service_healthy
minio:
condition: service_healthy
ports:
- "127.0.0.1:8080:8080"
volumes:
- ./configs/trino_delta_catalog.properties:/etc/trino/catalog/delta.properties:ro
- ./sql/01_medallion_trino.sql:/opt/trino/sql/01_medallion_trino.sql:ro
networks:
- lakehouse_net
healthcheck:
test: ["CMD-SHELL", "curl -sf http://localhost:8080/v1/info | grep -q '\"starting\":false' || exit 1"]
interval: 10s
timeout: 5s
retries: 12
start_period: 25s
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "2.0"
memory: 2048M
networks:
lakehouse_net:
driver: bridge
volumes:
miniodata:
pgmetastore:
connector.name=delta_lake
hive.metastore.uri=thrift://hive-metastore:9083
fs.native-s3.enabled=true
s3.endpoint=http://minio:9000
s3.region=us-east-1
s3.path-style-access=true
s3.aws-access-key=${ENV:MINIO_ROOT_USER}
s3.aws-secret-key=${ENV:MINIO_ROOT_PASSWORD}
delta.enable-non-concurrent-writes=true
delta.register-table-procedure.enabled=true
delta.vacuum.min-retention=168h
delta.compression-codec=ZSTD
-- FSDS-SOTA-2026 Track 2 Lab 07: Multi-Hop Medallion Lakehouse DDL & Maintenance on Trino + Delta Lake
-- Execution target: Trino 471 with catalog `delta` backed by MinIO S3 & Hive Metastore
CREATE SCHEMA IF NOT EXISTS delta.bronze
WITH (location = 's3://lakehouse/bronze/');
CREATE SCHEMA IF NOT EXISTS delta.silver
WITH (location = 's3://lakehouse/silver/');
CREATE SCHEMA IF NOT EXISTS delta.gold
WITH (location = 's3://lakehouse/gold/');
-- 1. Bronze Layer: Append-only immutable raw landing table
CREATE TABLE IF NOT EXISTS delta.bronze.orders_raw (
order_id BIGINT,
customer_id BIGINT,
region VARCHAR,
category VARCHAR,
order_date DATE,
event_ts TIMESTAMP(6) WITH TIME ZONE,
amount_usd DOUBLE,
quantity INTEGER,
status VARCHAR,
ingested_at TIMESTAMP(6) WITH TIME ZONE
)
WITH (
location = 's3://lakehouse/bronze/orders_raw',
partitioned_by = ARRAY['order_date']
);
-- 2. Silver Layer: Deduplicated, validated & conformed table
CREATE TABLE IF NOT EXISTS delta.silver.orders_clean
WITH (
location = 's3://lakehouse/silver/orders_clean',
partitioned_by = ARRAY['region']
) AS
WITH ranked_orders AS (
SELECT
order_id,
customer_id,
UPPER(TRIM(region)) AS region,
LOWER(TRIM(category)) AS category,
order_date,
event_ts,
amount_usd,
quantity,
status,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY event_ts DESC, ingested_at DESC
) AS rn
FROM delta.bronze.orders_raw
WHERE amount_usd > 0.0
AND quantity > 0
AND status <> 'CANCELLED'
)
SELECT
order_id,
customer_id,
region,
category,
order_date,
event_ts,
amount_usd,
quantity,
status
FROM ranked_orders
WHERE rn = 1;
-- 3. Gold Layer: Daily revenue & category executive mart
CREATE TABLE IF NOT EXISTS delta.gold.daily_revenue_mart
WITH (
location = 's3://lakehouse/gold/daily_revenue_mart'
) AS
SELECT
order_date,
region,
category,
COUNT(*) AS order_count,
SUM(quantity) AS total_units,
ROUND(SUM(amount_usd), 2) AS gross_revenue_usd,
ROUND(AVG(amount_usd), 2) AS avg_order_value_usd
FROM delta.silver.orders_clean
GROUP BY order_date, region, category;
-- 4. Physical Layout Maintenance: Compact small Parquet files into optimal 128MB chunks
ALTER TABLE delta.silver.orders_clean
EXECUTE optimize(file_size_threshold => '128MB');
ALTER TABLE delta.gold.daily_revenue_mart
EXECUTE optimize(file_size_threshold => '128MB');
"""FSDS-SOTA-2026 Track 2 Lab 07 — Open Lakehouse Storage & Query Engines (`lakehouse_storage_lab`)."""
from __future__ import annotations
from lakehouse_storage_lab.delta_medallion import (
run_delta_medallion_pipeline,
validate_vacuum_retention_safety,
)
from lakehouse_storage_lab.iceberg_occ_sim import (
morton_zorder_2d,
run_iceberg_manifest_pruning_sim,
run_occ_conflict_matrix,
run_zorder_vs_liquid_clustering_benchmark,
)
from lakehouse_storage_lab.infra_audit import audit_lakehouse_infrastructure
from lakehouse_storage_lab.parquet_engine import (
benchmark_csv_vs_parquet,
benchmark_parquet_zone_map_pruning,
generate_order_events,
)
from lakehouse_storage_lab.query_engines import benchmark_duckdb_vs_polars
__all__ = [
"audit_lakehouse_infrastructure",
"benchmark_csv_vs_parquet",
"benchmark_duckdb_vs_polars",
"benchmark_parquet_zone_map_pruning",
"generate_order_events",
"morton_zorder_2d",
"run_delta_medallion_pipeline",
"run_iceberg_manifest_pruning_sim",
"run_occ_conflict_matrix",
"run_zorder_vs_liquid_clustering_benchmark",
"validate_vacuum_retention_safety",
]
"""PyArrow Parquet columnar storage, CSV vs Parquet benchmarks & Zone-Map Row-Group pruning."""
from __future__ import annotations
import csv
import time
from pathlib import Path
from typing import Any
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from pydantic import BaseModel, Field
REGIONS: tuple[str, ...] = ("APAC", "EMEA", "NA", "LATAM")
CATEGORIES: tuple[str, ...] = ("electronics", "apparel", "home", "beauty", "sports", "books")
STATUSES: tuple[str, ...] = ("COMPLETED", "COMPLETED", "COMPLETED", "PENDING", "CANCELLED")
class OrderBatchMetrics(BaseModel):
"""Summary schema for synthetic deterministic order events."""
total_rows: int = Field(..., ge=1)
unique_order_ids: int = Field(..., ge=1)
duplicate_rows: int = Field(..., ge=0)
cancelled_rows: int = Field(..., ge=0)
invalid_amount_rows: int = Field(..., ge=0)
valid_unique_rows: int = Field(..., ge=0)
def generate_order_events(
num_rows: int = 50_000,
duplicate_rate: float = 0.04,
invalid_rate: float = 0.01,
seed: int = 42,
) -> pa.Table:
"""Generate deterministic e-commerce order events as a PyArrow Table.
Includes controlled duplicate order_ids, cancelled statuses, and negative/zero amounts
to exercise Medallion Silver deduplication and data quality contracts.
"""
rng = np.random.default_rng(seed)
n_dups = int(num_rows * duplicate_rate)
n_base = num_rows - n_dups
base_order_ids = np.arange(1, n_base + 1, dtype=np.int64)
dup_order_ids = rng.choice(base_order_ids, size=n_dups, replace=True)
order_ids = np.concatenate([base_order_ids, dup_order_ids])
# Shuffle deterministically so raw landing mimics unsorted streaming ingestion
perm = rng.permutation(num_rows)
order_ids = order_ids[perm]
customer_ids = rng.integers(10_000, 35_000, size=num_rows, dtype=np.int64)
region_idx = rng.integers(0, len(REGIONS), size=num_rows)
category_idx = rng.integers(0, len(CATEGORIES), size=num_rows)
status_idx = rng.integers(0, len(STATUSES), size=num_rows)
# Event days across 60 days (2026-01-01 to 2026-03-01)
day_offsets = rng.integers(0, 60, size=num_rows, dtype=np.int64)
seconds_in_day = rng.integers(0, 86_400, size=num_rows, dtype=np.int64)
base_epoch_sec = 1_767_225_600 # 2026-01-01T00:00:00Z
event_ts_sec = base_epoch_sec + day_offsets * 86_400 + seconds_in_day
# Order dates as ISO strings YYYY-MM-DD for easy CSV/Parquet/Delta interop
# 2026 is not a leap year: Jan(31), Feb(28), Mar(31)
day_labels: list[str] = []
for d in range(60):
if d < 31:
day_labels.append(f"2026-01-{d + 1:02d}")
elif d < 59:
day_labels.append(f"2026-02-{d - 30:02d}")
else:
day_labels.append(f"2026-03-{d - 58:02d}")
order_dates = [day_labels[int(d)] for d in day_offsets]
regions = [REGIONS[int(i)] for i in region_idx]
categories = [CATEGORIES[int(i)] for i in category_idx]
statuses = [STATUSES[int(i)] for i in status_idx]
amounts = np.round(rng.lognormal(mean=4.2, sigma=0.75, size=num_rows), 2)
n_invalid = int(num_rows * invalid_rate)
if n_invalid > 0:
bad_indices = rng.choice(num_rows, size=n_invalid, replace=False)
amounts[bad_indices] = -np.abs(amounts[bad_indices])
quantities = rng.integers(1, 8, size=num_rows, dtype=np.int32)
return pa.table(
{
"order_id": pa.array(order_ids, type=pa.int64()),
"customer_id": pa.array(customer_ids, type=pa.int64()),
"region": pa.array(regions, type=pa.string()),
"category": pa.array(categories, type=pa.string()),
"order_date": pa.array(order_dates, type=pa.string()),
"day_offset": pa.array(day_offsets, type=pa.int32()),
"event_ts": pa.array(event_ts_sec, type=pa.int64()),
"amount_usd": pa.array(amounts, type=pa.float64()),
"quantity": pa.array(quantities, type=pa.int32()),
"status": pa.array(statuses, type=pa.string()),
}
)
def summarize_order_batch(table: pa.Table) -> OrderBatchMetrics:
"""Compute exact quality counts on an order events PyArrow table."""
order_ids = table["order_id"].to_pylist()
amounts = table["amount_usd"].to_pylist()
statuses = table["status"].to_pylist()
unique_ids = set(order_ids)
cancelled = sum(1 for s in statuses if s == "CANCELLED")
invalid_amt = sum(1 for a in amounts if a <= 0.0)
valid_unique_ids = {
oid
for oid, amt, st in zip(order_ids, amounts, statuses, strict=True)
if amt > 0.0 and st != "CANCELLED"
}
return OrderBatchMetrics(
total_rows=table.num_rows,
unique_order_ids=len(unique_ids),
duplicate_rows=table.num_rows - len(unique_ids),
cancelled_rows=cancelled,
invalid_amount_rows=invalid_amt,
valid_unique_rows=len(valid_unique_ids),
)
def benchmark_csv_vs_parquet(
table: pa.Table,
work_dir: Path,
row_group_size: int = 5_000,
) -> dict[str, Any]:
"""Compare uncompressed CSV vs Parquet (Snappy & Zstd) storage size and selective column read."""
work_dir.mkdir(parents=True, exist_ok=True)
csv_path = work_dir / "orders.csv"
pq_snappy_path = work_dir / "orders_snappy.parquet"
pq_zstd_path = work_dir / "orders_zstd.parquet"
# Write CSV deterministically
cols = table.column_names
py_cols = {c: table[c].to_pylist() for c in cols}
with csv_path.open("w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(cols)
for i in range(table.num_rows):
writer.writerow([py_cols[c][i] for c in cols])
# Write Parquet with Dictionary + RLE + Snappy / Zstd
pq.write_table(
table,
pq_snappy_path,
compression="snappy",
use_dictionary=True,
row_group_size=row_group_size,
)
pq.write_table(
table,
pq_zstd_path,
compression="zstd",
use_dictionary=True,
row_group_size=row_group_size,
)
csv_bytes = csv_path.stat().st_size
snappy_bytes = pq_snappy_path.stat().st_size
zstd_bytes = pq_zstd_path.stat().st_size
# Selective 2-column aggregation read (Column Pruning vs Full CSV scan)
t0 = time.perf_counter()
csv_sum = 0.0
csv_count = 0
with csv_path.open("r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
if row["region"] == "APAC":
csv_sum += float(row["amount_usd"])
csv_count += 1
csv_read_ms = (time.perf_counter() - t0) * 1000.0
t1 = time.perf_counter()
snappy_tbl = pq.read_table(pq_snappy_path, columns=["region", "amount_usd"])
snappy_regs = snappy_tbl["region"].to_pylist()
snappy_amts = snappy_tbl["amount_usd"].to_pylist()
snappy_sum = sum(
a for r, a in zip(snappy_regs, snappy_amts, strict=True) if r == "APAC"
)
snappy_read_ms = (time.perf_counter() - t1) * 1000.0
t2 = time.perf_counter()
zstd_tbl = pq.read_table(pq_zstd_path, columns=["region", "amount_usd"])
zstd_regs = zstd_tbl["region"].to_pylist()
zstd_amts = zstd_tbl["amount_usd"].to_pylist()
zstd_sum = sum(
a for r, a in zip(zstd_regs, zstd_amts, strict=True) if r == "APAC"
)
zstd_read_ms = (time.perf_counter() - t2) * 1000.0
# Measure exact Parquet column chunk byte share for 2/10 columns
pf_zstd = pq.ParquetFile(pq_zstd_path)
total_chunk_bytes = 0
pruned_chunk_bytes = 0
for rg_idx in range(pf_zstd.metadata.num_row_groups):
rg = pf_zstd.metadata.row_group(rg_idx)
for c_idx in range(rg.num_columns):
col_meta = rg.column(c_idx)
col_bytes = int(col_meta.total_compressed_size)
total_chunk_bytes += col_bytes
if col_meta.path_in_schema in ("region", "amount_usd"):
pruned_chunk_bytes += col_bytes
column_pruning_io_saved_pct = round(
(1.0 - pruned_chunk_bytes / max(1, total_chunk_bytes)) * 100.0, 2
)
return {
"rows": table.num_rows,
"num_columns": table.num_columns,
"csv_bytes": csv_bytes,
"parquet_snappy_bytes": snappy_bytes,
"parquet_zstd_bytes": zstd_bytes,
"compression_ratio_snappy": round(csv_bytes / max(1, snappy_bytes), 2),
"compression_ratio_zstd": round(csv_bytes / max(1, zstd_bytes), 2),
"csv_read_ms": round(csv_read_ms, 2),
"parquet_snappy_read_ms": round(snappy_read_ms, 2),
"parquet_zstd_read_ms": round(zstd_read_ms, 2),
"read_speedup_zstd_x": round(csv_read_ms / max(0.01, zstd_read_ms), 2),
"column_pruning_cols_read": 2,
"column_pruning_io_saved_pct": column_pruning_io_saved_pct,
"apac_row_count": csv_count,
"apac_sum_parity_ok": abs(csv_sum - snappy_sum) < 1e-4 and abs(csv_sum - zstd_sum) < 1e-4,
}
def _inspect_row_group_pruning(
parquet_path: Path,
filter_col: str,
low: int,
high: int,
) -> dict[str, Any]:
"""Read real PyArrow Parquet Footer Zone-Map Min/Max statistics and evaluate skipping."""
pf = pq.ParquetFile(parquet_path)
meta = pf.metadata
num_rgs = int(meta.num_row_groups)
col_idx = pf.schema_arrow.get_field_index(filter_col)
scanned_rgs = 0
skipped_rgs = 0
total_bytes = 0
scanned_bytes = 0
rg_summaries: list[dict[str, Any]] = []
for i in range(num_rgs):
rg = meta.row_group(i)
col_meta = rg.column(col_idx)
stats = col_meta.statistics
rg_min = int(stats.min)
rg_max = int(stats.max)
rg_bytes = int(rg.total_byte_size)
total_bytes += rg_bytes
# Zone-Map skipping predicate: max < low OR min > high
is_skipped = rg_max < low or rg_min > high
if is_skipped:
skipped_rgs += 1
else:
scanned_rgs += 1
scanned_bytes += rg_bytes
rg_summaries.append(
{
"row_group": i,
"min": rg_min,
"max": rg_max,
"rows": int(rg.num_rows),
"skipped": is_skipped,
}
)
skip_ratio = skipped_rgs / max(1, num_rgs)
return {
"num_row_groups": num_rgs,
"scanned_row_groups": scanned_rgs,
"skipped_row_groups": skipped_rgs,
"skip_ratio": round(skip_ratio, 4),
"skip_pct": round(skip_ratio * 100.0, 2),
"bytes_scanned_ratio": round(scanned_bytes / max(1, total_bytes), 4),
"row_groups_sample": rg_summaries[:6],
}
def benchmark_parquet_zone_map_pruning(
table: pa.Table,
work_dir: Path,
filter_day_low: int = 52,
filter_day_high: int = 56,
row_group_size: int = 2_500,
) -> dict[str, Any]:
"""Demonstrate Row-Group Zone-Map Min/Max skipping: Unsorted vs Sorted Parquet files."""
work_dir.mkdir(parents=True, exist_ok=True)
unsorted_path = work_dir / "orders_unsorted.parquet"
sorted_path = work_dir / "orders_sorted_by_day.parquet"
pq.write_table(
table,
unsorted_path,
compression="zstd",
row_group_size=row_group_size,
write_statistics=True,
)
sorted_table = table.sort_by([("day_offset", "ascending"), ("region", "ascending")])
pq.write_table(
sorted_table,
sorted_path,
compression="zstd",
row_group_size=row_group_size,
write_statistics=True,
)
unsorted_stats = _inspect_row_group_pruning(
unsorted_path, "day_offset", filter_day_low, filter_day_high
)
sorted_stats = _inspect_row_group_pruning(
sorted_path, "day_offset", filter_day_low, filter_day_high
)
# Verify actual filtered read returns identical row counts
filt = [("day_offset", ">=", filter_day_low), ("day_offset", "<=", filter_day_high)]
u_rows = pq.read_table(unsorted_path, filters=filt).num_rows
s_rows = pq.read_table(sorted_path, filters=filt).num_rows
return {
"predicate": f"day_offset BETWEEN {filter_day_low} AND {filter_day_high}",
"row_group_size": row_group_size,
"matched_rows": s_rows,
"result_parity_ok": u_rows == s_rows,
"unsorted": unsorted_stats,
"sorted": sorted_stats,
"row_group_reduction_x": round(
unsorted_stats["scanned_row_groups"] / max(1, sorted_stats["scanned_row_groups"]), 2
),
}
"""Real Delta Lake (`deltalake`) ACID Medallion pipeline, Time Travel, Compaction & VACUUM guard."""
from __future__ import annotations
import json
import tempfile
from pathlib import Path
from typing import Any
import polars as pl
import pyarrow as pa
from deltalake import DeltaTable, write_deltalake
from lakehouse_storage_lab.parquet_engine import generate_order_events
def validate_vacuum_retention_safety(
retention_hours: float,
max_concurrent_query_hours: float,
time_travel_sla_hours: float,
clock_skew_margin_hours: float = 1.0,
) -> dict[str, Any]:
"""Verify the VACUUM retention inequality:
T_retention >= max(T_query_max, T_time_travel_SLA) + delta_clock.
"""
min_safe_hours = max(max_concurrent_query_hours, time_travel_sla_hours) + clock_skew_margin_hours
is_safe = retention_hours >= min_safe_hours
risk = "SAFE"
if retention_hours < max_concurrent_query_hours + clock_skew_margin_hours:
risk = "CRITICAL_CONCURRENT_READER_FILE_NOT_FOUND"
elif retention_hours < min_safe_hours:
risk = "VIOLATES_TIME_TRAVEL_SLA"
return {
"retention_hours": retention_hours,
"max_concurrent_query_hours": max_concurrent_query_hours,
"time_travel_sla_hours": time_travel_sla_hours,
"clock_skew_margin_hours": clock_skew_margin_hours,
"min_safe_retention_hours": round(min_safe_hours, 2),
"is_safe": is_safe,
"risk_classification": risk,
}
def inspect_delta_log(table_dir: Path) -> dict[str, Any]:
"""Read real `_delta_log/*.json` commit files and tally protocol/metaData/add/remove actions."""
log_dir = table_dir / "_delta_log"
json_files = sorted(p for p in log_dir.glob("*.json") if p.is_file())
action_counts = {"protocol": 0, "metaData": 0, "add": 0, "remove": 0, "commitInfo": 0}
commits: list[dict[str, Any]] = []
for jf in json_files:
commit_actions: dict[str, int] = {"add": 0, "remove": 0}
with jf.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
obj = json.loads(line)
for key in action_counts:
if key in obj:
action_counts[key] += 1
if "add" in obj:
commit_actions["add"] += 1
if "remove" in obj:
commit_actions["remove"] += 1
commits.append(
{
"commit_file": jf.name,
"adds": commit_actions["add"],
"removes": commit_actions["remove"],
}
)
return {
"commit_json_count": len(json_files),
"action_counts": action_counts,
"commits": commits,
}
def run_delta_medallion_pipeline(
base_dir: Path,
raw_table: pa.Table,
small_file_batches: int = 12,
) -> dict[str, Any]:
"""Execute a real Bronze -> Silver -> Gold Delta Lake pipeline on disk.
Exercises:
1. Bronze append (v0) + Schema Enforcement rejection + Schema Evolution (`schema_mode='merge'`)
adding `loyalty_tier` (v1).
2. Silver cleaning/deduplication (`amount_usd > 0`, `status != 'CANCELLED'`, latest `event_ts`
per `order_id`) + Time Travel verification (`v0` vs `v1`) + `_delta_log` audit.
3. Small-file bloat (`small_file_batches` tiny commits) -> real `dt.optimize.compact()`
-> `dt.vacuum(dry_run=True)` stale file detection + retention-window safety check.
4. Gold daily revenue mart written as a Delta table.
"""
base_dir.mkdir(parents=True, exist_ok=True)
bronze_path = base_dir / "bronze_orders"
silver_path = base_dir / "silver_orders"
gold_path = base_dir / "gold_daily_revenue"
small_files_path = base_dir / "silver_small_files_demo"
# --- 1. BRONZE: Initial v0 append ---
write_deltalake(str(bronze_path), raw_table, mode="overwrite")
bronze_v0 = DeltaTable(str(bronze_path))
v0_rows = bronze_v0.to_pyarrow_table().num_rows
v0_cols = [f.name for f in bronze_v0.to_pyarrow_table().schema]
# --- 2. BRONZE: Schema Enforcement rejection test ---
bad_batch = pa.table(
{
"order_id": pa.array([999_999], type=pa.int64()),
"customer_id": pa.array([12345], type=pa.int64()),
"region": pa.array(["APAC"], type=pa.string()),
"unexpected_corrupt_col": pa.array(["POISON"], type=pa.string()),
}
)
schema_enforced_rejected = False
schema_error_type = ""
try:
write_deltalake(str(bronze_path), bad_batch, mode="append")
except Exception as exc:
schema_enforced_rejected = True
schema_error_type = type(exc).__name__
# --- 3. BRONZE: Controlled Schema Evolution (`schema_mode="merge"`) adding `loyalty_tier` ---
evolved_batch = pa.table(
{
"order_id": pa.array([900_001, 900_002, 900_003], type=pa.int64()),
"customer_id": pa.array([10_001, 10_002, 10_003], type=pa.int64()),
"region": pa.array(["APAC", "EMEA", "NA"], type=pa.string()),
"category": pa.array(["electronics", "apparel", "home"], type=pa.string()),
"order_date": pa.array(["2026-03-01", "2026-03-01", "2026-03-01"], type=pa.string()),
"day_offset": pa.array([59, 59, 59], type=pa.int32()),
"event_ts": pa.array([1_772_323_200, 1_772_323_260, 1_772_323_320], type=pa.int64()),
"amount_usd": pa.array([250.0, 180.0, 320.0], type=pa.float64()),
"quantity": pa.array([2, 1, 3], type=pa.int32()),
"status": pa.array(["COMPLETED", "COMPLETED", "COMPLETED"], type=pa.string()),
"loyalty_tier": pa.array(["PLATINUM", "GOLD", "SILVER"], type=pa.string()),
}
)
write_deltalake(str(bronze_path), evolved_batch, mode="append", schema_mode="merge")
# Verify real Delta Time Travel (v0 vs v1)
bronze_tt_v0 = DeltaTable(str(bronze_path), version=0).to_pyarrow_table()
bronze_tt_v1 = DeltaTable(str(bronze_path), version=1).to_pyarrow_table()
v1_cols = [f.name for f in bronze_tt_v1.schema]
bronze_log_audit = inspect_delta_log(bronze_path)
# --- 4. SILVER: Deduplicate & enforce quality contract ---
bronze_df = pl.from_arrow(bronze_tt_v1)
assert isinstance(bronze_df, pl.DataFrame)
silver_df = (
bronze_df.filter((pl.col("amount_usd") > 0.0) & (pl.col("status") != "CANCELLED"))
.sort(["order_id", "event_ts"], descending=[False, True])
.unique(subset=["order_id"], keep="first", maintain_order=True)
)
silver_arrow = silver_df.to_arrow()
write_deltalake(str(silver_path), silver_arrow, mode="overwrite")
silver_dt = DeltaTable(str(silver_path))
silver_total_revenue = round(float(silver_df["amount_usd"].sum()), 2)
# --- 5. GOLD: Executive daily revenue mart ---
gold_df = (
silver_df.group_by(["region", "category"])
.agg(
pl.len().alias("order_count"),
pl.col("quantity").sum().alias("total_units"),
pl.col("amount_usd").sum().round(2).alias("gross_revenue_usd"),
pl.col("amount_usd").mean().round(2).alias("avg_order_value_usd"),
)
.sort(["region", "category"])
)
write_deltalake(str(gold_path), gold_df.to_arrow(), mode="overwrite")
gold_dt = DeltaTable(str(gold_path))
gold_total_revenue = round(float(gold_df["gross_revenue_usd"].sum()), 2)
# --- 6. SMALL-FILE BLOAT -> REAL COMPACTION (`optimize.compact()`) -> VACUUM DRY-RUN ---
sample_rows = min(1200, silver_arrow.num_rows)
chunk_size = max(10, sample_rows // small_file_batches)
for b_idx in range(small_file_batches):
start = b_idx * chunk_size
slice_tbl = silver_arrow.slice(start, chunk_size)
write_deltalake(str(small_files_path), slice_tbl, mode="append")
sf_dt_before = DeltaTable(str(small_files_path))
files_before = len(sf_dt_before.file_uris())
rows_before = sf_dt_before.to_pyarrow_table().num_rows
compact_metrics = sf_dt_before.optimize.compact()
sf_dt_after = DeltaTable(str(small_files_path))
files_after = len(sf_dt_after.file_uris())
rows_after = sf_dt_after.to_pyarrow_table().num_rows
# Dry-run vacuum with retention=0 (only for inspecting orphaned files safely in demo!)
vacuum_candidates = sf_dt_after.vacuum(
retention_hours=0,
enforce_retention_duration=False,
dry_run=True,
)
sf_log_audit = inspect_delta_log(small_files_path)
# Evaluate safety guard: unsafe 0h vs safe 168h (7 days)
vacuum_unsafe_guard = validate_vacuum_retention_safety(
retention_hours=0.0,
max_concurrent_query_hours=4.0,
time_travel_sla_hours=168.0,
)
vacuum_safe_guard = validate_vacuum_retention_safety(
retention_hours=172.0,
max_concurrent_query_hours=4.0,
time_travel_sla_hours=168.0,
)
return {
"bronze_path": str(bronze_path),
"silver_path": str(silver_path),
"gold_path": str(gold_path),
"bronze": {
"v0_rows": v0_rows,
"v0_columns": v0_cols,
"v1_rows": bronze_tt_v1.num_rows,
"v1_columns": v1_cols,
"schema_enforced_rejected": schema_enforced_rejected,
"schema_error_type": schema_error_type,
"time_travel_v0_rows": bronze_tt_v0.num_rows,
"time_travel_v0_has_loyalty_tier": "loyalty_tier" in bronze_tt_v0.column_names,
"time_travel_v1_has_loyalty_tier": "loyalty_tier" in bronze_tt_v1.column_names,
"delta_log_audit": bronze_log_audit,
},
"silver": {
"rows": silver_dt.to_pyarrow_table().num_rows,
"duplicates_and_bad_filtered": bronze_tt_v1.num_rows - silver_df.height,
"total_revenue_usd": silver_total_revenue,
"active_files": len(silver_dt.file_uris()),
},
"gold": {
"rows": gold_dt.to_pyarrow_table().num_rows,
"total_revenue_usd": gold_total_revenue,
"revenue_parity_with_silver_ok": abs(silver_total_revenue - gold_total_revenue) <= 0.1,
"active_files": len(gold_dt.file_uris()),
},
"compaction_and_vacuum": {
"small_file_batches_written": small_file_batches,
"active_files_before_compact": files_before,
"active_files_after_compact": files_after,
"file_reduction_x": round(files_before / max(1, files_after), 2),
"rows_preserved_ok": rows_before == rows_after,
"num_files_added": int(compact_metrics.get("numFilesAdded", 0)),
"num_files_removed": int(compact_metrics.get("numFilesRemoved", 0)),
"vacuum_dry_run_stale_files": len(vacuum_candidates),
"delta_log_commits": sf_log_audit["commit_json_count"],
"delta_log_removes": sf_log_audit["action_counts"]["remove"],
"vacuum_guard_0h": vacuum_unsafe_guard,
"vacuum_guard_172h": vacuum_safe_guard,
},
}
def main() -> None:
"""Quick CLI smoke entry point running the Medallion Delta Lake pipeline in a temp directory."""
with tempfile.TemporaryDirectory() as tmp:
raw = generate_order_events(num_rows=5_000, seed=42)
res = run_delta_medallion_pipeline(Path(tmp), raw, small_file_batches=12)
print(json.dumps(res["compaction_and_vacuum"], indent=2))
"""DuckDB 2.x SQL & Polars 2.x Lazy Execution query engine parity and performance benchmark."""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any
import duckdb
import polars as pl
import pyarrow.parquet as pq
from deltalake import DeltaTable
def benchmark_duckdb_vs_polars(
silver_delta_dir: Path,
parquet_export_dir: Path,
repeats: int = 3,
) -> dict[str, Any]:
"""Run identical analytical OLAP aggregation on DuckDB 2.x and Polars 2.x Lazy.
Reads the Silver Delta table via Arrow zero-copy AND exports a partitioned-free Parquet
file so both DuckDB `read_parquet` and Polars `scan_parquet` execute true columnar pushdown.
"""
parquet_export_dir.mkdir(parents=True, exist_ok=True)
silver_dt = DeltaTable(str(silver_delta_dir))
silver_arrow = silver_dt.to_pyarrow_table()
silver_pq = parquet_export_dir / "silver_orders.parquet"
pq.write_table(silver_arrow, silver_pq, compression="zstd", row_group_size=5_000)
pq_posix = str(silver_pq).replace("\\", "/")
# --- 1. DuckDB 2.x SQL on Parquet (vectorized execution + predicate/projection pushdown) ---
con = duckdb.connect(database=":memory:")
duck_sql = f"""
SELECT
region,
category,
COUNT(*)::BIGINT AS order_count,
SUM(quantity)::BIGINT AS total_units,
ROUND(SUM(amount_usd), 2) AS gross_revenue_usd
FROM read_parquet('{pq_posix}')
WHERE region IN ('APAC', 'EMEA')
AND amount_usd >= 50.0
GROUP BY region, category
ORDER BY region ASC, category ASC
"""
duck_times: list[float] = []
duck_rows: list[tuple[Any, ...]] = []
for _ in range(repeats):
t0 = time.perf_counter()
duck_rows = con.execute(duck_sql).fetchall()
duck_times.append((time.perf_counter() - t0) * 1000.0)
# Also verify Arrow zero-copy query directly over DeltaTable -> PyArrow Table
arrow_count_row = con.execute("SELECT COUNT(*)::BIGINT FROM silver_arrow").fetchone()
arrow_zero_copy_rows = int(arrow_count_row[0]) if arrow_count_row is not None else 0
con.close()
# --- 2. Polars 2.x Lazy scan_parquet (Rust SIMD + pushdown optimizer) ---
polars_times: list[float] = []
polars_rows: list[tuple[Any, ...]] = []
for _ in range(repeats):
t1 = time.perf_counter()
lazy_df = (
pl.scan_parquet(silver_pq)
.filter(pl.col("region").is_in(["APAC", "EMEA"]) & (pl.col("amount_usd") >= 50.0))
.group_by(["region", "category"])
.agg(
pl.len().cast(pl.Int64).alias("order_count"),
pl.col("quantity").sum().cast(pl.Int64).alias("total_units"),
pl.col("amount_usd").sum().round(2).alias("gross_revenue_usd"),
)
.sort(["region", "category"])
)
collected = lazy_df.collect()
polars_rows = [tuple(r) for r in collected.iter_rows()]
polars_times.append((time.perf_counter() - t1) * 1000.0)
# Exact parity verification across all groups
exact_parity = len(duck_rows) == len(polars_rows)
max_rev_diff = 0.0
if exact_parity:
for d_row, p_row in zip(duck_rows, polars_rows, strict=True):
rev_diff = abs(float(d_row[4]) - float(p_row[4]))
max_rev_diff = max(max_rev_diff, rev_diff)
if (
d_row[0] != p_row[0]
or d_row[1] != p_row[1]
or int(d_row[2]) != int(p_row[2])
or int(d_row[3]) != int(p_row[3])
or rev_diff > 0.02
):
exact_parity = False
break
total_filtered_revenue = round(sum(float(r[4]) for r in duck_rows), 2)
total_filtered_orders = sum(int(r[2]) for r in duck_rows)
return {
"silver_total_rows": silver_arrow.num_rows,
"arrow_zero_copy_rows": arrow_zero_copy_rows,
"groups_returned": len(duck_rows),
"filtered_order_count": total_filtered_orders,
"filtered_gross_revenue_usd": total_filtered_revenue,
"duckdb_median_ms": round(sorted(duck_times)[len(duck_times) // 2], 2),
"polars_median_ms": round(sorted(polars_times)[len(polars_times) // 2], 2),
"exact_kpi_parity": exact_parity,
"max_revenue_diff_usd": round(max_rev_diff, 4),
"top_groups": [
{
"region": str(r[0]),
"category": str(r[1]),
"order_count": int(r[2]),
"total_units": int(r[3]),
"gross_revenue_usd": float(r[4]),
}
for r in duck_rows[:6]
],
}
"""Apache Iceberg 3-tier metadata pruning, OCC conflict detection & Z-Order vs Liquid Clustering."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
@dataclass(frozen=True, slots=True)
class IcebergDataFile:
"""Data file leaf in an Iceberg Manifest File with column lower/upper bounds."""
file_id: str
day_partition: int
region_min: int
region_max: int
amount_min: float
amount_max: float
num_rows: int
@dataclass(frozen=True, slots=True)
class IcebergManifestFile:
"""Iceberg Manifest File grouping data files for a partition range."""
manifest_id: str
day_min: int
day_max: int
data_files: tuple[IcebergDataFile, ...]
def run_iceberg_manifest_pruning_sim(
num_days: int = 60,
manifests_per_month: int = 2,
files_per_day: int = 4,
query_day_start: int = 45,
query_day_end: int = 47,
query_region: int = 2,
) -> dict[str, Any]:
"""Simulate Apache Iceberg 3-tier metadata tree pruning & Hidden Partitioning (`days(event_ts)`).
Demonstrates:
1. Manifest-List level pruning using partition summary `[day_min, day_max]`.
2. Manifest-File level pruning using column bounds `[region_min, region_max]` & `day_partition`.
3. Hidden Partitioning vs Naive Hive full-scan trap when users filter only on `event_ts`.
"""
manifests: list[IcebergManifestFile] = []
days_per_manifest = max(1, num_days // (manifests_per_month * 2))
manifest_idx = 0
for start_day in range(0, num_days, days_per_manifest):
end_day = min(num_days - 1, start_day + days_per_manifest - 1)
data_files: list[IcebergDataFile] = []
for d in range(start_day, end_day + 1):
for r in range(files_per_day):
data_files.append(
IcebergDataFile(
file_id=f"data-d{d:02d}-r{r}.parquet",
day_partition=d,
region_min=r,
region_max=r,
amount_min=10.0 + r * 20.0,
amount_max=450.0 + r * 50.0,
num_rows=10_000,
)
)
manifests.append(
IcebergManifestFile(
manifest_id=f"manifest-{manifest_idx:03d}.avro",
day_min=start_day,
day_max=end_day,
data_files=tuple(data_files),
)
)
manifest_idx += 1
total_manifests = len(manifests)
total_data_files = sum(len(m.data_files) for m in manifests)
# Tier 2: Manifest List Pruning (Hidden Partitioning translates event_ts -> days(event_ts))
kept_manifests = [
m for m in manifests if not (m.day_max < query_day_start or m.day_min > query_day_end)
]
pruned_manifests = total_manifests - len(kept_manifests)
# Tier 3: Manifest File -> Data File Pruning using exact day + region column bounds
scanned_files: list[str] = []
for m in kept_manifests:
for df in m.data_files:
day_match = query_day_start <= df.day_partition <= query_day_end
region_match = df.region_min <= query_region <= df.region_max
if day_match and region_match:
scanned_files.append(df.file_id)
skipped_files = total_data_files - len(scanned_files)
file_skip_pct = round((skipped_files / max(1, total_data_files)) * 100.0, 2)
manifest_skip_pct = round((pruned_manifests / max(1, total_manifests)) * 100.0, 2)
return {
"query_predicate": (
f"event_ts IN days[{query_day_start}..{query_day_end}] AND region_id = {query_region}"
),
"hidden_partition_transform": "days(event_ts)",
"total_manifests": total_manifests,
"manifests_pruned": pruned_manifests,
"manifests_scanned": len(kept_manifests),
"manifest_skip_pct": manifest_skip_pct,
"total_data_files": total_data_files,
"data_files_scanned": len(scanned_files),
"data_files_skipped": skipped_files,
"data_file_skip_pct": file_skip_pct,
"naive_hive_missing_partition_col_files_scanned": total_data_files,
"iceberg_vs_hive_trap_speedup_x": round(
total_data_files / max(1, len(scanned_files)), 2
),
}
@dataclass(frozen=True, slots=True)
class OccTransaction:
"""Optimistic Concurrency Control transaction intent on a Lakehouse table."""
tx_id: str
op_type: Literal["APPEND", "UPDATE", "DELETE", "OVERWRITE"]
read_version: int
read_partitions: frozenset[str]
written_partitions: frozenset[str]
removed_files: frozenset[str]
isolation_level: Literal["WriteSerializable", "Serializable"] = "WriteSerializable"
def evaluate_occ_commit(
committed_tx: OccTransaction,
incoming_tx: OccTransaction,
) -> dict[str, Any]:
"""Detect Optimistic Concurrency Control conflict between an already-committed version v+1
and a concurrent transaction that read from v.
"""
if incoming_tx.read_version > committed_tx.read_version:
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "COMMITTED_DIRECT",
"conflict_detected": False,
"retry_required": False,
"reason": "No concurrent commit occurred since read_version.",
}
# Case 1: Append + Append -> Blind append never modifies existing files; rebase cleanly!
if committed_tx.op_type == "APPEND" and incoming_tx.op_type == "APPEND":
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "AUTO_REBASED_COMMIT",
"conflict_detected": False,
"retry_required": False,
"reason": "Disjoint file additions (Append+Append); atomic rebase to v+2 succeeds.",
}
# Case 2: Both remove overlapping files -> ConcurrentDeleteDeleteException
overlap_removed = committed_tx.removed_files & incoming_tx.removed_files
if overlap_removed:
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "CONFLICT_RETRY_REQUIRED",
"conflict_detected": True,
"retry_required": True,
"reason": (
f"ConcurrentDeleteDeleteException on files {sorted(overlap_removed)}; "
"must reload latest snapshot and retry."
),
}
# Case 3: Committed DELETE/UPDATE/OVERWRITE modified partitions read by incoming_tx
overlap_read_write = committed_tx.written_partitions & incoming_tx.read_partitions
if committed_tx.op_type in ("DELETE", "UPDATE", "OVERWRITE") and overlap_read_write:
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "CONFLICT_RETRY_REQUIRED",
"conflict_detected": True,
"retry_required": True,
"reason": (
f"ConcurrentDeleteReadException: committed {committed_tx.op_type} mutated "
f"partitions {sorted(overlap_read_write)} read by {incoming_tx.tx_id}."
),
}
# Case 4: Serializable blocks concurrent APPEND into partitions scanned by UPDATE/DELETE/OVERWRITE
if (
incoming_tx.isolation_level == "Serializable"
and committed_tx.op_type == "APPEND"
and (committed_tx.written_partitions & incoming_tx.read_partitions)
):
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "CONFLICT_RETRY_REQUIRED",
"conflict_detected": True,
"retry_required": True,
"reason": (
"ConcurrentAppendException under Serializable isolation: "
"new data appended into scanned predicate range."
),
}
return {
"incoming_tx": incoming_tx.tx_id,
"committed_tx": committed_tx.tx_id,
"status": "AUTO_REBASED_COMMIT",
"conflict_detected": False,
"retry_required": False,
"reason": "Disjoint partition/file predicates under WriteSerializable; rebase succeeds.",
}
def run_occ_conflict_matrix() -> dict[str, Any]:
"""Run four canonical Lakehouse OCC scenarios covering Append, Delete, Overwrite & Isolation."""
t_append_a = OccTransaction(
tx_id="tx_append_stream_a",
op_type="APPEND",
read_version=10,
read_partitions=frozenset(),
written_partitions=frozenset({"dt=2026-03-01"}),
removed_files=frozenset(),
)
t_append_b = OccTransaction(
tx_id="tx_append_stream_b",
op_type="APPEND",
read_version=10,
read_partitions=frozenset(),
written_partitions=frozenset({"dt=2026-03-01"}),
removed_files=frozenset(),
)
t_delete_gdpr = OccTransaction(
tx_id="tx_gdpr_delete",
op_type="DELETE",
read_version=10,
read_partitions=frozenset({"dt=2026-02-15"}),
written_partitions=frozenset({"dt=2026-02-15"}),
removed_files=frozenset({"part-0042.parquet"}),
)
t_overwrite_same = OccTransaction(
tx_id="tx_backfill_overwrite",
op_type="OVERWRITE",
read_version=10,
read_partitions=frozenset({"dt=2026-02-15"}),
written_partitions=frozenset({"dt=2026-02-15"}),
removed_files=frozenset({"part-0042.parquet"}),
)
t_update_serializable = OccTransaction(
tx_id="tx_update_serializable",
op_type="UPDATE",
read_version=10,
read_partitions=frozenset({"dt=2026-03-01"}),
written_partitions=frozenset({"dt=2026-03-01"}),
removed_files=frozenset({"part-0099.parquet"}),
isolation_level="Serializable",
)
t_delete_disjoint = OccTransaction(
tx_id="tx_delete_other_partition",
op_type="DELETE",
read_version=10,
read_partitions=frozenset({"dt=2026-01-10"}),
written_partitions=frozenset({"dt=2026-01-10"}),
removed_files=frozenset({"part-0005.parquet"}),
)
return {
"append_vs_append": evaluate_occ_commit(t_append_a, t_append_b),
"delete_vs_overwrite_same_file": evaluate_occ_commit(t_delete_gdpr, t_overwrite_same),
"append_vs_serializable_update": evaluate_occ_commit(t_append_a, t_update_serializable),
"delete_vs_disjoint_delete": evaluate_occ_commit(t_delete_gdpr, t_delete_disjoint),
}
def morton_zorder_2d(x: int, y: int, bits: int = 16) -> int:
"""Compute exact 2D Morton Z-Order key by bit interleaving x and y."""
if x < 0 or y < 0:
raise ValueError("Morton coordinates must be non-negative integers.")
z = 0
for i in range(bits):
z |= ((x >> i) & 1) << (2 * i)
z |= ((y >> i) & 1) << (2 * i + 1)
return z
def _evaluate_2d_file_skipping(
xs: np.ndarray,
ys: np.ndarray,
order_idx: np.ndarray,
num_files: int,
q_x_range: tuple[int, int],
q_y_range: tuple[int, int],
) -> dict[str, Any]:
"""Partition ordered 2D points into `num_files` Parquet files and measure Zone-Map skipping."""
n = len(xs)
file_size = max(1, n // num_files)
ox = xs[order_idx]
oy = ys[order_idx]
scanned = 0
total_files = 0
for start in range(0, n, file_size):
end = min(n, start + file_size)
if start >= end:
break
total_files += 1
f_xmin, f_xmax = int(ox[start:end].min()), int(ox[start:end].max())
f_ymin, f_ymax = int(oy[start:end].min()), int(oy[start:end].max())
x_overlap = not (f_xmax < q_x_range[0] or f_xmin > q_x_range[1])
y_overlap = not (f_ymax < q_y_range[0] or f_ymin > q_y_range[1])
if x_overlap and y_overlap:
scanned += 1
skipped = total_files - scanned
return {
"total_files": total_files,
"files_scanned": scanned,
"files_skipped": skipped,
"skip_pct": round((skipped / max(1, total_files)) * 100.0, 2),
}
def run_zorder_vs_liquid_clustering_benchmark(
num_points: int = 16_384,
num_files: int = 64,
incremental_batch_ratio: float = 0.15,
seed: int = 42,
) -> dict[str, Any]:
"""Compare Unsorted, Lexicographical Sort, Z-Ordering (Morton) & Liquid Clustering.
Measures:
1. Multi-dimensional 2D query data skipping across (customer_bucket, day_offset).
2. Write Amplification (`WA = 1 + bytes_rewritten / bytes_initial`) when appending an
incremental batch (`15%` new data) across 5 ingestion rounds:
- Classic Z-Order rewrites the entire partition each cycle -> high WA.
- Liquid Clustering clusters only incremental new/unclustered Z-cubes -> low WA.
"""
rng = np.random.default_rng(seed)
# Two orthogonal high-selectivity filter dimensions in [0, 255]
xs = rng.integers(0, 256, size=num_points, dtype=np.int32)
ys = rng.integers(0, 256, size=num_points, dtype=np.int32)
# Selective 2D query box: ~12.5% x 12.5% (~1.56% of 2D domain)
q_x = (64, 95)
q_y = (128, 159)
unsorted_idx = np.arange(num_points)
lex_idx = np.lexsort((ys, xs)) # primary x, secondary y
z_keys = np.array(
[morton_zorder_2d(int(x), int(y), bits=8) for x, y in zip(xs, ys, strict=True)],
dtype=np.int64,
)
zorder_idx = np.argsort(z_keys, kind="mergesort")
# Liquid Clustering partitions 2D space into balanced hierarchical Hilbert/Z-cubes
# (grid cells 8x8 -> 64 cubes) so each cube has tight bounding box and incremental maintenance
cube_x = xs // 32 # 0..7
cube_y = ys // 32 # 0..7
liquid_keys = np.array(
[morton_zorder_2d(int(cx), int(cy), bits=4) for cx, cy in zip(cube_x, cube_y, strict=True)],
dtype=np.int64,
)
liquid_idx = np.argsort(liquid_keys, kind="mergesort")
# Evaluate 2D query AND single-column y query (shows lex_sort fails when filtering on col 2!)
unsorted_2d = _evaluate_2d_file_skipping(xs, ys, unsorted_idx, num_files, q_x, q_y)
lex_2d = _evaluate_2d_file_skipping(xs, ys, lex_idx, num_files, q_x, q_y)
zorder_2d = _evaluate_2d_file_skipping(xs, ys, zorder_idx, num_files, q_x, q_y)
liquid_2d = _evaluate_2d_file_skipping(xs, ys, liquid_idx, num_files, q_x, q_y)
lex_y_only = _evaluate_2d_file_skipping(xs, ys, lex_idx, num_files, (0, 255), q_y)
zorder_y_only = _evaluate_2d_file_skipping(xs, ys, zorder_idx, num_files, (0, 255), q_y)
liquid_y_only = _evaluate_2d_file_skipping(xs, ys, liquid_idx, num_files, (0, 255), q_y)
# Write Amplification across 5 incremental ingestion rounds (initial 1000 MB + 5x 150 MB)
base_mb = 1000.0
inc_mb = base_mb * incremental_batch_ratio
rounds = 5
total_ingested_mb = base_mb + rounds * inc_mb
# Classic Z-Order rewrites the entire cumulative table/partition on each optimize pass
zorder_rewritten_mb = sum(base_mb + r * inc_mb for r in range(1, rounds + 1))
zorder_wa = round(1.0 + zorder_rewritten_mb / total_ingested_mb, 2)
# Liquid Clustering only rewrites new incremental files + small boundary merges (~1.25x inc_mb)
liquid_rewritten_mb = sum(1.25 * inc_mb for _ in range(rounds))
liquid_wa = round(1.0 + liquid_rewritten_mb / total_ingested_mb, 2)
return {
"num_points": num_points,
"num_files": num_files,
"query_2d_box": {"x": list(q_x), "y": list(q_y)},
"unsorted_2d": unsorted_2d,
"lex_sort_2d": lex_2d,
"zorder_2d": zorder_2d,
"liquid_clustering_2d": liquid_2d,
"col2_only_skip_pct": {
"lex_sort": lex_y_only["skip_pct"],
"zorder": zorder_y_only["skip_pct"],
"liquid_clustering": liquid_y_only["skip_pct"],
},
"write_amplification_5_rounds": {
"total_ingested_mb": round(total_ingested_mb, 1),
"zorder_rewritten_mb": round(zorder_rewritten_mb, 1),
"zorder_wa": zorder_wa,
"liquid_rewritten_mb": round(liquid_rewritten_mb, 1),
"liquid_wa": liquid_wa,
"wa_reduction_x": round(zorder_wa / max(0.01, liquid_wa), 2),
},
}
"""Static infrastructure auditor for Lab 07 Docker Compose, Trino Delta catalog & Medallion SQL."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
import yaml
REQUIRED_SERVICES = frozenset(
{"minio", "minio-init", "postgres-metastore", "hive-metastore", "trino"}
)
def _parse_properties(path: Path) -> dict[str, str]:
props: dict[str, str] = {}
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
k, v = line.split("=", 1)
props[k.strip()] = v.strip()
return props
def audit_lakehouse_infrastructure(lab_root: Path) -> dict[str, Any]:
"""Statically audit docker-compose.yml, Trino Delta catalog & Medallion Trino SQL."""
compose_path = lab_root / "docker-compose.yml"
trino_cfg_path = lab_root / "configs" / "trino_delta_catalog.properties"
sql_path = lab_root / "sql" / "01_medallion_trino.sql"
compose_data = yaml.safe_load(compose_path.read_text(encoding="utf-8"))
services: dict[str, Any] = compose_data.get("services", {})
service_names = sorted(services.keys())
has_all_services = REQUIRED_SERVICES.issubset(set(service_names))
# Pinned image tags (no ':latest' or untagged image)
unpinned_images: list[str] = []
for svc_name, svc_def in services.items():
img = str(svc_def.get("image", ""))
if ":" not in img or img.endswith(":latest"):
unpinned_images.append(f"{svc_name}:{img}")
# Healthchecks on long-running services (exclude one-shot minio-init)
long_running = ("minio", "postgres-metastore", "hive-metastore", "trino")
all_healthchecks_ok = all("healthcheck" in services.get(s, {}) for s in long_running)
# Trino & Hive Metastore depend on healthy dependencies
trino_deps = services.get("trino", {}).get("depends_on", {})
trino_healthy_deps = (
isinstance(trino_deps, dict)
and trino_deps.get("hive-metastore", {}).get("condition") == "service_healthy"
and trino_deps.get("minio", {}).get("condition") == "service_healthy"
)
# Check isolated network & non-hardcoded env-default credentials
networks_ok = "lakehouse_net" in compose_data.get("networks", {})
compose_text = compose_path.read_text(encoding="utf-8")
uses_env_defaults = (
"${MINIO_ROOT_USER:-" in compose_text
and "${MINIO_ROOT_PASSWORD:-" in compose_text
and "${METASTORE_PASSWORD:-" in compose_text
)
# Audit Trino Delta catalog properties
props = _parse_properties(trino_cfg_path)
trino_props_ok = (
props.get("connector.name") == "delta_lake"
and "thrift://hive-metastore:9083" in props.get("hive.metastore.uri", "")
and props.get("s3.endpoint") == "http://minio:9000"
and props.get("s3.path-style-access") == "true"
and props.get("delta.vacuum.min-retention") == "168h"
and "${ENV:MINIO_ROOT_PASSWORD}" in props.get("s3.aws-secret-key", "")
)
# Audit Trino Medallion SQL
sql_text = sql_path.read_text(encoding="utf-8")
sql_upper = sql_text.upper()
sql_has_schemas = all(
f"CREATE SCHEMA IF NOT EXISTS DELTA.{layer}" in sql_upper
for layer in ("BRONZE", "SILVER", "GOLD")
)
sql_has_dedup = "ROW_NUMBER()" in sql_upper and "PARTITION BY ORDER_ID" in sql_upper
sql_has_gold_mart = "DELTA.GOLD.DAILY_REVENUE_MART" in sql_upper and "GROUP BY" in sql_upper
sql_has_optimize = bool(
re.search(r"ALTER\s+TABLE\s+delta\.silver\.orders_clean\s+EXECUTE\s+optimize", sql_text, re.I)
)
sql_all_ok = sql_has_schemas and sql_has_dedup and sql_has_gold_mart and sql_has_optimize
all_passed = (
has_all_services
and len(unpinned_images) == 0
and all_healthchecks_ok
and trino_healthy_deps
and networks_ok
and uses_env_defaults
and trino_props_ok
and sql_all_ok
)
return {
"docker_compose": {
"services": service_names,
"has_all_required_services": has_all_services,
"unpinned_images": unpinned_images,
"all_healthchecks_present": all_healthchecks_ok,
"trino_depends_on_healthy": trino_healthy_deps,
"isolated_lakehouse_net": networks_ok,
"uses_env_default_credentials": uses_env_defaults,
},
"trino_delta_catalog": {
"connector": props.get("connector.name", ""),
"metastore_uri": props.get("hive.metastore.uri", ""),
"s3_endpoint": props.get("s3.endpoint", ""),
"vacuum_min_retention": props.get("delta.vacuum.min-retention", ""),
"valid": trino_props_ok,
},
"medallion_sql": {
"has_bronze_silver_gold_schemas": sql_has_schemas,
"has_silver_window_deduplication": sql_has_dedup,
"has_gold_revenue_mart": sql_has_gold_mart,
"has_optimize_maintenance": sql_has_optimize,
"valid": sql_all_ok,
},
"all_infra_checks_passed": all_passed,
}
"""CLI runner for Track 2 Lab 07 (`lakehouse_storage_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 lakehouse_storage_lab.delta_medallion import run_delta_medallion_pipeline # noqa: E402
from lakehouse_storage_lab.iceberg_occ_sim import ( # noqa: E402
run_iceberg_manifest_pruning_sim,
run_occ_conflict_matrix,
run_zorder_vs_liquid_clustering_benchmark,
)
from lakehouse_storage_lab.infra_audit import audit_lakehouse_infrastructure # noqa: E402
from lakehouse_storage_lab.parquet_engine import ( # noqa: E402
benchmark_csv_vs_parquet,
benchmark_parquet_zone_map_pruning,
generate_order_events,
summarize_order_batch,
)
from lakehouse_storage_lab.query_engines import benchmark_duckdb_vs_polars # noqa: E402
def build_workbench_panels(
csv_pq: dict[str, Any],
zonemap: dict[str, Any],
delta: dict[str, Any],
engines: dict[str, Any],
iceberg: dict[str, Any],
occ: dict[str, Any],
zorder_liquid: dict[str, Any],
infra: dict[str, Any],
) -> dict[str, Any]:
"""Assemble standardized 6-KPI, 4-Bar, 4-Table workbench payload for the web platform."""
cv = delta["compaction_and_vacuum"]
wa = zorder_liquid["write_amplification_5_rounds"]
u_zm = zonemap["unsorted"]
s_zm = zonemap["sorted"]
trino_cat = infra["trino_delta_catalog"]
kpis = [
{
"id": "kpi_csv_vs_parquet_compression",
"label": "CSV vs Parquet (Zstd + Dictionary/RLE)",
"value": f"{csv_pq['compression_ratio_zstd']}x smaller",
"unit": f"{csv_pq['read_speedup_zstd_x']}x faster read",
"status": "ok",
"detail": (
f"50k rows: CSV {csv_pq['csv_bytes']:,} B -> Parquet Zstd "
f"{csv_pq['parquet_zstd_bytes']:,} B; 2/10 col pruning saved "
f"{csv_pq['column_pruning_io_saved_pct']}% I/O."
),
},
{
"id": "kpi_zonemap_rowgroup_skip",
"label": "Parquet Zone-Map Row-Group Skipping",
"value": f"{u_zm['skip_pct']}% -> {s_zm['skip_pct']}%",
"unit": f"{zonemap['row_group_reduction_x']}x fewer RGs",
"status": "ok",
"detail": (
f"Predicate {zonemap['predicate']}: unsorted scanned "
f"{u_zm['scanned_row_groups']}/{u_zm['num_row_groups']} RGs "
f"vs sorted {s_zm['scanned_row_groups']}/{s_zm['num_row_groups']}."
),
},
{
"id": "kpi_delta_medallion_timetravel",
"label": "Delta Lake ACID, Schema Merge & Time Travel",
"value": (
f"v0={delta['bronze']['time_travel_v0_rows']} "
f"-> v1={delta['bronze']['v1_rows']}"
),
"unit": "Schema Guard PASS",
"status": "ok",
"detail": (
f"Rejected bad schema ({delta['bronze']['schema_error_type']}); "
f"merged loyalty_tier; Silver cleaned "
f"{delta['silver']['duplicates_and_bad_filtered']} dup/bad rows."
),
},
{
"id": "kpi_delta_compaction_vacuum",
"label": "Delta Small-File Compaction & VACUUM Guard",
"value": f"{cv['active_files_before_compact']} -> {cv['active_files_after_compact']} files",
"unit": f"{cv['file_reduction_x']}x file drop",
"status": "ok",
"detail": (
f"optimize.compact() preserved 100% rows; vacuum dry-run found "
f"{cv['vacuum_dry_run_stale_files']} stale files; 0h blocked vs 172h SAFE."
),
},
{
"id": "kpi_duckdb_polars_parity",
"label": "DuckDB 2.x SQL vs Polars 2.x Lazy Parity",
"value": f"{engines['duckdb_median_ms']} ms / {engines['polars_median_ms']} ms",
"unit": f"100% parity ({engines['groups_returned']} groups)",
"status": "ok",
"detail": (
f"Exact match across {engines['filtered_order_count']:,} Silver orders "
f"({engines['filtered_gross_revenue_usd']:,.2f} USD, "
f"max diff {engines['max_revenue_diff_usd']} USD)."
),
},
{
"id": "kpi_iceberg_liquid_infra",
"label": "Iceberg Pruning, Liquid WA & Trino Infra",
"value": f"{iceberg['data_file_skip_pct']}% skip | WA {wa['liquid_wa']}x",
"unit": "5/5 Infra PASS",
"status": "ok",
"detail": (
f"Hidden partitioning skipped {iceberg['data_files_skipped']}/"
f"{iceberg['total_data_files']} files; Liquid WA {wa['liquid_wa']}x "
f"vs Z-Order {wa['zorder_wa']}x; Compose/Trino/SQL PASS."
),
},
]
bars = [
{
"id": "bar_storage_size_kb",
"title": "50,000 Order Events On-Disk Size (KB): CSV vs Parquet Snappy vs Zstd",
"metric_label": "File Size (KB)",
"items": [
{
"label": "parquet_zstd_dict_rle",
"value": round(csv_pq["parquet_zstd_bytes"] / 1024.0, 1),
"display": (
f"{round(csv_pq['parquet_zstd_bytes'] / 1024.0, 1)} KB "
f"({csv_pq['compression_ratio_zstd']}x smaller)"
),
"css_class": "is-fast",
},
{
"label": "parquet_snappy_dict_rle",
"value": round(csv_pq["parquet_snappy_bytes"] / 1024.0, 1),
"display": (
f"{round(csv_pq['parquet_snappy_bytes'] / 1024.0, 1)} KB "
f"({csv_pq['compression_ratio_snappy']}x smaller)"
),
"css_class": "is-mid",
},
{
"label": "raw_uncompressed_csv",
"value": round(csv_pq["csv_bytes"] / 1024.0, 1),
"display": f"{round(csv_pq['csv_bytes'] / 1024.0, 1)} KB (baseline 1.0x)",
"css_class": "is-slow",
},
],
},
{
"id": "bar_rowgroup_skipping_pct",
"title": "Parquet Row-Group Zone-Map Skipping (%): Unsorted vs Sorted by Filter Key",
"metric_label": "Row Groups Skipped (%)",
"items": [
{
"label": "sorted_parquet_zonemap",
"value": s_zm["skip_pct"],
"display": (
f"{s_zm['skip_pct']}% "
f"({s_zm['scanned_row_groups']}/{s_zm['num_row_groups']} RGs read)"
),
"css_class": "is-fast",
},
{
"label": "unsorted_parquet_zonemap",
"value": u_zm["skip_pct"],
"display": (
f"{u_zm['skip_pct']}% "
f"({u_zm['scanned_row_groups']}/{u_zm['num_row_groups']} RGs read)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_delta_compaction_files",
"title": "Delta Lake Compaction: Active Parquet Files Before vs After optimize.compact()",
"metric_label": "Active Parquet Files",
"items": [
{
"label": "after_delta_optimize_compact",
"value": cv["active_files_after_compact"],
"display": (
f"{cv['active_files_after_compact']} file "
f"({cv['file_reduction_x']}x reduction)"
),
"css_class": "is-fast",
},
{
"label": "before_small_file_bloat",
"value": cv["active_files_before_compact"],
"display": (
f"{cv['active_files_before_compact']} small files "
"(metadata/IOPS bloat)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_write_amplification_zorder_vs_liquid",
"title": "5-Round Incremental Write Amplification (WA): Liquid Clustering vs Z-Order",
"metric_label": "Write Amplification Factor (x)",
"items": [
{
"label": "liquid_clustering_incremental",
"value": wa["liquid_wa"],
"display": f"{wa['liquid_wa']}x ({wa['liquid_rewritten_mb']} MB rewritten)",
"css_class": "is-fast",
},
{
"label": "classic_zorder_full_partition",
"value": wa["zorder_wa"],
"display": f"{wa['zorder_wa']}x ({wa['zorder_rewritten_mb']} MB rewritten)",
"css_class": "is-slow",
},
],
},
]
tables = [
{
"id": "table_delta_medallion_layers",
"title": "Real Delta Lake Multi-Hop Medallion Execution (Bronze -> Silver -> Gold)",
"columns": ["layer", "rows", "active_files", "key_invariant", "status"],
"rows": [
[
"Bronze v0 (Raw Append)",
str(delta["bronze"]["v0_rows"]),
"1",
f"Schema Enforcement rejected ({delta['bronze']['schema_error_type']})",
"PASS",
],
[
"Bronze v1 (Schema Merge)",
str(delta["bronze"]["v1_rows"]),
"2",
"Added loyalty_tier; Time Travel v0 preserved without loyalty_tier",
"PASS",
],
[
"Silver (Deduplicated Clean)",
str(delta["silver"]["rows"]),
str(delta["silver"]["active_files"]),
f"Filtered {delta['silver']['duplicates_and_bad_filtered']} dup/bad rows",
"PASS",
],
[
"Gold (Revenue Mart)",
str(delta["gold"]["rows"]),
str(delta["gold"]["active_files"]),
f"Revenue {delta['gold']['total_revenue_usd']:,.2f} USD matches Silver",
"PASS" if delta["gold"]["revenue_parity_with_silver_ok"] else "FAIL",
],
],
},
{
"id": "table_occ_and_vacuum_safety",
"title": "Optimistic Concurrency Control (OCC) Matrix & VACUUM Retention Guard",
"columns": ["scenario", "mechanism", "outcome", "retry_or_risk"],
"rows": [
[
"Append + Append",
"WriteSerializable OCC",
occ["append_vs_append"]["status"],
f"retry={occ['append_vs_append']['retry_required']}",
],
[
"Delete + Overwrite (Same File)",
"WriteSerializable OCC",
occ["delete_vs_overwrite_same_file"]["status"],
f"retry={occ['delete_vs_overwrite_same_file']['retry_required']}",
],
[
"Append + Update (Scanned Range)",
"Serializable OCC",
occ["append_vs_serializable_update"]["status"],
f"retry={occ['append_vs_serializable_update']['retry_required']}",
],
[
"VACUUM 0h vs 172h (SLA 168h)",
"Retention Inequality Guard",
(
f"0h={cv['vacuum_guard_0h']['is_safe']} | "
f"172h={cv['vacuum_guard_172h']['is_safe']}"
),
cv["vacuum_guard_0h"]["risk_classification"],
],
],
},
{
"id": "table_2d_layout_comparison",
"title": "Physical Data Layout: 2D Box Skipping, Col-2 Skipping & Write Amplification",
"columns": ["layout_strategy", "box_2d_skip_pct", "col2_only_skip_pct", "wa_5_rounds"],
"rows": [
[
"Unsorted Raw Files",
f"{zorder_liquid['unsorted_2d']['skip_pct']}%",
"0.0%",
"1.0x (no optimize)",
],
[
"Lexicographical Sort (x, y)",
f"{zorder_liquid['lex_sort_2d']['skip_pct']}%",
f"{zorder_liquid['col2_only_skip_pct']['lex_sort']}%",
f"{wa['zorder_wa']}x (full rewrite)",
],
[
"Z-Ordering (Morton Curve)",
f"{zorder_liquid['zorder_2d']['skip_pct']}%",
f"{zorder_liquid['col2_only_skip_pct']['zorder']}%",
f"{wa['zorder_wa']}x (full rewrite)",
],
[
"Liquid Clustering (Incremental)",
f"{zorder_liquid['liquid_clustering_2d']['skip_pct']}%",
f"{zorder_liquid['col2_only_skip_pct']['liquid_clustering']}%",
f"{wa['liquid_wa']}x ({wa['wa_reduction_x']}x lower WA)",
],
],
},
{
"id": "table_infra_static_audit",
"title": "Deployable Lakehouse Infrastructure Audit (MinIO, Hive Metastore, Trino, SQL)",
"columns": ["artifact", "verified_components", "security_and_sla", "audit_status"],
"rows": [
[
"docker-compose.yml",
", ".join(infra["docker_compose"]["services"]),
f"pinned=True, healthy={infra['docker_compose']['trino_depends_on_healthy']}",
"PASS" if infra["docker_compose"]["has_all_required_services"] else "FAIL",
],
[
"configs/trino_delta_catalog.properties",
f"connector={trino_cat['connector']}, s3={trino_cat['s3_endpoint']}",
f"vacuum_min={trino_cat['vacuum_min_retention']}, env_secrets=True",
"PASS" if trino_cat["valid"] else "FAIL",
],
[
"sql/01_medallion_trino.sql",
"bronze/silver/gold schemas + ROW_NUMBER dedup + daily_revenue_mart",
f"optimize_proc={infra['medallion_sql']['has_optimize_maintenance']}",
"PASS" if infra["medallion_sql"]["valid"] else "FAIL",
],
],
},
]
return {"kpis": kpis, "bars": bars, "tables": tables}
def run_all_benchmarks(num_rows: int = 50_000, seed: int = 42) -> dict[str, Any]:
"""Run all Lab 07 benchmarks cleanly inside a temp directory (zero leftover Parquet files)."""
raw_table = generate_order_events(num_rows=num_rows, seed=seed)
batch_summary = summarize_order_batch(raw_table).model_dump()
with tempfile.TemporaryDirectory(prefix="fsds_lab07_") as tmp:
tmp_path = Path(tmp)
csv_pq = benchmark_csv_vs_parquet(raw_table, tmp_path / "parquet_bench")
zonemap = benchmark_parquet_zone_map_pruning(raw_table, tmp_path / "zonemap_bench")
delta = run_delta_medallion_pipeline(
tmp_path / "delta_lakehouse", raw_table, small_file_batches=12
)
engines = benchmark_duckdb_vs_polars(
Path(delta["silver_path"]), tmp_path / "engine_parquet"
)
delta_clean = {
k: v for k, v in delta.items() if k not in ("bronze_path", "silver_path", "gold_path")
}
iceberg = run_iceberg_manifest_pruning_sim()
occ = run_occ_conflict_matrix()
zorder_liquid = run_zorder_vs_liquid_clustering_benchmark(seed=seed)
infra = audit_lakehouse_infrastructure(LAB_ROOT)
panels = build_workbench_panels(
csv_pq=csv_pq,
zonemap=zonemap,
delta=delta_clean,
engines=engines,
iceberg=iceberg,
occ=occ,
zorder_liquid=zorder_liquid,
infra=infra,
)
return {
"config": {
"lab_root": "lab-07-open-lakehouse-delta-iceberg-trino",
"num_rows": num_rows,
"seed": seed,
"docker_daemon_required": False,
},
"dataset_summary": batch_summary,
"csv_vs_parquet": csv_pq,
"parquet_zone_map_pruning": zonemap,
"delta_medallion": delta_clean,
"duckdb_vs_polars": engines,
"iceberg_manifest_pruning": iceberg,
"occ_conflict_matrix": occ,
"zorder_vs_liquid_clustering": zorder_liquid,
"infrastructure_audit": infra,
"workbench_panels": panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 07 Open Lakehouse benchmarks.")
parser.add_argument(
"--rows",
type=int,
default=50_000,
help="Number of synthetic e-commerce order rows to generate (default: 50000).",
)
parser.add_argument(
"--output",
type=Path,
default=LAB_ROOT / "artifacts" / "t2_ch08_lab07_results.json",
help="Path to write JSON benchmark artifact.",
)
args = parser.parse_args()
results = run_all_benchmarks(num_rows=args.rows, seed=42)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(results, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
print(f"[Lab 07] Wrote verified Lakehouse benchmark artifact -> {args.output}")
if __name__ == "__main__":
main()
"""16-test offline verification suite for FSDS-SOTA-2026 Track 2 Lab 07 (`lakehouse_storage_lab`)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
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 lakehouse_storage_lab.delta_medallion import ( # noqa: E402
run_delta_medallion_pipeline,
validate_vacuum_retention_safety,
)
from lakehouse_storage_lab.iceberg_occ_sim import ( # noqa: E402
morton_zorder_2d,
run_iceberg_manifest_pruning_sim,
run_occ_conflict_matrix,
run_zorder_vs_liquid_clustering_benchmark,
)
from lakehouse_storage_lab.infra_audit import audit_lakehouse_infrastructure # noqa: E402
from lakehouse_storage_lab.parquet_engine import ( # noqa: E402
benchmark_csv_vs_parquet,
benchmark_parquet_zone_map_pruning,
generate_order_events,
summarize_order_batch,
)
from lakehouse_storage_lab.query_engines import benchmark_duckdb_vs_polars # noqa: E402
# Security-only AST guard banning unsafe deserialization libraries; SOTA Lakehouse libraries allowed.
FORBIDDEN_RUNTIME_IMPORTS = frozenset(
{
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
)
def test_01_ast_forbids_unsafe_deserializers() -> None:
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 6
violations: list[str] = []
for pf in py_files:
tree = ast.parse(pf.read_text(encoding="utf-8"), filename=str(pf))
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_RUNTIME_IMPORTS:
violations.append(f"{pf.name}:{root}")
elif isinstance(node, ast.ImportFrom) and node.module:
root = node.module.split(".")[0]
if root in FORBIDDEN_RUNTIME_IMPORTS:
violations.append(f"{pf.name}:{root}")
assert violations == []
def test_02_deterministic_order_generator_and_quality_metrics() -> None:
t1 = generate_order_events(num_rows=4_000, duplicate_rate=0.05, invalid_rate=0.02, seed=42)
t2 = generate_order_events(num_rows=4_000, duplicate_rate=0.05, invalid_rate=0.02, seed=42)
assert t1.equals(t2)
summary = summarize_order_batch(t1)
assert summary.total_rows == 4_000
assert summary.duplicate_rows == 200
assert summary.invalid_amount_rows == 80
assert summary.cancelled_rows > 0
assert summary.valid_unique_rows < summary.unique_order_ids
def test_03_csv_vs_parquet_compression_and_column_pruning(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=10_000, seed=42)
res = benchmark_csv_vs_parquet(tbl, tmp_path / "bench", row_group_size=2_500)
assert res["compression_ratio_snappy"] > 2.0
assert res["compression_ratio_zstd"] > res["compression_ratio_snappy"]
assert res["parquet_zstd_bytes"] < res["parquet_snappy_bytes"] < res["csv_bytes"]
assert res["column_pruning_io_saved_pct"] > 60.0
assert res["apac_sum_parity_ok"] is True
def test_04_parquet_zonemap_minmax_rowgroup_skipping(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=20_000, seed=42)
res = benchmark_parquet_zone_map_pruning(
tbl, tmp_path / "zm", filter_day_low=52, filter_day_high=56, row_group_size=1_000
)
assert res["result_parity_ok"] is True
assert res["matched_rows"] > 0
assert res["unsorted"]["skip_ratio"] == 0.0
assert res["sorted"]["skip_ratio"] >= 0.75
assert res["sorted"]["scanned_row_groups"] < res["unsorted"]["scanned_row_groups"]
assert res["row_group_reduction_x"] >= 4.0
def test_05_delta_bronze_schema_enforcement_and_merge_evolution(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=2_000, seed=42)
res = run_delta_medallion_pipeline(tmp_path / "delta", tbl, small_file_batches=6)
bronze = res["bronze"]
assert bronze["schema_enforced_rejected"] is True
assert bronze["schema_error_type"] != ""
assert bronze["time_travel_v0_has_loyalty_tier"] is False
assert bronze["time_travel_v1_has_loyalty_tier"] is True
assert bronze["v1_rows"] == bronze["v0_rows"] + 3
def test_06_delta_silver_deduplication_and_gold_revenue_parity(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=3_000, duplicate_rate=0.06, invalid_rate=0.02, seed=7)
res = run_delta_medallion_pipeline(tmp_path / "delta_sg", tbl, small_file_batches=6)
assert res["silver"]["duplicates_and_bad_filtered"] > 180
assert res["silver"]["rows"] < res["bronze"]["v1_rows"]
assert res["gold"]["rows"] > 0
assert res["gold"]["revenue_parity_with_silver_ok"] is True
def test_07_delta_time_travel_and_transaction_log_json_audit(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=1_500, seed=42)
res = run_delta_medallion_pipeline(tmp_path / "delta_tt", tbl, small_file_batches=6)
bronze = res["bronze"]
assert bronze["time_travel_v0_rows"] == 1_500
assert bronze["v1_rows"] == 1_503
log_audit = bronze["delta_log_audit"]
assert log_audit["commit_json_count"] == 2
assert log_audit["action_counts"]["protocol"] >= 1
assert log_audit["action_counts"]["metaData"] >= 2
assert log_audit["action_counts"]["add"] >= 2
def test_08_delta_small_file_bloat_and_real_optimize_compact(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=2_400, seed=42)
res = run_delta_medallion_pipeline(tmp_path / "delta_opt", tbl, small_file_batches=12)
cv = res["compaction_and_vacuum"]
assert cv["active_files_before_compact"] == 12
assert cv["active_files_after_compact"] == 1
assert cv["file_reduction_x"] == 12.0
assert cv["rows_preserved_ok"] is True
assert cv["num_files_removed"] == 12
assert cv["num_files_added"] == 1
assert cv["delta_log_removes"] >= 12
def test_09_delta_vacuum_dry_run_and_retention_safety_guard(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=1_500, seed=42)
res = run_delta_medallion_pipeline(tmp_path / "delta_vac", tbl, small_file_batches=8)
cv = res["compaction_and_vacuum"]
assert cv["vacuum_dry_run_stale_files"] == 8
assert cv["vacuum_guard_0h"]["is_safe"] is False
assert cv["vacuum_guard_0h"]["risk_classification"] == "CRITICAL_CONCURRENT_READER_FILE_NOT_FOUND"
assert cv["vacuum_guard_172h"]["is_safe"] is True
assert cv["vacuum_guard_172h"]["risk_classification"] == "SAFE"
mid_guard = validate_vacuum_retention_safety(
retention_hours=24.0,
max_concurrent_query_hours=4.0,
time_travel_sla_hours=168.0,
)
assert mid_guard["is_safe"] is False
assert mid_guard["risk_classification"] == "VIOLATES_TIME_TRAVEL_SLA"
def test_10_duckdb_vs_polars_exact_olap_kpi_parity(tmp_path: Path) -> None:
tbl = generate_order_events(num_rows=8_000, seed=42)
delta_res = run_delta_medallion_pipeline(tmp_path / "delta_q", tbl, small_file_batches=4)
eng = benchmark_duckdb_vs_polars(
Path(delta_res["silver_path"]), tmp_path / "pq_export", repeats=2
)
assert eng["exact_kpi_parity"] is True
assert eng["max_revenue_diff_usd"] <= 0.01
assert eng["groups_returned"] == 12 # 2 regions (APAC, EMEA) x 6 categories
assert eng["arrow_zero_copy_rows"] == eng["silver_total_rows"]
assert eng["filtered_order_count"] > 0
def test_11_iceberg_three_tier_manifest_pruning_and_hidden_partitioning() -> None:
res = run_iceberg_manifest_pruning_sim(
num_days=60,
manifests_per_month=2,
files_per_day=4,
query_day_start=45,
query_day_end=47,
query_region=2,
)
assert res["total_manifests"] == 4
assert res["manifests_pruned"] == 3
assert res["manifests_scanned"] == 1
assert res["total_data_files"] == 240
assert res["data_files_scanned"] == 3
assert res["data_file_skip_pct"] == 98.75
assert res["iceberg_vs_hive_trap_speedup_x"] == 80.0
def test_12_occ_conflict_matrix_append_delete_overwrite_isolation() -> None:
occ = run_occ_conflict_matrix()
assert occ["append_vs_append"]["status"] == "AUTO_REBASED_COMMIT"
assert occ["append_vs_append"]["conflict_detected"] is False
assert occ["delete_vs_overwrite_same_file"]["status"] == "CONFLICT_RETRY_REQUIRED"
assert occ["delete_vs_overwrite_same_file"]["retry_required"] is True
assert occ["append_vs_serializable_update"]["status"] == "CONFLICT_RETRY_REQUIRED"
assert occ["delete_vs_disjoint_delete"]["status"] == "AUTO_REBASED_COMMIT"
def test_13_morton_zorder_bit_interleaving_invariants() -> None:
# Exact bit-interleaving checks: x in even bits, y in odd bits
assert morton_zorder_2d(0, 0) == 0
assert morton_zorder_2d(1, 0) == 0b01
assert morton_zorder_2d(0, 1) == 0b10
assert morton_zorder_2d(1, 1) == 0b11
assert morton_zorder_2d(0b101, 0b011) == 0b011011
# Injectivity across 32x32 grid
keys = {morton_zorder_2d(x, y, bits=8) for x in range(32) for y in range(32)}
assert len(keys) == 1024
def test_14_zorder_vs_liquid_clustering_skipping_and_write_amplification() -> None:
res = run_zorder_vs_liquid_clustering_benchmark(num_points=8_192, num_files=64, seed=42)
assert res["unsorted_2d"]["skip_pct"] == 0.0
assert res["zorder_2d"]["skip_pct"] >= 85.0
assert res["liquid_clustering_2d"]["skip_pct"] >= 90.0
# Lexicographical sort collapses on secondary column y-only queries while Z-Order/Liquid skip well
assert res["col2_only_skip_pct"]["lex_sort"] < 5.0
assert res["col2_only_skip_pct"]["zorder"] >= 75.0
assert res["col2_only_skip_pct"]["liquid_clustering"] >= 80.0
# Liquid Clustering slashes compaction write amplification vs full-partition Z-Order
wa = res["write_amplification_5_rounds"]
assert wa["liquid_wa"] < wa["zorder_wa"]
assert wa["wa_reduction_x"] >= 3.0
def test_15_static_infrastructure_audit_compose_trino_sql() -> None:
audit = audit_lakehouse_infrastructure(LAB_ROOT)
assert audit["all_infra_checks_passed"] is True
assert audit["docker_compose"]["unpinned_images"] == []
assert audit["docker_compose"]["trino_depends_on_healthy"] is True
assert audit["trino_delta_catalog"]["valid"] is True
assert audit["medallion_sql"]["valid"] is True
def test_16_cli_runner_and_workbench_artifact_schema(tmp_path: Path) -> None:
out_file = tmp_path / "lab07_smoke.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--rows",
"5000",
"--output",
str(out_file),
],
capture_output=True,
text=True,
check=True,
)
assert "Wrote verified Lakehouse benchmark artifact" in proc.stdout
data = json.loads(out_file.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
assert data["infrastructure_audit"]["all_infra_checks_passed"] is True
assert data["duckdb_vs_polars"]["exact_kpi_parity"] is True
S3/MinIO/GCS), vì sao bài toán tệp nhỏ (Small-File Problem, ví dụ ghi hàng nghìn tệp 0.5 MB) làm tụt mạnh thông lượng đọc theo phương trình \(B_{\text{eff}}(S) = \frac{S}{t_{\text{req}} + S / B}\) và thiếu lệnh rename() thư mục nguyên tử?0.5 MB chỉ đạt ~17.2 MB/s (13.8% băng thông), trong khi gom compaction về 128–256 MB đẩy băng thông hiệu dụng lên 98.8% và cắt mạnh số lần gọi LIST/GET.
50,000 đơn hàng của Lab 07 (parquet_engine.py), vì sao Parquet Zstd nhỏ hơn CSV 3.47x, cắt tỉa 2/10 cột tiết kiệm 75.28% I/O, và sắp xếp theo day_offset nâng tỷ lệ bỏ qua Row Group từ 0.0% lên 85.0%?test_03 và test_04 (artifacts/t2_ch08_lab07_results.json): CSV 3,381,970 B \(\to\) Parquet Zstd 974,275 B (3.47x), đọc 2/10 cột tiết kiệm 75.28% I/O; với vị từ day_offset BETWEEN 52 AND 56, unsorted quét 20/20 RG (0.0%) còn sorted chỉ quét 3/20 RG (85.0% skip, 6.67x ít hơn).
Delta Lake thật của Lab 07 (delta_medallion.py), cơ chế Schema Enforcement, Schema Evolution (schema_mode="merge") và kiến trúc Medallion (Bronze -> Silver -> Gold) bảo vệ Lakehouse khỏi biến thành Data Swamp như thế nào?deltalake==1.6.6 tại Tests 05, 06, 07: lô dữ liệu có unexpected_corrupt_col bị chặn bằng SchemaMismatchError; DeltaTable(path, version=0) giữ đúng 50,000 dòng không chứa loyalty_tier; và Gold khớp Silver ở 3,395,566.59 USD.
Delta Lake và Apache Iceberg, vì sao Hidden Partitioning (days(event_ts)) của Iceberg nhanh hơn 80.0x so với bẫy phân vùng Hive cổ điển trong Lab 07?test_11 (run_iceberg_manifest_pruning_sim): Iceberg loại 75.0% Manifest ngay ở tầng Manifest List và cắt tỉa 98.75% tệp dữ liệu (3/240 đọc so với 240/240 của bẫy Hive \(\Rightarrow 80.0\times\)). Trong năm 2026, Delta UniForm và Apache XTable cho phép đồng bộ siêu dữ liệu giữa hai định dạng mà không nhân đôi tệp Parquet.
v10. Theo quy tắc Optimistic Concurrency Control (OCC) trong Lab 07 (run_occ_conflict_matrix), kết quả nào sau đây ĐÚNG?test_12: append_vs_append và delete_vs_disjoint_delete trả AUTO_REBASED_COMMIT (retry_required=False), trong khi delete_vs_overwrite_same_file và append_vs_serializable_update trả CONFLICT_RETRY_REQUIRED (conflict_detected=True).
OPTIMIZE và VACUUM?test_08 và test_09: dt.optimize.compact() giảm 12 -> 1 tệp (12.0x) tạo 12 action remove; vacuum(dry_run=True) phát hiện đúng 12 tệp cũ; bộ kiểm định validate_vacuum_retention_safety đánh dấu 0h là CRITICAL, 24h là VIOLATES_TIME_TRAVEL_SLA, và 172h >= 169h là SAFE.
(x, y) và liên tục nạp lô dữ liệu mới (+15% qua 5 vòng) trong Lab 07 (iceberg_occ_sim.py), vì sao Liquid Clustering vượt trội hơn cả Lexicographical Sort lẫn Z-Ordering cổ điển?test_13 và test_14: morton_zorder_2d(0b101, 0b011) == 0b011011; lọc riêng cột 2 cho kết quả Lex Sort 0.0% vs Z-Order/Liquid 79.69%; sau 5 vòng nạp gia tăng (1,750 MB), Write Amplification giảm từ 5.14x (Z-Order) xuống 1.54x (Liquid Clustering, 3.34x thấp hơn).
Trino, Polaris/Unity, DuckDB 2.x, Polars 2.x), vai trò phân bổ nào sau đây ĐÚNG?test_10 và test_15: DuckDB 2.0.1 và Polars 2.1.0 trả về khớp 100% 12 nhóm (12,443 đơn, 1,477,312.45 USD, max_revenue_diff_usd = 0.0) trong vài mili-giây; trong khi hạ tầng docker-compose.yml + trino_delta_catalog.properties + 01_medallion_trino.sql đạt kiểm toán all_infra_checks_passed=True.
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 — Toán học Object Storage, Small-File Roofline & Nén Parquet (Zstd + Column Pruning)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết lại phương trình \(B_{\text{eff}}(S) = S / (t_{\text{req}} + S / B)\) với \(B=125\text{ MB/s}, t_{\text{req}}=25\text{ ms}\), tính tỷ lệ băng thông ở \(S=0.5\text{ MB}\) vs \(256\text{ MB}\), và nêu cơ chế Dictionary + RLE + Delta của Parquet.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi benchmark_csv_vs_parquet trong src/lakehouse_storage_lab/parquet_engine.py và chạy pytest -k test_03 -v.
Tiêu chí Đáp án & Số đối chứng
Tệp 0.5 MB chỉ đạt 17.2 MB/s (13.8% băng thông) so với 123.5 MB/s (98.8%) ở 256 MB; trên 50,000 đơn hàng, Parquet Zstd đạt 3.47x nén (3,381,970 B -> 974,275 B), đọc nhanh hơn 7.45x, và cắt tỉa 2/10 cột tiết kiệm 75.28% I/O.
Bài tập 2 — Kiểm chứng Parquet Zone Maps Min/Max Row-Group Skipping & Bloom Filters
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Trình bày điều kiện bỏ qua Row Group \(\max_g < a \lor \min_g > b\), giải thích vì sao dữ liệu không sắp xếp làm mọi Row Group mang biên độ [0, 59], và nêu trường hợp cần Split-Block Bloom Filter.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi benchmark_parquet_zone_map_pruning và kiểm tra thống kê thực tế từ pyarrow.parquet.ParquetFile.metadata qua pytest -k test_04 -v.
Tiêu chí Đáp án & Số đối chứng
Với day_offset BETWEEN 52 AND 56 (20 RGs), unsorted quét 20/20 RG (0.0% skip), còn sorted chỉ quét 3/20 RG (85.0% skip, giảm 6.67x) và trả đúng 4,182 dòng; với cột định danh order_id phân bố đều, cần Split-Block Bloom Filter.
Bài tập 3 — Pipeline Delta Lake Medallion (Bronze -> Silver -> Gold), Schema Evolution & Time Travel
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra cơ chế SchemaMismatchError khi chèn cột lạ, sự khác biệt giữa version=0 và version=1 sau schema_mode="merge", và cấu trúc actions trong _delta_log/0000000000000000000*.json.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_delta_medallion_pipeline và inspect_delta_log trong src/lakehouse_storage_lab/delta_medallion.py, xác minh bằng pytest -k "test_05 or test_06 or test_07" -v.
Tiêu chí Đáp án & Số đối chứng
Lô sai bị chặn bằng SchemaMismatchError; v0=50,000 dòng (không có loyalty_tier) và v1=50,003 dòng (có loyalty_tier); _delta_log ghi 2 tệp JSON (protocol=1, metaData=2, add=2); Silver lọc 11,534 dòng lỗi/trùng còn 38,469 dòng, Gold khớp 3,395,566.59 USD.
Bài tập 4 — OPTIMIZE Compaction, Bất đẳng thức An toàn VACUUM & Ma trận Xung đột OCC
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân biệt xóa logic remove trong _delta_log với xóa vật lý VACUUM; áp dụng \(T_{\text{retention}} \ge \max(T_{\text{query\_max}}, T_{\text{time\_travel\_SLA}}) + \delta_{\text{clock}}\); và phân tích WriteSerializable vs Serializable.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra validate_vacuum_retention_safety và run_occ_conflict_matrix bằng pytest -k "test_08 or test_09 or test_12" -v.
Tiêu chí Đáp án & Số đối chứng
optimize.compact() gom 12 -> 1 tệp (12.0x), vacuum(dry_run=True) phát hiện 12 tệp cũ; ngưỡng an toàn là 169.0h (0h -> CRITICAL, 172h -> SAFE); OCC tự rebase Append+Append & Disjoint Delete, yêu cầu retry với Delete+Overwrite cùng tệp và Serializable Append+Update.
Bài tập 5 — Apache Iceberg Hidden Partitioning, Đường cong Morton Z-Order vs. Liquid Clustering
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính thủ công morton_zorder_2d(0b101, 0b011) theo công thức đan xen bit \(Z(x,y)\); so sánh tỷ lệ bỏ qua cột 2 (y) giữa Lex Sort vs Z-Order/Liquid; và tính hệ số khuếch đại ghi \(\text{WA} = 1 + B_{\text{rewritten}}/B_{\text{initial}}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy run_iceberg_manifest_pruning_sim và run_zorder_vs_liquid_clustering_benchmark, kiểm chứng qua pytest -k "test_11 or test_13 or test_14" -v.
Tiêu chí Đáp án & Số đối chứng
morton_zorder_2d(5, 3) == 27 (0b011011); Iceberg Hidden Partitioning cắt tỉa 98.75% tệp (80.0x vs Hive); lọc riêng cột 2: Lex Sort 0.0% vs Z-Order/Liquid 79.69%; Liquid Clustering đạt 93.75% skip 2D và hạ WA từ 5.14x xuống 1.54x (3.34x thấp hơn).
Bài tập 6 — Đối chiếu DuckDB 2.x vs. Polars 2.x, Kiểm toán Hạ tầng MinIO/HMS/Trino & Cổng 16/16 pytest
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra cách DuckDB đọc trực tiếp PyArrow Table (zero-copy) và read_parquet so với Polars.scan_parquet; đối chiếu 5 dịch vụ trong docker-compose.yml, cấu hình trino_delta_catalog.properties và 01_medallion_trino.sql.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy ruff check src tests scripts, mypy src, python scripts/run_lab_demo.py --output artifacts/t2_ch08_lab07_results.json, và pytest -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
DuckDB và Polars khớp 0.0 USD sai lệch trên 12 nhóm (12,443 đơn, 1,477,312.45 USD); kiểm toán hạ tầng Compose/Trino/SQL đạt all_infra_checks_passed=True, ruff/mypy 0 lỗi và 16/16 pytest PASS (0 skip).