FSDS SOTA 2026 DSAI + EDAI Textbook
T2-P2-U06 Part 2 • Engineering for Data & AI (EDAI) ~41 phút đọc (8,545 từ) 3 Simulators • 3 Diagrams

Chương 12 — Điều phối Đường ống Dữ liệu (Apache Airflow 3.x: Tính Bất biến, logical_date Backfill, Task Execution API, Deferrable Triggerer), Hợp đồng Dữ liệu (ODCS v3.1.0, Iceberg WAP, Circuit Breaker) & Quản trị Phả hệ (DataHub v1.0+, RLS/DDM, Temporal)

Từ Airflow 3.0.1 Task SDK (airflow.sdk.Asset, Deadline Alerts, @task.short_circuit, DAG-level module instances), tái chạy/backfill bất biến (0.0% vs +100.0% double-count, logical_date 7/7 vs datetime.now() 0/7) & Deferrable Triggerer + ObjectStore XCom URI (100,079x gọn, 0/16 slots giữ) đến Hợp đồng ODCS v3.1.0 + Circuit Breaker chặn 4/4 lỗi (0% ô nhiễm Gold) & DataHub v1.0+ AST Column Lineage (100% PII kế thừa, 4 bảng hưởng tác động) — Tích hợp Mini Coursework Phần 2.

Unit ID: T2-P2-U06
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 (R34 & Milestone): Bài 12 Data Engineering — Orchestration & Governance Layers (Pipeline orchestration benefits, Beyond the cronjob: idempotency, backfill, dynamic pipelines, Airflow architecture, operators and data passing, Airflow administration & scaling: variables & connections, task concurrency, and monitoring, Fundamentals of data validation: circuit breaker pattern, validation frameworks and data contracts, Data governance, Lab: Deploy/administrate Airflow + multi-step pipeline with DataHub lineage + Milestone: Mini Coursework 1–2 weeks) trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành & Đề án Phần 2 (Lab 11 + Mini Coursework): labs/lab-11-airflow-datahub-governance-pipeline/README.md (orchestration_governance_lab)


Tình huống Mở đầu: Bốn Thảm họa Kinh điển Ở Tầng Điều phối & Quản trị Dữ liệu#

Sau khi dựng đường ống nhập luồng Kafka/Debezium (Chương 7), Lakehouse Iceberg/Delta (Chương 8), xử lý lô Spark và xử lý luồng Flink (Chương 9–10) cùng tầng tiêu thụ ClickHouse + Feast Feature Store (Chương 11), nhiều đội ngũ vội vàng ghép tất cả bằng vài tập lệnh crontab, viết nối bảng bằng INSERT INTO, truyền thẳng DataFrame qua bộ nhớ trung gian và bỏ qua kiểm định hợp đồng đầu vào. Dưới tải sản xuất thật, bốn thảm họa vận hành nghiêm trọng lập tức xảy ra:

  1. Ghi nối cron Không Lũy đẳng Nhân đôi Doanh thu Khi Chạy lại (+100.0% Drift Trên Phân vùng Retry): Trên tập thực nghiệm 7 ngày \(\times\) 400 đơn hàng (2,800 đơn, tổng doanh thu chuẩn 299,524.31 USD) của Lab 11 (test_03), khi một tác vụ ngày 2026-10-04 gặp sự cố mạng và chạy lại đúng 1 lần, kịch bản cron Append (INSERT INTO không dọn phân vùng) biến 400 đơn (43,290.30 USD) thành 800 đơn (86,580.60 USD — phình đúng +100.0%!); trải qua 4 lượt retry trong tuần, bảng đích phình lên 4,400 dòng (+1,600 bản ghi trùng, +173,570.66 USD = +57.95%). Ngược lại, mẫu Atomic Partition Overwrite (DELETE + INSERT / MERGE theo partition_dt) trên DuckDB 2.0 (hoặc zero-copy Iceberg Write–Audit–Publish branching) bảo toàn chính xác 2,800 dòng (0 trùng, 0.0 USD / 0.0% sai lệch).
  2. Dùng datetime.now() Thay Vì logical_date (data_interval_start) Phá Hủy 100% Backfill Lịch sử: Một kỹ sư chạy bù lịch sử 7 ngày (2026-10-01 đến 2026-10-07) vào ngày đồng hồ thực 2026-10-10, nhưng trong SQL/Python lại gọi datetime.now() để gắn nhãn ngày phân vùng. Kết quả đo tại Lab 11 (test_04): toàn bộ 7 phân vùng lịch sử đích đều trống rỗng (0 / 7 ngày có dữ liệu = 0.0% độ chính xác), trong khi phân vùng ngày chạy 2026-10-10 bị đổ đè 2,800 dòng trộn lẫn từ 7 ngày khác nhau! Trói chặt mọi phép đọc–ghi vào logical_date (ds) đạt độ chính xác 7 / 7 (100.0%), 0 dòng nhiễm chéo.
  3. Nhồi DataFrame Vào XCom Gây Sập Postgres (6.013 MB > 48 KB) & Cảm biến Đồng bộ Làm Tắc Nghẽn 100% Worker Pool: Đẩy thẳng một lô 50,000 đơn hàng qua cơ chế XCom mặc định của Airflow tạo ra gói JSON nặng 6,304,985 B (6.013 MB = 6,157.2 KB) — vượt trần khuyến nghị 48 KB của Metadata DB hơn 128x (test_05), làm nghẽn Task Execution API và PostgreSQL; đổi sang Object-Store URI Pointer (s3://lakehouse/..., 63 B) thu nhỏ dung lượng truyền XCom tới 100,079.1x. Song song, khi 48 tác vụ cảm biến đồng bộ (mode="poke") chờ 600s dữ liệu hạ cánh trên bể 16 worker slots (test_06), chúng chiếm cứng 16 / 16 (100.0%) worker slots, đẩy 32 tác vụ vào hàng đợi bế tắc và đốt 28,800 slot-giây vô ích; chuyển sang DeferrableOperator chạy trên Triggerer asyncio hạ số worker slot bị giam xuống 0 / 16 (0.0%) trong khi vẫn theo dõi đồng thời toàn bộ 48 sự kiện!
  4. Thiếu Hợp đồng Dữ liệu (ODCS v3.1.0 Circuit Breaker) & Phả hệ Cột DataHub v1.0+ Làm Nhiễm Độc Gold/Feast (8,000 Dòng Bẩn) & Rò rỉ PII: Tiêm 4 lỗi thực tế vào lô 2,000 đơn hàng (Schema Drift đánh mất cột amount_usd, 18 đơn âm < 0.01 USD, Null Spike 12.5% vượt ngưỡng 1.0%, và trễ độ tươi 47 phút > 30 phút, cộng thêm kiểm định chặn đơn lỗi > 500,000.0 USD): đường ống thiếu mạch ngắt đẩy trọn 8,000 / 8,000 (100.0%) dòng độc hại xuống tầng Gold ClickHouse và kho đặc trưng Feast! Ngược lại, ODCS v3.1.0 Data Contract Circuit Breaker (@task.short_circuit) bắt sạch 4 / 4 (100.0%) sự cố, cách ly toàn bộ vào bảng chết quarantine_orders_dead_letter và giữ bảng Gold ở 0 dòng ô nhiễm (0.0%); đồng thời đồ thị phả hệ cột DataHub (22 cột, 17 cạnh qua 5 tầng) tự động lan truyền 100.0% nhãn PII/Financial (chỉ dừng tại phép băm SHA256_DOMAIN_MASK) và cảnh báo chính xác bán kính nổ 4 cột / 4 tập dữ liệu trước khi thay đổi lược đồ được phép hợp nhất.

Mục tiêu Học tập (Learning Objectives)#

Sau Chương 12, orchestration_governance_lab (Lab 11) và Đề án Mini Coursework Phần 2 (1–2 tuần), kỹ sư Dữ liệu & AI nắm vững:

  1. Vượt khỏi cronjob — Điều phối Bất biến & Backfill Xác định: Thiết kế DAG lũy đẳng \(f(f(D_t)) = f(D_t)\) bằng Atomic Partition Overwrite (DELETE + INSERT / MERGE) và zero-copy Iceberg WAP branching, phân biệt logical_date (ds) với thời gian tường datetime.now(), sử dụng Dynamic Task Mapping (.expand()), Asset-Aware Scheduling (airflow.sdk.Asset) và AIP-78 Backfill API.
  2. Kiến trúc Nội tại Apache Airflow 3.0–3.2 & Điều phối Bền bỉ: Làm chủ kiến trúc tách lớp Task Execution API (AIP-72) (cấm worker chạm trực tiếp Metadata DB Session), Standalone DAG Processor, DAG Versioning & Bundles, Deadline Alerts (3.1) thay thế SLA đã xóa bỏ, AssetWatcher & HITLOperator, quy tắc lint Ruff AIR30x, Triggerer (Deferrable), Object-Store URI XCom, và ranh giới chọn Apache Airflow vs Temporal / Restate cho vòng lặp AI Agent dài ngày.
  3. Xác thực Dữ liệu, Ngắt mạch & Hợp đồng Dữ liệu ODCS v3.1.0: Thiết kế Circuit Breaker (@task.short_circuit + Quarantine DLQ + Iceberg WAP + Apache Polaris 1.x), đối chiếu Pandera, Great Expectations và SodaCL, và thực thi hợp đồng YAML ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[], team/roles) qua Pydantic v2 + jsonschema.
  4. Quản trị Dữ liệu (Data Governance), DataHub v1.0+, OpenLineage 1.x & RLS/DDM: Nắm vững mô hình URN/Aspect/MCP + OpenLineage 1.x Iceberg Scan/Commit facets, cài đặt thuật toán lan truyền nhãn PII theo cạnh biến đổi, tính Breaking-Change Blast Radius, và phân biệt thực thi RLS/DDM giữa Apache Polaris + OPA, Unity Catalog, và Trino + Apache Ranger.

Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P2-U06, R34)#

Nội dung Gốc (02-track-edai-raw-curriculum.md, R34) Nâng cấp Chuẩn SOTA 2026 (ch-12) Mục trong Chương 12 Tạo tác & Kiểm thử (orchestration_governance_lab)
1. Pipeline orchestration benefits (R34) Phụ thuộc đồ thị DAG, phục hồi từng nút, airflow.sdk.Asset Scheduling, DAG Versioning & Bundles, truy vết trạng thái tập trung Trụ cột 1 (§1.1) + Mermaid 1 dags/medallion_governance_dag.py, Test 15
2. Beyond the cronjob: idempotency, backfill, dynamic pipelines (R34) Tính bất biến \(f(f(D_t)) = f(D_t)\), Atomic Partition Swap / MERGE, Iceberg WAP branching, logical_date (ds) & AIP-78 Backfill API, .expand() Trụ cột 1 (§1.1 & §1.3) + Widget 1 dag_and_backfill_engine.py, sql/01_governance_audit.sql, Tests 03, 04, 16
3. Airflow architecture, operators and data passing (R34) Airflow 3.0–3.2 (API Server, Task Execution API, DAG Processor, Triggerer asyncio, Celery vs K8s), DeferrableOperator, URI XCom (63 B vs 6.013 MB), @task.short_circuit Trụ cột 1 (§1.2) + Mermaid 1 + Widget 1 docker-compose.yml, run_xcom_and_sensor_concurrency_benchmark, Tests 05, 06, 14
4. Airflow administration & scaling (R34) Task Execution API (không truy cập Metadata DB trực tiếp), Secret Backends, Pools, Deadline Alerts (3.1) thay SLA, AssetWatcher, HITLOperator, Ruff AIR30x, Temporal/Restate vs Airflow Trụ cột 1 (§1.2) + Trụ cột 2 (§2.1) medallion_governance_dag.py (pool, DEADLINE_ALERT_SPEC, AIR30x), Tests 15, 18
5. Fundamentals of data validation: circuit breaker, frameworks, data contracts (R34) Circuit Breaker (@task.short_circuit + Quarantine DLQ + Iceberg WAP + Polaris 1.x), Pandera vs GX vs SodaCL, ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[], amount_usd_max) Trụ cột 1 (§1.3) + Mermaid 2 + Widget 2 contracts/orders_silver_contract.yaml, contracts_and_lineage.py, Tests 07–10, 13, 13b
6. Data governance (DataHub lineage, ownership, PII) (R34) DataHub v1.0+ (URN, MCP, GMS PG Ebean) + OpenLineage 1.x Iceberg Scan/Commit facets, Column-Level Lineage, PII Masking Boundary, Phân tách RLS/DDM (Polaris vs Unity Catalog vs Trino + Ranger/OPA) Trụ cột 1 (§1.4) + Mermaid 3 + Widget 3 build_part2_column_lineage_graph, propagate_pii_tags, Tests 11, 12
7. Lab & Mini Coursework (1–2 weeks) (R34) Kiến trúc Hai Tầng (13-service Airflow 3.0.1 + DataHub v1.0.0 Compose tách DB datahub + Task SDK AST + ODCS v3.1.0 + DuckDB/NetworkX/OTel 100% offline) & Đề án Part 2 (Ch 07 -> Ch 12) Trụ cột 2 (§2.2) + Trụ cột 3–4 Toàn bộ lab-11-airflow-datahub-governance-pipeline/ (24/24 test cases PASS, 0 skip, ruff+AIR, mypy)

Bảng Ký hiệu Thống nhất Xuyên suốt Chương 12 (Unified Notation)#

Ký hiệu Miền / Đơn vị Định nghĩa Chính xác Trong Chương 12 & orchestration_governance_lab Giá trị Thực nghiệm Lab 11
\(t_{\text{logical}}\) ngày / timestamp (\(\text{UTC}\)) logical_date (data_interval_start / chuỗi ds) của mỗi DAGRun, hoàn toàn độc lập đồng hồ tường \(t_{\text{wall}}\) 7 ngày (2026-10-01..10-07) chạy tại 2026-10-10
\(f(D_t)\) tác tử biến đổi Tác vụ xử lý phân vùng ngày \(t\); thỏa Tính bất biến khi \(f(f(D_t)) = f(D_t)\) với mọi số lần chạy lại \(k \ge 1\) Naive +100.0% vs Swap 0.0% drift
\(S_{\text{XCom}}\) \(\text{Byte} / \text{MB}\) Kích thước dữ liệu tuần tự hóa qua XCom (trần an toàn \(\le 48\,\text{KB}\)) Raw 6,304,985 B (6.013 MB) vs URI 63 B (100,079.1x)
\(P_{\text{slots}}, W_{\text{held}}\) slot Tổng số khe worker khả dụng trong Pool và số khe bị cảm biến chờ giữ chặt Sync 16/16 (100%) vs Deferrable 0/16 (0%)
\(\text{CB}(B, \mathcal{C})\) \(\{0, 1\}\) Cổng ngắt mạch Hợp đồng ODCS v3.1.0 đánh giá lô \(B\) theo lược đồ, bất biến chất lượng (0.01..500,000 USD, null <= 1%) & độ tươi 4/4 (100%) lỗi bị chặn, 0.0% ô nhiễm Gold
\(G_{\text{col}} = (V, E)\) Đồ thị có hướng (DAG) Đồ thị Phả hệ Cấp Cột DataHub: đỉnh \(v \in V\) là cặp (dataset_urn, column), cạnh \(e \in E\) gắn cờ propagates_pii 22 cột, 17 cạnh, 5 tầng (100% PII phủ đúng)

Trụ cột 1 — Nguyên lý Gốc: Điều phối Airflow 3.x Bất biến, Hợp đồng ODCS v3.1.0 & Phả hệ DataHub v1.0+#

1.1 Vượt khỏi cronjob: Lợi ích Điều phối DAG, Toán học Tính Bất biến & Backfill Xác định#

Trong những hệ thống sơ khai, kỹ sư thường viết nhiều lệnh cron đặt lịch nối tiếp bằng đồng hồ (01:00 chạy Spark, 02:00 chạy ClickHouse, 03:00 đẩy Feast). Cách làm này sụp đổ vì 4 lỗ hổng cấu trúc: (i) thiếu đồ thị phụ thuộc (DAG) khiến tác vụ sau vẫn chạy dù tác vụ trước sập hoặc kéo dài quá 02:00; (ii) không hỗ trợ retry cấp bước có kiểm soát exponential backoff; (iii) mù trạng thái phân vùng khi cần chạy bù dữ liệu lịch sử (backfill); và (iv) không thể mở rộng động khi số shard thay đổi theo ngày.

1. Toán học Tính Bất biến (Idempotency — Maxime Beauchemin Functional Data Engineering)#

Một tác vụ ETL \(f\) nhận đầu vào bất biến của phân vùng \(D_t\) được gọi là lũy đẳng (idempotent) nếu việc thực thi nó \(k\) lần liên tiếp (\(k \ge 1\)) tạo ra trạng thái bảng đích đồng nhất tuyệt đối với lần chạy đầu tiên:

\[f^{(k)}(D_t) \equiv f(D_t), \qquad \forall k \ge 1\]
  • Phản ví dụ (Non-Idempotent Append): Câu lệnh INSERT INTO silver_orders SELECT ... vi phạm bất biến trên: nếu Worker mất kết nối sau khi commit xong và Scheduler phát lệnh chạy lại (retry=1), phân vùng \(D_t\) bị cộng đúp chính xác +100.0% số dòng và doanh thu (trong Lab 11 test_03: phân vùng 2026-10-04 phình từ 400 đơn / 43,290.30 USD thành 800 đơn / 86,580.60 USD). Qua 4 lần retry rải rác trong tuần, tổng sai lệch phình lên +173,570.66 USD (+57.95%).
  • Mẫu SOTA (Atomic Partition Overwrite / MERGE INTO & Iceberg WAP): Đóng gói thao tác xóa phân vùng đích hoặc hợp nhất trong một giao dịch nguyên tử gắn chặt khóa phân vùng (như trong sql/01_governance_audit.sql):
    1. Delete-Write Swap: BEGIN TRANSACTION; DELETE FROM silver_orders WHERE partition_dt = :logical_date; INSERT INTO silver_orders ... WHERE partition_dt = :logical_date; COMMIT;
    2. Deterministic MERGE INTO / Zero-copy Iceberg WAP: Đối chiếu trên khóa tổng hợp (order_id, partition_dt) hoặc ghi vào nhánh cô lập Write–Audit–Publish (Iceberg branch) rồi fast-forward sang main. Dù Airflow retry 1 hay 100 lần, bảng đích luôn giữ đúng 2,800 dòng với 0.0 USD (0.0%) sai số.

2. Bẫy datetime.now() vs. logical_date (ds) & AIP-78 Backfill API#

Một nguyên tắc tối thượng của Apache Airflow: không bao giờ đọc đồng hồ hệ thống datetime.now() hay SQL CURRENT_DATE() để xác định phạm vi dữ liệu đầu vào hoặc phân vùng đầu ra. Mỗi DAGRun đại diện cho một khoảng thời gian dữ liệu xác định \([t_{\text{start}}, t_{\text{end}})\), trong đó logical_date (data_interval_start) chính là \(t_{\text{start}}\) và được truyền vào TaskFlow dưới dạng chuỗi ngày ds: str | None = None (YYYY-MM-DD):

\[D_{\text{partition}} = \left\{ r \in \text{Bronze} \;\middle|\; t_{\text{logical}} \le r.\text{order\_ts} < t_{\text{logical}} + \Delta_{\text{schedule}} \right\}\]

Cạm bẫy tham số TaskFlow trong Airflow 3.x: Tuyệt đối không đặt tên tham số hàm @task là logical_date: str = "{{ ds }}" vì Airflow tự động bơm biến ngữ cảnh logical_date kiểu Pendulum DateTime (2026-10-01 00:00:00+00:00) đè lên chuỗi mẫu! Thay vào đó, hãy khai báo ds: str | None = None để nhận chuẩn chuỗi "2026-10-01".

Khi chạy bù lịch sử 2026-10-01..2026-10-07 vào ngày 2026-10-10 qua AIP-78 Scheduler-Managed Backfill API (tính năng lõi từ Airflow 3.0 thay thế vòng lặp CLI ngoài Scheduler, hỗ trợ tạm dừng/huỷ/theo dõi trực tiếp trên UI và REST API):

  • DAG lỗi dùng datetime.now() gán toàn bộ 7 ngày lịch sử vào partition_dt = '2026-10-10', để lại 0 / 7 (0.0%) phân vùng đích và làm ô nhiễm hôm nay bằng 2,800 bản ghi trộn lẫn (test_04).
  • DAG chuẩn dùng ds / logical_date tái tạo chính xác 7 / 7 (100.0%) phân vùng, 0 bản ghi nhiễm chéo.

3. Đường ống Động (Dynamic Task Mapping), Asset Scheduling & AssetWatcher#

  • Dynamic Task Mapping (.expand()): Tác vụ thượng nguồn discover_shard_uris trả về danh sách URI thực tế có trong ngày, rồi gọi validate_shard_contract.expand(shard_uri=shard_uris) để Airflow tự sinh số TaskInstance động lúc chạy (runtime), kết hợp max_active_tis_per_dag=4 kiểm soát đồng thời an toàn (test_06: xử lý 12 shards gọn trong 3 đợt).
  • Asset-Aware Scheduling (from airflow.sdk import Asset) & AssetWatcher: Airflow 3.x thay thế airflow.datasets.Dataset bằng airflow.sdk.Asset. DAG nhập liệu khai báo outlets=[ORDERS_BRONZE_ASSET], còn DAG quản trị hạ lưu đặt schedule=[ORDERS_BRONZE_ASSET] để kích hoạt tức thì khi tài sản nguồn được cam kết. Với hệ sinh thái phân tán Data Mesh ngoài một Metadata DB đơn lẻ, AssetWatcher cho phép Triggerer lắng nghe trực tiếp hàng đợi sự kiện (Kafka/SQS/Webhook) để kích hoạt DAG theo sự kiện thời gian thực.
Đang khởi tạo mô phỏng tương tác...

1.2 Kiến trúc Nội tại Apache Airflow 3.0–3.2, Task Execution API & Điều phối Bền bỉ#

Kiến trúc Apache Airflow 3.0–3.2 tách rời hoàn toàn Mặt phẳng Điều khiển (Control Plane) khỏi Mặt phẳng Thực thi (Execution Plane) nhằm tăng bảo mật đa vùng và co giãn hàng chục nghìn tác vụ:

Mermaid Architecture Diagram
100%
flowchart LR
    FILES["DAG Bundles & ODCS v3.1 YAML"] -->|"Independent Parse Loop"| DAGP["Standalone DAG Processor (Airflow 3)"]
    DAGP -->|"DAG Versioning Snapshot"| META["Metadata DB (PostgreSQL 16)"]
    SCHED["Airflow Scheduler (AIP-78 Backfill + Asset Graph)"] <-->|"State, DAGRun, Pools"| META
    SCHED -->|"Queue Task Messages"| BROKER["Celery Broker (Redis 7.4) / K8s API"]

    BROKER -->|"Compute Tasks (Pool-Bounded)"| WORKER["Celery / K8s / Edge Workers"]
    BROKER -->|"Async Wait & Deadline Alerts (3.1)"| TRIG["Airflow Triggerer (asyncio + AssetWatcher)"]

    WORKER <-->|"Task Execution API (AIP-72 JWT/HTTP - No Direct DB!)"| APISRV["Airflow API Server (:8080)"]
    TRIG <-->|"Execution / Callback State"| APISRV
    APISRV <--> META

    WORKER -->|"Read/Write Parquet & Iceberg WAP"| OBJ["Object Store (MinIO / S3 / Polaris 1.x)"]
    WORKER -->|"Emit OpenLineage 1.x / MCP"| DH["DataHub v1.0+ GMS + Kafka + ES"]
  1. Tách Airflow API Server, Standalone DAG Processor & Task Execution API (AIP-72):
    • Trong Airflow 2.x, Webserver vừa phục vụ UI vừa cho phép Worker/Task mở kết nối trực tiếp vào bảng PostgreSQL Metadata DB (Session), tạo rủi ro lộ chuỗi kết nối DB và nghẽn connection pool.
    • Từ Airflow 3.0, webserver được thay bằng airflow api-server, tiến trình airflow dag-processor tách hẳn khỏi Scheduler, và mọi Worker/Task bị cấm chạm trực tiếp Metadata DB Session — toàn bộ heartbeat, lấy Variable/Connection, ghi XCom và cập nhật trạng thái đều đi qua Task Execution API (AIP-72) được xác thực bằng JWT (AIRFLOW__CORE__EXECUTION_API_SERVER_URL).
    • Toàn bộ tác giả DAG chỉ nhập khẩu qua Task SDK (from airflow.sdk import Asset, dag, task); DAG Versioning & DAG Bundles lưu lại chính xác mã DAG theo từng DAGRun lịch sử, ngăn chặn gãy ngữ cảnh khi triển khai phiên bản DAG mới giữa lúc đang chạy dở.
  2. So sánh Các Bộ thực thi (Executors):
Executor Cơ chế Thực thi Tác vụ Ưu điểm Chính Nhược điểm & Khi nào Dùng
LocalExecutor Sinh tiến trình con ngay trên máy Scheduler Triển khai siêu nhẹ, không cần Redis/K8s Không co giãn ngang đa máy — chỉ dùng dev/nhỏ (< 20 tasks đồng thời)
CeleryExecutor Đẩy hàng đợi qua Redis/RabbitMQ tới nhóm Celery Workers sống sẵn Khởi động task cực nhanh (< 200 ms), chia hàng đợi (queue="gpu", queue="etl") Chung môi trường Python trên worker; tốn RAM tĩnh nếu rảnh
KubernetesExecutor Mỗi TaskInstance khởi tạo 1 Pod K8s độc lập, chạy xong tự hủy Cô lập tuyệt đối thư viện/CPU/RAM/GPU theo từng task; co giãn về 0 Độ trễ khởi tạo Pod (5–20 s); tối ưu khi gộp KubernetesPodOperator hoặc Edge/K8s hybrid
  1. Triggerer, Deferrable Operators, Deadline Alerts (3.1) & HITLOperator:
    • Deferrable Operator (deferrable=True): Tác vụ kiểm tra một nhịp trên Worker rồi gọi self.defer(trigger=...) trả lại 100% Worker Slot ngay lập tức về Triggerer (asyncio, test_06: 48 cảm biến chờ chỉ tiêu thụ 0 / 16 worker slots thay vì nghẽn 100.0% pool!).
    • Deadline Alerts (Airflow 3.1+) thay thế hoàn toàn SLA/sla_miss_callback đã xóa bỏ: Airflow 3.x xóa bỏ tham số sla lỗi thời của Airflow 2.x (vốn gắn cứng vào vòng lặp Scheduler gây nghẽn) và thay bằng DeadlineAlert (reference=DeadlineReference.DAGRUN_LOGICAL_DATE, interval=timedelta(minutes=30), callback=AsyncCallback(...)) do Triggerer giám sát bất đồng bộ ở cấp DAGRun và phát cảnh báo ngoài luồng không chặn Worker.
    • HITLOperator (Human-in-the-Loop, Airflow 3.1/3.2): Khi hợp đồng dữ liệu hoặc tác vụ AI cần con người phê duyệt (approve/reject), HITLOperator chuyển TaskInstance sang trạng thái awaiting_input do Scheduler quản lý — giải phóng toàn bộ Worker & Triggerer slots cho tới khi người duyệt phản hồi qua UI/API.
  2. Truyền Dữ liệu (XCom vs. Object-Store URI Pointer) & Quy tắc Lint Ruff AIR30x:
    • Nhồi DataFrame vào XCom (6.013 MB cho 50,000 dòng ở test_05) vượt trần 48 KB hơn 128x và làm quá tải Task Execution API / Metadata DB; mẫu chuẩn truyền Object-Store URI Pointer (s3://lakehouse/..., 63 B, nhỏ hơn 100,079.1x!).
    • Di trú Sạch với Ruff AIR30x: Sử dụng bộ quy tắc AIR301–AIR304, AIR311–AIR321 trong ruff (ruff check --select AIR dags/) để tự động phát hiện và ngăn chặn mọi API Airflow 2.x đã loại bỏ (airflow.datasets.Dataset \(\to\) AIR311, gọi datetime.now() động ở cấp module DAG gây hỏng DAG Versioning \(\to\) AIR304, tham số sla cũ).
  3. Điều phối Bền bỉ cho Agent Dài ngày (Temporal / Restate vs. Apache Airflow 3.x):
    • Apache Airflow 3.x là chuẩn vàng cho scheduled batch & Asset/event-driven ETL/ML pipelines (DAG phi chu trình có định kỳ theo logical_date, backfill lịch sử, dynamic mapping).
    • Tuy nhiên, với AI Agents / Human-in-the-Loop dài ngày có vòng lặp chu trình (cyclic tool-calling loops) kéo dài hàng giờ hoặc hàng ngày, điều phối theo DAG thuần túy không phù hợp. Các hệ thống Durable Execution như Temporal hoặc Restate lưu event-sourced execution log ở cấp từng bước gọi LLM/tool (intra-task durability): nếu process sập ở bước thứ 14/20, Agent phát lại lịch sử từ bộ nhớ bền vững và tiếp tục đúng bước 15 mà không gọi lại LLM tốn phí hay lặp tác dụng phụ API. Trong kiến trúc SOTA 2026, Airflow điều phối chuỗi dữ liệu Lakehouse & Feature Store định kỳ, còn Temporal/Restate chạy dịch vụ Agent/workflow tương tác dài ngày (hoặc được Airflow kích hoạt như một tác vụ ngoài bền bỉ).

1.3 Xác thực Dữ liệu, Hợp đồng ODCS v3.1.0 & Kiến trúc Iceberg WAP + Apache Polaris#

Một đường ống điều phối chạy đúng giờ nhưng bơm rác vào bảng Gold và kho đặc trưng ML sẽ tàn phá độ tin cậy nhanh hơn cả một đường ống dừng chạy! Giải pháp SOTA là kết hợp Hợp đồng Dữ liệu ODCS v3.1.0 ở ranh giới Producer–Consumer với mẫu Circuit Breaker (@task.short_circuit + Quarantine DLQ + Iceberg WAP).

Mermaid Architecture Diagram
100%
flowchart LR
    RAW["Bronze Partition (dt = ds)"] --> MAP["Mapped Shard Check (.expand)"]
    MAP --> WAP["Write to Iceberg WAP Audit Branch (Apache Polaris 1.x)"]
    WAP --> AUDIT{"ODCS v3.1.0 Gate (Schema + quality[] + slaProperties[])"}
    AUDIT -->|"PASS (0 Violations)"| PROMOTE["@task.short_circuit = True -> Fast-Forward WAP Branch / Atomic Swap Gold & Feast"]
    AUDIT -->|"FAIL (Drift / Min-Max / Null Spike / Late)"| TRIP["@task.short_circuit = False (Downstream Skipped!)"]
    TRIP --> DLQ["Quarantine Dead-Letter Table + Alert Data Steward"]
Đang khởi tạo mô phỏng tương tác...

1. Đối chiếu Ba Framework Xác thực Dữ liệu Phổ biến#

Framework Triết lý & API Chính Điểm Mạnh SOTA Điểm Yếu & Ngữ cảnh Lựa chọn
Pandera Schema kiểu Python DataFrame (pa.DataFrameModel, pa.Check) cho Pandas, Polars, PySpark Cú pháp Pythonic, nhẹ, tích hợp chặt @pa.check_types và Hypothesis sinh dữ liệu test trong CI Ít phù hợp nếu muốn đẩy kiểm toán SQL trực tiếp trên bảng tỷ dòng kho dữ liệu
Great Expectations (GX) Khai báo ExpectationSuite, Checkpoint & xuất báo cáo HTML Data Docs Kho luật dựng sẵn đồ sộ, Data Docs đẹp cho kiểm toán tuân thủ doanh nghiệp Cấu hình cồng kềnh, tốc độ chạy Python tương đối nặng khi chạy trên nhiều shard nhỏ
Soda Core / SodaCL Ngôn ngữ khai báo YAML (SodaCL) biên dịch thành câu lệnh SQL đẩy xuống DuckDB / ClickHouse / Spark / Trino Dễ đọc cho cả Business Analyst & Engineer, thực thi pushdown trên engine dữ liệu Các hàm kiểm tra thống kê tùy biến phức tạp vẫn cần bổ sung Python/Pandera

2. Đặc tả Hợp đồng ODCS v3.1.0 (contracts/orders_silver_contract.yaml) & Iceberg WAP#

Chuẩn Open Data Contract Standard (ODCS v3.1.0) chuẩn hóa hợp đồng máy-đọc-được thành các khối tường minh nằm chung Git với mã Producer:

  • schema[].properties[]: Tách biệt đối tượng bảng (silver_orders) và danh sách thuộc tính (properties[]), khai báo đồng thời logicalType, physicalType, required, primaryKey, classification và tags (PII.CustomerID, PII.Email, Financial.Amount). Đặc biệt, để nhất quán 100% với quy tắc dung sai null max_null_rate_pct <= 1.0% cho khách vãng lai, cột customer_id được khai báo required: false trong lược đồ (vẫn bắt buộc tồn tại khóa cột chống SCHEMA_DRIFT, nhưng cho phép giá trị null đến <= 1.0%), triệt tiêu mâu thuẫn báo sai SCHEMA_DRIFT khi kiểm tra ngưỡng Null Spike!
  • quality[] & slaProperties[]: Luật kiểm định amount_usd_min >= 0.01, amount_usd_max <= 500000.0 (chặn mọi đơn hàng lỗi phình giá trị bất thường, kiểm chứng tại test_13b), max_null_rate_pct <= 1.0%, max_duplicate_order_id_pct == 0.0%, cùng slaProperties[] gắn bộ lập lịch (freshness <= 30 minutes, availability >= 99.9%).
  • team[], roles[] & customProperties[]: Phân tách rạch ròi đội ngũ sở hữu (Data Product Owner, Data Steward) với vai trò truy cập người tiêu thụ (finance-bi-olap, fraud-ml-feast), luật thay đổi phá vỡ (allow_column_drop: false) và chính sách ngắt mạch (quarantine_and_short_circuit).
  • Zero-Copy Iceberg Write–Audit–Publish (WAP) + Apache Polaris (1.x): Ở quy mô bảng Lakehouse lớn, thay vì ghi tạm rồi copy lại dữ liệu, tác vụ Airflow mở một nhánh Iceberg cô lập (WAP branch) được đăng ký qua catalog mở Apache Polaris 1.x, chạy bộ kiểm định ODCS v3.1.0 trực tiếp trên nhánh đó; nếu pass mới thực hiện phép đổi con trỏ zero-copy fast-forward sang main, còn nếu fail (@task.short_circuit = False) thì giữ nguyên main sạch 0.0% ô nhiễm và cách ly dữ liệu lỗi vào quarantine_orders_dead_letter (test_08–test_10, test_13b).

1.4 Quản trị Dữ liệu (Data Governance): DataHub v1.0+, OpenLineage 1.x & Phân tách RLS/DDM#

Khi doanh nghiệp vận hành hàng trăm bảng dữ liệu và mô hình AI, câu hỏi sinh tử không chỉ là "Pipeline hôm nay có xanh không?" mà là:

  1. "Cột amount_ewma_30d trên Feast lấy nguồn từ đâu, mỗi lần Iceberg WAP commit đã thêm/xóa bao nhiêu tệp Parquet?"
  2. "Nếu đội Checkout sửa tên hoặc đổi đơn vị cột gross_amount_cents ở PostgreSQL CDC, có bao nhiêu dashboard tài chính và mô hình chống gian lận sẽ gãy?"
  3. "Ai được phép nhìn thấy email thật vs bản băm, và thành phần nào thực thi RLS / DDM lúc truy vấn?"

1. Kiến trúc DataHub v1.0+ (PostgreSQL Ebean, URN, MCP) & OpenLineage 1.x Iceberg Facets#

  • Mô hình Siêu dữ liệu Đồ thị & DataHub v1.0+: Mọi thực thể được định danh bằng URN (urn:li:dataset:(urn:li:dataPlatform:iceberg,lakehouse.silver_orders,PROD)) và gắn Aspects qua sự kiện Metadata Change Proposal (MCP) đẩy vào Kafka (CLUSTER_ID 22 ký tự base64 chuẩn KRaft, KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 và MIN_ISR=1 cho cụm single-broker) \(\to\) datahub-gms:v1.0.0 (cấu hình đầy đủ EBEAN_DATASOURCE_DRIVER=org.postgresql.Driver kết nối tới cơ sở dữ liệu datahub tách biệt hoàn toàn khỏi airflow nhờ 00_init_databases.sql và dịch vụ bootstrap datahub-postgres-setup nạp bảng metadata_aspect_v2 từ 02_datahub_bootstrap.sql) \(\to\) Elasticsearch 8 \(\to\) DataHub Frontend.
  • Kết nối OpenLineage 1.x với Apache Iceberg ScanReport / CommitReport Facets: Khi Spark/Flink/Trino đọc hoặc cam kết snapshot lên bảng Iceberg trong tác vụ Airflow, trình tích hợp OpenLineage 1.x đọc trực tiếp MetricsReporter của Iceberg để phát ScanReport facets (số tệp dữ liệu/delete files đã quét hoặc bỏ qua nhờ partition pruning) và CommitReport facets (số snapshot mới, tệp thêm/bớt, thời lượng commit) sang DataHub GMS, hợp nhất phả hệ cột với thống kê I/O vật lý!
  • Lan truyền Nhãn PII & Breaking-Change Blast Radius: Duyệt tô-pô đồ thị cột \(G_{\text{col}} = (V, E)\) (22 cột, 17 cạnh qua 5 tầng) đạt độ phủ 100.0% (9 / 9) thẻ nhạy cảm qua biến đổi tuyến tính (DIV_100_USD, SUM_STATE, EWMA_FEATURE), dừng chuẩn xác tại SHA256_DOMAIN_MASK (email_domain_hash, test_11), và đo bán kính nổ 4 cột / 4 tập dữ liệu / 4 đội khi phá vỡ gross_amount_cents (test_12).

2. Phân tách Thực thi Bảo mật Hàng/Cột (RLS / DDM Runtime): Catalog vs Engine#

Một nhầm lẫn phổ biến khi triển khai Lakehouse là cho rằng Catalog tự động che cột hoặc lọc dòng cho mọi truy vấn. Thực tế kiến trúc SOTA 2026 phân tách rạch ròi vai trò Quản lý Quyền & Vends Credentials với Thực thi Biểu thức RLS/DDM tại Runtime:

Kiến trúc Quản trị Vai trò Catalog & Credential Vending Nơi Thực thi Row-Level Security (RLS) & Dynamic Data Masking (DDM)
Apache Polaris (1.x) (+ OPA) Iceberg REST Catalog mở đa engine: kiểm tra RBAC ở cấp catalog/namespace/table, tích hợp Policy Decision Point ngoài như OPA, và cấp phát STS credentials ngắn hạn (credential vending) trỏ xuống S3/MinIO Polaris KHÔNG tự viết lại truy vấn RLS/DDM! Polaris nhường phần lọc hàng & che cột runtime cho Compute/Query Engine (như Trino, Spark) khi đọc tệp Parquet từ object storage
Unity Catalog Unified Catalog (hỗ trợ cả Delta & Iceberg REST spec), lưu trữ quyền, thẻ phân loại dữ liệu và định nghĩa biểu thức lọc/che tập trung Khi chạy qua hệ sinh thái compute tích hợp (hoặc giao thức thực thi được hỗ trợ), Unity Catalog trực tiếp gắn và áp dụng row filter & column mask functions ở tầng quy hoạch truy vấn
Trino + Apache Ranger / OPA Kết nối vào Polaris/HMS/Iceberg catalog để lấy metadata bảng & vị trí tệp Trino chịu trách nhiệm thực thi RLS/DDM tại runtime (viết lại SQL AST chèn WHERE filter & hàm sha256/redact cho cột PII) dựa trên chính sách lấy từ Apache Ranger hoặc OPA
Mermaid Architecture Diagram
100%
flowchart LR
    CDC_AMT["L1 CDC: postgres.orders_cdc#gross_amount_cents [Financial.Amount]"] -->|"DIV_100_USD (PII=True)"| SIL_AMT["L2 Iceberg: silver_orders#amount_usd [Financial.Amount]"]
    CDC_MAIL["L1 CDC: postgres.orders_cdc#customer_email [PII.Email]"] -->|"IDENTITY (PII=True)"| SIL_MAIL["L2 Iceberg: silver_orders#customer_email [PII.Email]"]
    CDC_CID["L1 CDC: postgres.orders_cdc#customer_id [PII.CustomerID]"] -->|"IDENTITY (PII=True)"| SIL_CID["L2 Iceberg: silver_orders#customer_id [PII.CustomerID]"]

    SIL_AMT -->|"SUM_1H_WINDOW"| FLK_SPEND["L3 Flink: customer_risk_1h#total_spend_1h_usd [Financial.Amount]"]
    SIL_AMT -->|"SUM_STATE"| CH_REV["L4 ClickHouse: gold_revenue_mart#revenue_usd [Financial.Amount]"]
    SIL_MAIL -->|"SHA256_DOMAIN_MASK (Stops PII)"| FLK_HASH["L3 Flink: customer_risk_1h#email_domain_hash [NO PII]"]
    SIL_CID -->|"IDENTITY"| CH_CID["L4 ClickHouse: gold_revenue_mart#customer_id [PII.CustomerID]"]

    FLK_SPEND -->|"EWMA_FEATURE"| FEAST_AMT["L5 Feast: customer_risk_features#amount_ewma_30d [Financial.Amount]"]
    SIL_AMT -->|"BATCH_MATERIALIZE"| FEAST_AMT
    SIL_CID -->|"ENTITY_KEY"| FEAST_CID["L5 Feast: customer_risk_features#customer_id [PII.CustomerID]"]
Đang khởi tạo mô phỏng tương tác...

Trụ cột 2 — Kiến trúc Hệ thống & Đề án Mini Coursework Phần 2 (1–2 Tuần: Tích hợp Ch 07 \(\to\) Ch 12)#

2.1 Cẩm nang Quyết định Sản xuất (Production Decision Playbook)#

Câu hỏi Kiến trúc Phương án A Phương án B Tiêu chuẩn Chọn Lựa SOTA 2026
Điều phối Batch ETL vs Agent Dài ngày Apache Airflow 3.x Temporal / Restate Dùng Airflow 3.x cho scheduled batch & Asset-driven Data/ML ETL (logical_date, backfill, .expand()); dùng Temporal/Restate cho durable execution vòng lặp AI Agent / HITL dài ngày
Cơ chế Chờ & Cảnh báo Trễ poke + sla cũ (Airflow 2.x) DeferrableOperator + DeadlineAlert (3.1) Cấm mode="poke" (> 60s) và bỏ hẳn sla đã xóa; dùng deferrable=True + DeadlineAlert chạy trên asyncio Triggerer
Truyền Dữ liệu (XCom) & Execution API Inline JSON / DB Session trực tiếp Object-Store URI + Task Execution API Chỉ truyền s3:// URI (63 B); worker luôn giao tiếp qua airflow-api-server Execution API (AIP-72), không chạm DB
Kiểm định Hợp đồng & Phát hành Bảng Kiểm tra sau ghi (Post-write) ODCS v3.1.0 + Iceberg WAP + @task.short_circuit Mọi bảng Silver/Gold đi qua ODCS v3.1.0 Gate (trên nhánh Iceberg WAP / staging) trước khi chuyển tiếp sang ClickHouse & Feast
Thực thi Bảo mật RLS / DDM Tin vào Catalog đơn thuần (Polaris) Catalog (Polaris) + Engine (Trino + Ranger/OPA) / Unity Catalog Polaris chỉ vend STS credentials & RBAC mức bảng; kết hợp Trino + Ranger/OPA (hoặc Unity Catalog) để áp dụng RLS/DDM runtime

2.2 Đề án Tổng hợp Phần 2 (Part 2 Mini Coursework, 1–2 Tuần — End-to-End Governed Data & Feature Platform)#

Trong đề cương gốc R34 (Milestone: Mini Coursework 1–2 weeks), sau khi học xong trọn bộ 6 chương Phần 2 (Ch 07 \(\to\) Ch 12), học viên phải ghép nối tất cả các mảnh ghép đơn lẻ thành một nền tảng dữ liệu & đặc trưng ML hoàn chỉnh có điều phối, kiểm định hợp đồng và truy vết phả hệ từ đầu tới cuối:

Chặng Kiến trúc Chương & Lab Tham chiếu Công nghệ & Nhiệm vụ Tích hợp Cốt lõi Tài sản (Asset) & Bất biến Bắt buộc
1. Streaming Ingestion Ch 07 + Lab 06 PostgreSQL Transactional Outbox + Debezium + Kafka KRaft + Schema Registry Phát sự kiện CDC ổn định không Dual-Write (0% mất/ma), gắn schema_id
2. Open Lakehouse Storage Ch 08 + Lab 07 MinIO/S3 + Apache Iceberg (WAP branching + Polaris 1.x) / Delta Lake + Trino/DuckDB Nén cột, Schema Enforcement, bất đẳng thức an toàn VACUUM (\(\ge 169\,\text{h}\))
3. Batch & Stream Compute Ch 09 (Lab 08) & Ch 10 (Lab 09) Spark Batch DQ Quarantine + Salted Skew Join; Flink Event-Time, Watermarks (withIdleness), RocksDB Checkpoints Bảo toàn 100% dòng (Raw = Clean + DLQ + Dedup), 0.0 USD lệch Event-Time
4. Consumption OLAP & Feast Ch 11 + Lab 10 ClickHouse MergeTree (SCD Type 2, AggregatingMergeTree MV, argMax) + Feast (Redis + DuckDB ASOF + OnDemandFeatureView) 0.0 USD méo SCD2, 0.0% Future Leak (TTL=3600s), 100.0% Offline–Online Parity
5. Orchestration & Governance Ch 12 + Lab 11 (orchestration_governance_lab) Airflow 3.x (airflow.sdk.Asset, ds, Deferrable, .expand(), @task.short_circuit, ObjectStore URI) + ODCS v3.1.0 + DataHub v1.0+ 0.0% drift khi retry, 7/7 backfill, 4/4 lỗi bị ngắt mạch (0% bẩn Gold), 100% PII lineage

Lộ trình Thực hiện 2 Tuần & Bảng Nghiệm thu (Mini Coursework Acceptance Checklist)#

  • Tuần 1 — Dựng Đường ống Liên thông & Điều phối Bất biến:
    1. Dựng hạ tầng Docker Compose (13 dịch vụ = 8 Airflow + 5 DataHub: airflow-postgres, airflow-redis, airflow-init, airflow-api-server, airflow-dag-processor, airflow-scheduler, airflow-worker, airflow-triggerer, datahub-postgres-setup, datahub-kafka, datahub-elasticsearch, datahub-gms:v1.0.0, datahub-frontend) kết nối Kafka CDC (Lab 06) \(\to\) MinIO/Iceberg (Lab 07) \(\to\) Spark/Flink (Lab 08–09) \(\to\) ClickHouse/Feast (Lab 10).
    2. Chuyển đổi toàn bộ tác vụ sang ds (logical_date), truyền s3:// URI qua XCom và dùng Atomic MERGE INTO / Partition Swap (sql/01_governance_audit.sql).
    3. Kiểm chứng chạy lại (rerun) và backfill 7 ngày đạt 0.0% trùng lặp.
  • Tuần 2 — Gắn Hợp đồng ODCS v3.1.0 Circuit Breaker, Phả hệ DataHub v1.0+ & Nghiệm thu Bảo vệ:
    1. Định nghĩa contracts/orders_silver_contract.yaml chuẩn ODCS v3.1.0 (schema[].properties[], quality[] gồm amount_usd_min/amount_usd_max, slaProperties[], team/roles).
    2. Tích hợp @task.short_circuit vào medallion_orders_governance_dag và tiêm thử các lỗi (schema_drift, negative_amount, excessive_amount > 500k, null_spike, freshness_sla_breach), xác nhận 0 dòng độc lọt xuống Gold/Feast.
    3. Nạp DataHub v1.0+ GMS/OpenLineage 1.x để hiển thị đồ thị phả hệ 5 tầng, chứng minh lan truyền PII dừng đúng tại hàm băm và xuất báo cáo artifacts/t2_ch12_lab11_results.json kèm pytest + ruff (AIR30x) + mypy xanh 100%.

Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#

Đoạn mã hoàn chỉnh dưới đây chạy độc lập trong .venv (chỉ sử dụng duckdb, pydantic, pyyaml, networkx, jsonschema), chứng minh tại chỗ cả 3 trụ cột cốt lõi: (1) Atomic Partition Swap chống nhân đôi +100% trên DuckDB; (2) ODCS v3.1.0 Data Contract Circuit Breaker chặn dữ liệu âm/vượt trần 500,000 USD khỏi bảng Gold; và (3) DataHub Column-Level Lineage lan truyền nhãn PII và tính bán kính nổ thay đổi lược đồ:

python143 dòng
from __future__ import annotations

import duckdb
import jsonschema
import networkx as nx
import yaml
from pydantic import BaseModel, Field


class OdcsQualityRule(BaseModel):
    metric: str
    mustBeGreaterThanOrEqualTo: float | None = None
    mustBeLessThanOrEqualTo: float | None = None


class OdcsMiniContract(BaseModel):
    apiVersion: str
    kind: str
    id: str
    quality: list[OdcsQualityRule]
    required_columns: list[str] = Field(default_factory=list)


ODCS_V3_1_CONTRACT_YAML = """
apiVersion: v3.1.0
kind: DataContract
id: "urn:contract:orders-silver-v3"
schema:
  - name: silver_orders
    properties:
      - name: order_id
        logicalType: string
        required: true
      - name: customer_id
        logicalType: string
        required: false
      - name: amount_usd
        logicalType: number
        required: true
      - name: partition_dt
        logicalType: string
        required: true
quality:
  - metric: amount_usd_min
    mustBeGreaterThanOrEqualTo: 0.01
  - metric: amount_usd_max
    mustBeLessThanOrEqualTo: 500000.0
slaProperties:
  - property: freshness
    value: 30
    unit: minutes
"""


def demo_idempotent_swap_vs_cron_append() -> None:
    con = duckdb.connect(":memory:")
    con.execute("CREATE TABLE cron_orders (order_id VARCHAR, amount DOUBLE, partition_dt DATE)")
    con.execute("CREATE TABLE atomic_orders (order_id VARCHAR, amount DOUBLE, partition_dt DATE)")

    batch = [("ord_01", 120.0, "2026-10-04"), ("ord_02", 80.0, "2026-10-04")]
    for _run in range(2):  # Run 1 + 1 retry
        con.executemany("INSERT INTO cron_orders VALUES (?, ?, CAST(? AS DATE))", batch)
        con.execute("BEGIN TRANSACTION")
        con.execute("DELETE FROM atomic_orders WHERE partition_dt = CAST('2026-10-04' AS DATE)")
        con.executemany("INSERT INTO atomic_orders VALUES (?, ?, CAST(? AS DATE))", batch)
        con.execute("COMMIT")

    cron_sum = con.execute("SELECT SUM(amount) FROM cron_orders").fetchone()[0]
    atomic_sum = con.execute("SELECT SUM(amount) FROM atomic_orders").fetchone()[0]
    con.close()
    assert cron_sum == 400.0 and atomic_sum == 200.0
    print(f"[1. Idempotency] Cron Append = {cron_sum} (+100% double-count) | Atomic Swap = {atomic_sum} (0% drift)")


def demo_contract_circuit_breaker() -> None:
    raw = yaml.safe_load(ODCS_V3_1_CONTRACT_YAML)
    props = raw["schema"][0]["properties"]
    raw["required_columns"] = [p["name"] for p in props]
    spec = OdcsMiniContract.model_validate(raw)
    assert spec.apiVersion == "v3.1.0"

    rules = {r.metric: r for r in spec.quality}
    amt_min = rules["amount_usd_min"].mustBeGreaterThanOrEqualTo
    amt_max = rules["amount_usd_max"].mustBeLessThanOrEqualTo

    schema = {
        "type": "object",
        "properties": {
            "order_id": {"type": "string"},
            "customer_id": {"type": ["string", "null"]},
            "amount_usd": {"type": "number", "minimum": amt_min, "maximum": amt_max},
            "partition_dt": {"type": "string"},
        },
        "required": spec.required_columns,
        "additionalProperties": False,
    }
    validator = jsonschema.Draft202012Validator(schema)

    toxic_batch = [
        {"order_id": "ord_01", "customer_id": None, "amount_usd": 55.0, "partition_dt": "2026-10-04"},
        {"order_id": "ord_02", "customer_id": "cust_02", "amount_usd": -19.5, "partition_dt": "2026-10-04"},
        {"order_id": "ord_03", "customer_id": "cust_03", "amount_usd": 750000.0, "partition_dt": "2026-10-04"},
    ]
    errors = [err.message for row in toxic_batch for err in validator.iter_errors(row)]
    circuit_tripped = len(errors) > 0
    gold_rows = 0 if circuit_tripped else len(toxic_batch)
    quarantined_rows = len(toxic_batch) if circuit_tripped else 0
    assert circuit_tripped and len(errors) == 2 and gold_rows == 0 and quarantined_rows == 3
    print(f"[2. ODCS v3.1.0 Circuit Breaker] Tripped={circuit_tripped} | Errors={len(errors)} | Gold={gold_rows} | DLQ={quarantined_rows}")


def demo_datahub_column_lineage_pii() -> None:
    g: nx.DiGraph = nx.DiGraph()
    g.add_node("cdc.orders#email", pii=["PII.Email"])
    g.add_node("silver.orders#email", pii=[])
    g.add_node("flink.risk#email_domain_hash", pii=[])
    g.add_node("cdc.orders#cents", pii=["Financial.Amount"])
    g.add_node("silver.orders#amount_usd", pii=[])
    g.add_node("feast.risk#amount_ewma", pii=[])

    g.add_edge("cdc.orders#email", "silver.orders#email", propagates_pii=True)
    g.add_edge("silver.orders#email", "flink.risk#email_domain_hash", propagates_pii=False)
    g.add_edge("cdc.orders#cents", "silver.orders#amount_usd", propagates_pii=True)
    g.add_edge("silver.orders#amount_usd", "feast.risk#amount_ewma", propagates_pii=True)

    tags = {n: set(d["pii"]) for n, d in g.nodes(data=True)}
    for node in nx.topological_sort(g):
        for _, dst, ed in g.out_edges(node, data=True):
            if ed["propagates_pii"]:
                tags[dst].update(tags[node])

    blast_radius = sorted(nx.descendants(g, "cdc.orders#cents"))
    assert tags["silver.orders#email"] == {"PII.Email"}
    assert tags["flink.risk#email_domain_hash"] == set()
    assert blast_radius == ["feast.risk#amount_ewma", "silver.orders#amount_usd"]
    print(f"[3. DataHub Lineage] Feast PII={sorted(tags['feast.risk#amount_ewma'])} | Masked={sorted(tags['flink.risk#email_domain_hash'])} | Blast={blast_radius}")


if __name__ == "__main__":
    demo_idempotent_swap_vs_cron_append()
    demo_contract_circuit_breaker()
    demo_datahub_column_lineage_pii()
    print("Pillar 3 Governance & Orchestration Verification PASSED!")

Trụ cột 4 — Thực hành Công nghiệp (Lab 11: orchestration_governance_lab) & Kết quả Thực nghiệm#

4.1 Kiến trúc Hai Tầng Của Lab 11 (labs/lab-11-airflow-datahub-governance-pipeline/)#

  • Tầng 1 — Tạo tác Triển khai Apache Airflow 3.0.1 + DataHub v1.0.0 Thật (Kiểm toán tĩnh trong infra_audit.py):

    • docker-compose.yml: 13 dịch vụ (8 Airflow + 5 DataHub) gắn tag cố định (postgres:16.4-alpine mount sql/00_init_databases.sql tạo DB datahub riêng, redis:7.4-alpine, apache/airflow:3.0.1-python3.12 dùng x-airflow-common kèm _PIP_ADDITIONAL_REQUIREMENTS: "apache-airflow-providers-amazon>=9.0.0" cho airflow-init, airflow-api-server, airflow-dag-processor, airflow-scheduler, airflow-worker, airflow-triggerer, dịch vụ datahub-postgres-setup nạp sql/02_datahub_bootstrap.sql tạo metadata_aspect_v2, confluentinc/cp-kafka:7.6.1 với CLUSTER_ID 22 ký tự base64 và KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR="1" / MIN_ISR="1", elasticsearch:8.15.3, acryldata/datahub-gms:v1.0.0 với Ebean PostgreSQL trỏ riêng về DB datahub sau service_completed_successfully, acryldata/datahub-frontend-react:v1.0.0), khóa FERNET_KEY 32-byte chuẩn xác, cổng gắn 127.0.0.1:, healthcheck, giới hạn tài nguyên và mạng cô lập governance_net.
    • dags/medallion_governance_dag.py: DAG Airflow 3.x Task SDK (from airflow.sdk import Asset, dag, task) tách riêng hoàn toàn khỏi khối try/except ImportError của S3KeySensor (khi airflow.sdk có mặt nhưng thiếu apache-airflow-providers-amazon, vẫn giữ nguyên Asset, @dag, @task thật và lùi sang BaseSensorOperator/@task.sensor/shim nhẹ), khởi tạo sẵn 2 đối tượng DAG ở cấp module cho DagBag, ds: str | None = None, S3KeySensor(deferrable=True), Dynamic Task Mapping .expand(), XCom-by-ObjectStore URI (s3://lakehouse/...), @task.short_circuit nối trực tiếp XComArg (validation_reports), DEADLINE_ALERT_SPEC (Airflow 3.1), 0 lệnh datetime.now() / sla / pickle (Tests 15, 15b kiểm toán AST, ruff --select AIR & import).
    • contracts/orders_silver_contract.yaml & sql/01_governance_audit.sql: Hợp đồng ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[], team/roles, 7 cột, 3 thẻ PII, SLA 30m, ngưỡng 0.01..500,000.0 USD, nhất quán nullability customer_id, cấm drop cột) và SQL giao dịch DELETE+INSERT/MERGE + bảng quarantine_orders_dead_letter, đồng bộ customer_id VARCHAR nullable trên cả silver_orders lẫn silver_orders_staging (8/8 YAML + 7/7 SQL kiểm định Test 16).
  • Tầng 2 — Động cơ DuckDB 2.0.1 + Pydantic v2 + jsonschema + NetworkX 3.7 + OpenTelemetry SDK 100% Offline (0 Tệp Rác): Thực thi hoàn toàn trong bộ nhớ (duckdb.connect(":memory:")), phát 6 OpenTelemetry spans thật qua TracerProvider + SimpleSpanProcessor + InMemorySpanExporter, xuất báo cáo chuẩn hóa tại artifacts/t2_ch12_lab11_results.json (6 KPIs, 4 biểu đồ thanh, 4 bảng, otel_telemetry).

Danh sách 20 Hàm Kiểm thử (24 Test Cases, 0 Skipped) Trong tests/test_orchestration_governance_lab.py#

Nhóm Kiểm thử Mã Test (pytest) Bất biến Kỹ thuật Được Xác minh Tự động
Bảo mật AST & Sinh Phân vùng test_01, test_02 Cấm pickle/joblib/cloudpickle/dill/shelve/marshal; sinh tất định 7 ngày \(\times\) 400 đơn = 2,800 đơn (seed=42)
Idempotency & logical_date Backfill test_03, test_04 cron append sai +100.0% trên phân vùng retry (800 vs 400) & +57.95% tuần vs Swap 0.0%; datetime.now() sai 0/7 vs logical_date 7/7 (100%)
XCom URI, Deferrable & .expand() test_05, test_06 Raw XCom 6.013 MB > 48 KB vs ObjectStore URI 63 B (100,079.1x); Sync sensor chiếm 16/16 (100%) vs Deferrable 0/16 (0%)
ODCS v3.1.0, Circuit Breaker & Hypothesis test_07–test_10, test_13, test_13b Pydantic v2 + jsonschema giữ nguyên 2,000 lô sạch (kể cả 0.5% null <= 1.0%), bắt trọn lỗi (Schema Drift, Negative Amount, Excessive Amount > 500k, Null Spike 12.5% không lẫn SCHEMA_DRIFT, SLA 47m) với 0 dòng bẩn xuống Gold + Hypothesis
DataHub Lineage, PII & Blast Radius test_11, test_12 Phủ 100% (9/9) thẻ PII hạ lưu, dừng tại SHA256_DOMAIN_MASK, và tính chính xác bán kính nổ 4 cột / 4 datasets / 4 teams
Hạ tầng Airflow 3/DataHub v1, CLI & OTel test_14–test_18 Compose (13 services = 8 Airflow + 5 DataHub gồm datahub-postgres-setup, tách DB datahub, Kafka Tx=1, 127.0.0.1), DAG AST tách airflow.sdk vs S3KeySensor (test_15b giả lập thiếu provider), ODCS v3.1 YAML (8/8), SQL (7/7, customer_id nullable), schema 6/4/4 & 0 tệp .parquet/.duckdb* rác, OpenTelemetry spans

4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch12_lab11_results.json, seed=42)#

Thực nghiệm (orchestration_governance_lab) Thông số Đo được (Xác định) Bất biến Được Chứng minh
Idempotent Partition Swap (DuckDB, 2,800 đơn) Retry 1 ngày: cron 800 dòng (+100.0%) vs Swap 400 (0.0%); Tuần: cron 4,400 (+57.95%) vs Swap 2,800 (0.0 USD err) DELETE+INSERT / MERGE bất biến dưới mọi số lần retry
logical_date vs datetime.now() Backfill (7 ngày) datetime.now(): 0 / 7 (0.0%), 2,800 dòng đổ nhầm sang 2026-10-10; logical_date: 7 / 7 (100.0%), 0 nhiễm chéo Chỉ logical_date (ds) bảo toàn tính xác định khi chạy bù
XCom ObjectStore URI vs Raw DataFrame (50k đơn) Raw JSON XCom: 6,304,985 B (6.013 MB); ObjectStore URI: 63 B (100,079.1x nhỏ hơn) Bảo vệ Metadata DB & Execution API khỏi bão XCom OOM
Deferrable Triggerer vs Sync Sensor (48 shards) Sync poke: 16 / 16 (100.0%) worker slots bị giữ (32 queued, 28,800 slot-s); Deferrable: 0 / 16 (0.0%), 48 coros Triệt tiêu nghẽn Worker Pool khi chờ cảm biến
ODCS v3.1.0 Contract Circuit Breaker (5 kịch bản) Không có ngắt mạch: 8,000 / 8,000 (100.0%) dòng bẩn xuống Gold; Circuit Breaker: bắt 4 / 4 (100%), 0 (0.0%) bẩn Gold Chặn đứng dữ liệu lỗi vào ClickHouse Gold & Feast
DataHub Column Lineage & PII (22 cột, 17 cạnh) Phủ PII 9 / 9 (100.0%); dừng tại email_domain_hash; sửa gross_amount_cents tác động 4 cột / 4 datasets Truy vết và chặn breaking change trước khi triển khai
OpenTelemetry SDK (InMemorySpanExporter) span_count = 6 (idempotency_and_backfill, logical_date_backfill, xcom_uri_and_deferrable, circuit_breaker_gate, column_lineage_impact, benchmark.suite) Đo đạc chuẩn hóa qua OpenTelemetry SDK

4.3 Quy trình Kiểm định Tự động (24/24 Test Cases Pass)#

bash6 dòng
cd 03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-11-airflow-datahub-governance-pipeline
python scripts/run_lab_demo.py --days 7 --rows-per-day 400 --seed 42 --output artifacts/t2_ch12_lab11_results.json
ruff check src tests scripts dags
ruff check --select AIR dags
mypy src
pytest -p no:cacheprovider -v

Trụ cột 5 — Danh mục Tài liệu SOTA (6 Tài liệu) & Bài tập Chuyên sâu#

5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#

  1. Apache Airflow Project (2025–2026). "Apache Airflow 3.0–3.2 Architecture: Task SDK (airflow.sdk), Task Execution API (AIP-72), DAG Versioning, AIP-78 Backfills, Deadline Alerts (3.1), AssetWatcher & HITLOperator." — Tài liệu chuẩn về tách lớp Execution API, Triggerer asyncio và bộ quy tắc di trú Ruff AIR30x.
  2. Beauchemin, M. (2017–2025). "Functional Data Engineering — A Modern Paradigm for Batch Data Processing." — Nền tảng lý thuyết về tính bất biến phân vùng (partition idempotency), logical_date, cấm datetime.now(), và mô hình bất biến hóa pipeline.
  3. Jones, A. & Bitol / Linux Foundation AI & Data (2023–2026). "Driving Data Quality with Data Contracts" & Open Data Contract Standard (ODCS v3.1.0). — Đặc tả schema[].properties[], quality[], slaProperties[], team/roles và quy tắc thay đổi phá vỡ giữa Producer và Consumer.
  4. DataHub Project (v1.0+), OpenLineage (1.x) & Apache Polaris (1.x) (2024–2026). "DataHub Metadata Graph (URN/MCP/GMS), OpenLineage Iceberg ScanReport/CommitReport Facets & Fine-Grained Governance (Polaris + Trino/Ranger/OPA)." — Kiến trúc siêu dữ liệu đồ thị, phả hệ cột và phân tách credential vending với thực thi RLS/DDM.
  5. Netflix / Apache Iceberg & Python Data Validation Ecosystem (2023–2026). "Zero-Copy Iceberg Write–Audit–Publish (WAP) Branching" cùng Pandera, Great Expectations và SodaCL. — Thực thi cổng ngắt mạch cách ly lô lỗi trước khi phát hành bảng Gold và Feature Store.
  6. Temporal Technologies & Restate (2024–2026). "Durable Execution for Long-Running Stateful Workflows and AI Agents" (đối chiếu với Kleppmann DDIA & batch orchestrators). — Nguyên lý thực thi bền vững cấp từng bước (intra-task event sourcing) cho vòng lặp AI Agent & HITL dài ngày.

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 Tính Bất biến & logical_date Backfill: Chứng minh vì sao kịch bản cron append vi phạm bất biến \(f(f(D_t)) = f(D_t)\), giải thích số liệu Lab 11 (+100.0% trên 1 phân vùng retry, +57.95% theo tuần vs 0.0% với Atomic Swap), và phân tích bẫy datetime.now() lẫn lỗi đặt tham số logical_date: str trong TaskFlow (Tests 03, 04). Thang điểm: Đúng toán học bất biến (5%), phân tích đúng ds / logical_date vs datetime.now() (5%), pass Tests 03–04 (5%).

  • Bài tập 2 (ex2, 15%) — Truyền Dữ liệu XCom URI & Kiến trúc Airflow 3.x (Triggerer + Execution API): Giải thích nguyên nhân passing 50,000 dòng qua XCom (6.013 MB > 48 KB) gây nghẽn Metadata DB & Task Execution API so với Object-Store URI (63 B, gọn 100,079.1x), phân tích vai trò Triggerer (Deferrable + Deadline Alerts 3.1) và đối chiếu Airflow 3.x vs Temporal/Restate (Tests 05, 06). Thang điểm: Đúng cơ chế XCom URI & Execution API (5%), phân biệt poke/deferrable & Temporal (5%), pass Tests 05–06 (5%).

  • Bài tập 3 (ex3, 20%) — Hợp đồng ODCS v3.1.0, Iceberg WAP & Mẫu Circuit Breaker: Thiết kế bảng đối chiếu Pandera vs Great Expectations vs SodaCL; giải thích cấu trúc ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[]) và cách @task.short_circuit + Iceberg WAP chặn sạch Schema Drift, 18 đơn âm, đơn vượt 500,000 USD, Null Spike 12.5% và SLA 47m (Tests 07–10, 13, 13b). Thang điểm: Phân tích đúng 3 framework & Iceberg WAP (6%), cài đặt/kiểm chứng 5 kịch bản lỗi + Hypothesis (8%), pass Tests 07–10, 13, 13b (6%).

  • Bài tập 4 (ex4, 20%) — Phả hệ DataHub v1.0+, OpenLineage 1.x & Phân tách RLS/DDM: Vẽ và giải thích luồng MCP \(\to\) Kafka \(\to\) GMS (PG Ebean) \(\to\) Elasticsearch kèm OpenLineage Iceberg ScanReport/CommitReport facets; chứng minh lan truyền PII dừng đúng tại SHA256_DOMAIN_MASK, đo bán kính nổ gross_amount_cents và phân biệt Polaris vs Unity Catalog vs Trino + Ranger/OPA (Tests 11, 12). Thang điểm: Đúng kiến trúc DataHub & OpenLineage (6%), đúng PII masking boundary, blast radius & RLS/DDM (8%), pass Tests 11–12 (6%).

  • Bài tập 5 (ex5, 15%) — Kiểm toán Hạ tầng Airflow 3.0.1 + DataHub v1.0.0 & Bảo mật AST (AIR30x): Giải thích cấu trúc 13 dịch vụ trong docker-compose.yml (8 Airflow + 5 DataHub gồm datahub-postgres-setup, 00_init_databases.sql + 02_datahub_bootstrap.sql tách riêng DB datahub, Kafka Tx=1, Fernet 32-byte, KRaft 22-char CLUSTER_ID, cổng 127.0.0.1), các quy tắc AST trong infra_audit.py (tách try/except giữa airflow.sdk và S3KeySensor) + Ruff AIR30x và kiểm chứng sql/01_governance_audit.sql (Tests 01, 14–16). Thang điểm: Đúng kiến trúc Compose (5%), giải thích sạch luật AST, Task SDK & SQL (5%), pass Tests 01, 14–16 (5%).

  • Bài tập 6 (ex6, 15%) — Đề án Mini Coursework Phần 2 (1–2 Tuần: Ch 07 \(\to\) Ch 12): Trình bày bản thiết kế kết nối liên hoàn từ Kafka CDC (Lab 06) \(\to\) Iceberg/MinIO (Lab 07) \(\to\) Spark/Flink (Lab 08–09) \(\to\) ClickHouse/Feast (Lab 10) \(\to\) Airflow 3.x / DataHub v1.0+ (Lab 11) theo Checklist §2.2, xuất artifacts/t2_ch12_lab11_results.json (6/4/4, 6 spans OTel) và đạt xanh 24/24 test cases + ruff + mypy (Tests 17–18). Thang điểm: Thiết kế liên hoàn Ch 07 -> Ch 12 hợp lý (5%), xác minh đầy đủ Acceptance Checklist (5%), đạt xanh 24/24 test cases + ruff/mypy 0 lỗi (5%).


5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#

  1. (q1 — Tính Bất biến Phân vùng vs. cron Append): Trong thực nghiệm Lab 11 (test_03), điều gì xảy ra khi tác vụ ghi ngày 2026-10-04 (400 đơn hàng) gặp sự cố và được chạy lại 1 lần bằng INSERT INTO thô so với Atomic Partition Swap (DELETE + INSERT) trên DuckDB?
  2. (q2 — logical_date (ds) vs. datetime.now() & AIP-78 Backfill): Tại sao chạy backfill 7 ngày (2026-10-01..2026-10-07) vào ngày 2026-10-10 bằng datetime.now() lại phá hủy 100% phân vùng lịch sử, và vì sao TaskFlow Airflow 3 phải dùng ds thay vì đặt tham số logical_date: str?
  3. (q3 — Truyền Dữ liệu XCom URI & Airflow 3 Task Execution API): Khi cần chuyển kết quả 50,000 đơn hàng giữa hai tác vụ Airflow 3 (test_05), vì sao việc trả về DataFrame/JSON qua XCom làm quá tải Task Execution API / PostgreSQL Metadata DB và giải pháp chuẩn là gì?
  4. (q4 — Kiến trúc Airflow 3.x Triggerer, Deadline Alerts & Temporal/Restate): Khi 48 phân vùng cùng chờ tệp manifest hạ cánh trong 600s trên 16 worker slots (test_06), cơ chế DeferrableOperator / DeadlineAlert hoạt động ra sao và khi nào cần dùng Temporal / Restate thay cho Airflow?
  5. (q5 — Đối chiếu Pandera, Great Expectations, SodaCL & Iceberg WAP): Trong tầng xác thực dữ liệu sản xuất kết hợp zero-copy Iceberg WAP + Apache Polaris, tiêu chí nào giúp chọn đúng giữa Pandera, Great Expectations và SodaCL?
  6. (q6 — Hợp đồng ODCS v3.1.0 & Mẫu Circuit Breaker): Trong Lab 11 (Tests 08–10, 13b), hợp đồng ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[]) kết hợp @task.short_circuit xử lý thế nào khi gặp Schema Drift, số âm/> 500k USD, Null Spike 12.5% hay trễ 47 phút?
  7. (q7 — Phả hệ Cột DataHub v1.0+, OpenLineage & Phân tách RLS/DDM): Trên đồ thị 22 cột / 17 cạnh của Lab 11 (Tests 11–12), thuật toán lan truyền PII xử lý SHA256_DOMAIN_MASK ra sao, OpenLineage thu gì từ Iceberg, và thành phần nào thực thi RLS/DDM khi dùng Apache Polaris?
  8. (q8 — Tích hợp Mini Coursework Phần 2 Ch 07 \(\to\) Ch 12 & Kiểm toán Airflow 3.0.1 + DataHub v1.0.0): Trong đề án tích hợp Phần 2 và kiểm toán tĩnh Lab 11 (Tests 14–17), những bất biến nào của docker-compose.yml (13 dịch vụ), AST DAG (Ruff AIR30x) và ODCS v3.1.0 phải đạt trước khi nghiệm thu?
HANDS-ON PRODUCTION LAB

Lab 11 — Đường ống Điều phối Airflow 3.x, Hợp đồng Dữ liệu ODCS v3.1.0 & Phả hệ Cột DataHub + Mini Coursework (orchestration_governance_lab)

Kiến trúc Hai Tầng (Docker Compose 13 dịch vụ Airflow 3.0.1 + DataHub v1.0.0 + datahub-postgres-setup + airflow-init + 127.0.0.1 + DAG Task SDK/ShortCircuit + ODCS v3.1.0 YAML + DuckDB/NetworkX/OpenTelemetry 100% offline): 24/24 pytest, 0 lỗi ruff/mypy.

Mở hướng dẫn Production Lab đầy đủ →
Atomic Partition Swap vs Cron Append Retry Drift 0.0% vs +100.0% +1,600 dup rows weekly Retrying 1 partition duplicates rows +100.0% (800/400); atomic DuckDB DELETE+INSERT keeps exact 2,800 rows and 0.0 USD drift.
Deterministic logical_date Backfill vs datetime.now() 7/7 (100%) vs 0/7 2,800 misrouted rows Wall-clock datetime.now() routes all 7 historical runs into execution date 2026-10-10; logical_date populates 7/7 partitions cleanly.
ObjectStore URI XCom & Deferrable Triggerer Slots 100,079x XCom | 0/16 held vs 100% sync saturation Raw 50k-row XCom JSON (6.013 MB) exceeds 48 KB DB limit vs 63 B URI; Deferrable Triggerer frees 100% worker slots.
ODCS v3.1.0 Contract Circuit Breaker & Gold Protection 4/4 caught (100%) 0% Gold pollution Quarantines schema drift, out-of-range amounts, null spikes & SLA breaches (8,000 toxic rows blocked from Gold & Feast).
DataHub v1.0+ Column Lineage Blast Radius & PII Tagging 100% PII | 4 cols hit 4 datasets downstream Traces 22 column URNs across 5 Part 2 layers; hash-masking stops PII leak on email_domain_hash.
Airflow 3.x + DataHub v1.0+ Stack & AST Security Audits 4/4 PASS 13 Compose services Validates 13-service Airflow 3.0.1 + DataHub v1.0.0 Compose, Airflow 3 Task SDK AST (Asset, @task.short_circuit, 0 datetime.now/pickle), ODCS v3.1.0 YAML, and idempotent SQL.

Partition Revenue Drift on Retry (%): Atomic Swap vs Naive Cron Append

atomic_partition_swap_merge 0.0% drift (exact 400/400 partition rows)
cron_append_multi_retry_week +57.95% weekly inflation (+1,600 duplicate rows)
cron_append_single_partition_retry +100.0% double-count (800 vs 400 rows)

Airflow Metadata DB XCom Footprint (KB): ObjectStore URI vs Raw DataFrame

object_store_uri_xcom_pointer 63 B (100,079x smaller)
naive_50k_row_json_xcom 6.013 MB (6,157.2 KB — exceeds 48 KB limit!)

Worker Pool Saturation (48-Shard Wait): Deferrable vs Sync Sensor

deferrable_triggerer_asyncio 0.0% worker slots held (48 async coros)
sync_poke_external_sensor 100.0% saturated (16/16 held, 32 queued)

Gold & Feast Toxic Pollution Rate (%): Circuit Breaker vs Unchecked

contract_circuit_breaker_gate 0.0% Gold pollution (8,000/8,000 toxic rows quarantined)
unchecked_pipeline_no_contract 100.0% pollution (8,000 corrupted rows pushed to Gold & Feast)

Idempotent Replay & Deterministic Backfill Reconciliation (DuckDB)

invariant_experiment naive_or_buggy sota_airflow_duckdb verdict
Single-Partition Retry (1x rerun) 800 rows (+100.0%) 400 rows (0.0% drift) PASS (Idempotent Swap)
Multi-Day Incident Retries (7 days) 4,400 rows (+57.95%) 2,800 rows (0.0 USD err) PASS (0 duplicates)
7-Day Historical Backfill Date Binding 0/7 target dates (2,800 rows on today) 7/7 target dates (0 leaks) PASS (logical_date)

Airflow 3.x Scaling: ObjectStore XCom, Deferrable Sensors & Dynamic Task Mapping

scaling_dimension naive_antipattern sota_airflow_3_x impact
XCom Payload (50,000 rows) 6.013 MB JSON in Postgres 63 B ObjectStore URI 100,079x smaller
48-Shard Wait (16-Slot Pool) 16/16 slots held (32 queued) 0/16 held (48 async) 0 worker slot-s wasted
Dynamic Task Mapping (.expand) Static hardcoded 12 tasks 12 shards in 3 waves (max_tis=4) Bounded pool execution

ODCS v3.1.0 Data Contract & Automated Circuit Breaker Outcomes

scenario violation_detected gold_rows_written quarantine_action
Clean Silver Batch (2,000 rows) NONE (0 errors, delay 8m <= 30m) 2,000 PROMOTE_TO_GOLD_AND_FEAST
Schema Drift (Drop amount_usd) SCHEMA_DRIFT 0 Quarantined 2,000 rows
Negative Amounts (18 rows < 0.01) INVARIANT_NEGATIVE_AMOUNT 0 Quarantined 2,000 rows
Null Spike (12.5% > 1.0% limit) INVARIANT_NULL_SPIKE 0 Quarantined 2,000 rows
Freshness SLA Breach (47m > 30m) SLA_FRESHNESS_BREACH 0 Quarantined 2,000 rows

DataHub v1.0+ Column Lineage Blast Radius & Production Infra Static Audits

governance_artifact_or_audit verified_metrics_and_scope status
DataHub Column Lineage & PII 22 cols / 17 edges | PII 100% | amount break hits 4 cols PASS
docker-compose.yml (Airflow 3.0.1 + DataHub v1.0.0) 13 pinned services (8 Airflow + 5 DataHub), isolated datahub DB, Kafka tx=1, 127.0.0.1 ports PASS
dags/medallion_governance_dag.py (Airflow 3 SDK AST) airflow.sdk.Asset, Deferrable S3KeySensor, .expand(), @task.short_circuit, 2 module DAGs, 0 sla/datetime.now/pickle PASS
orders_silver_contract.yaml (ODCS v3.1.0) & 01_governance_audit.sql 7 schema cols, 8/8 ODCS & 7/7 SQL checks PASS
Trình duyệt Mã nguồn 03-track-2-data-and-ai-engineering/part-02-data-engineering-and-lakehouse/labs/lab-11-airflow-datahub-governance-pipeline
docker-compose.yml 393 dòng
x-airflow-common: &airflow-common-env
  AIRFLOW__CORE__EXECUTOR: CeleryExecutor
  AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: "postgresql+psycopg2://${POSTGRES_USER:-airflow}:${POSTGRES_PASSWORD:-airflow_local_dev_only}@airflow-postgres:5432/${POSTGRES_DB:-airflow}"
  AIRFLOW__CELERY__BROKER_URL: "redis://airflow-redis:6379/0"
  AIRFLOW__CELERY__RESULT_BACKEND: "db+postgresql://${POSTGRES_USER:-airflow}:${POSTGRES_PASSWORD:-airflow_local_dev_only}@airflow-postgres:5432/${POSTGRES_DB:-airflow}"
  AIRFLOW__CORE__LOAD_EXAMPLES: "false"
  AIRFLOW__CORE__FERNET_KEY: "${AIRFLOW_FERNET_KEY:-ZnNkcy1sYWIxMS1kZXYtZmVybmV0LWtleS0zMmJ5dGU=}"
  AIRFLOW__API_AUTH__JWT_SECRET: "${AIRFLOW_JWT_SECRET:-fsds_local_dev_jwt_secret_only_32b}"
  _PIP_ADDITIONAL_REQUIREMENTS: "apache-airflow-providers-amazon>=9.0.0"

services:
  airflow-postgres:
    image: postgres:16.4-alpine
    container_name: fsds-gov-airflow-postgres
    environment:
      POSTGRES_USER: "${POSTGRES_USER:-airflow}"
      POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-airflow_local_dev_only}"
      POSTGRES_DB: "${POSTGRES_DB:-airflow}"
    ports:
      - "127.0.0.1:${AIRFLOW_PG_PORT:-5432}:5432"
    volumes:
      - airflow_pg_data:/var/lib/postgresql/data
      - ./sql/00_init_databases.sql:/docker-entrypoint-initdb.d/00_init_databases.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-airflow} -d ${POSTGRES_DB:-airflow}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1G
    networks:
      - governance_net

  airflow-redis:
    image: redis:7.4-alpine
    container_name: fsds-gov-airflow-redis
    command: ["redis-server", "--appendonly", "yes"]
    ports:
      - "127.0.0.1:${AIRFLOW_REDIS_PORT:-6379}:6379"
    volumes:
      - airflow_redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 5s
    deploy:
      resources:
        limits:
          cpus: "0.5"
          memory: 512M
    networks:
      - governance_net

  airflow-init:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-init
    command: ["db", "migrate"]
    restart: "no"
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
    environment:
      <<: *airflow-common-env
    deploy:
      resources:
        limits:
          cpus: "0.75"
          memory: 1G
    networks:
      - governance_net

  airflow-api-server:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-api-server
    command: ["api-server"]
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
      airflow-init:
        condition: service_completed_successfully
    environment:
      <<: *airflow-common-env
      AIRFLOW__CORE__EXECUTION_API_SERVER_URL: "http://airflow-api-server:8080/execution/"
    ports:
      - "127.0.0.1:${AIRFLOW_WEB_PORT:-8080}:8080"
    volumes:
      - ./dags:/opt/airflow/dags:ro
      - ./contracts:/opt/airflow/contracts:ro
      - ./sql:/opt/airflow/sql:ro
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:8080/api/v2/version || exit 1"]
      interval: 15s
      timeout: 5s
      retries: 6
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1536M
    networks:
      - governance_net

  airflow-dag-processor:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-dag-processor
    command: ["dag-processor"]
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
      airflow-init:
        condition: service_completed_successfully
    environment:
      <<: *airflow-common-env
      AIRFLOW__DAG_PROCESSOR__PARSING_PROCESSES: "2"
    volumes:
      - ./dags:/opt/airflow/dags:ro
      - ./contracts:/opt/airflow/contracts:ro
      - ./sql:/opt/airflow/sql:ro
    healthcheck:
      test: ["CMD-SHELL", "airflow jobs check --job-type DagProcessorJob --hostname $(hostname) || exit 1"]
      interval: 20s
      timeout: 10s
      retries: 5
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1G
    networks:
      - governance_net

  airflow-scheduler:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-scheduler
    command: ["scheduler"]
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
      airflow-init:
        condition: service_completed_successfully
    environment:
      <<: *airflow-common-env
      AIRFLOW__CORE__EXECUTION_API_SERVER_URL: "http://airflow-api-server:8080/execution/"
      AIRFLOW__SCHEDULER__ENABLE_HEALTH_CHECK: "true"
    volumes:
      - ./dags:/opt/airflow/dags:ro
      - ./contracts:/opt/airflow/contracts:ro
      - ./sql:/opt/airflow/sql:ro
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:8974/health || exit 1"]
      interval: 20s
      timeout: 10s
      retries: 5
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "1.5"
          memory: 1536M
    networks:
      - governance_net

  airflow-worker:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-worker
    command: ["celery", "worker"]
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
      airflow-init:
        condition: service_completed_successfully
    environment:
      <<: *airflow-common-env
      AIRFLOW__CORE__EXECUTION_API_SERVER_URL: "http://airflow-api-server:8080/execution/"
      AIRFLOW__CELERY__WORKER_CONCURRENCY: "8"
    volumes:
      - ./dags:/opt/airflow/dags:ro
      - ./contracts:/opt/airflow/contracts:ro
      - ./sql:/opt/airflow/sql:ro
    healthcheck:
      test: ["CMD-SHELL", "celery --app airflow.providers.celery.executors.celery_executor.app inspect ping -d celery@$(hostname) || exit 1"]
      interval: 20s
      timeout: 10s
      retries: 5
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "2.0"
          memory: 2G
    networks:
      - governance_net

  airflow-triggerer:
    image: apache/airflow:3.0.1-python3.12
    container_name: fsds-gov-airflow-triggerer
    command: ["triggerer"]
    depends_on:
      airflow-postgres:
        condition: service_healthy
      airflow-redis:
        condition: service_healthy
      airflow-init:
        condition: service_completed_successfully
    environment:
      <<: *airflow-common-env
      AIRFLOW__CORE__EXECUTION_API_SERVER_URL: "http://airflow-api-server:8080/execution/"
      AIRFLOW__TRIGGERER__DEFAULT_CAPACITY: "1000"
    volumes:
      - ./dags:/opt/airflow/dags:ro
    healthcheck:
      test: ["CMD-SHELL", "airflow jobs check --job-type TriggererJob --hostname $(hostname) || exit 1"]
      interval: 20s
      timeout: 10s
      retries: 5
      start_period: 25s
    deploy:
      resources:
        limits:
          cpus: "0.75"
          memory: 768M
    networks:
      - governance_net

  datahub-postgres-setup:
    image: postgres:16.4-alpine
    container_name: fsds-gov-datahub-pg-setup
    restart: "no"
    depends_on:
      airflow-postgres:
        condition: service_healthy
    environment:
      PGPASSWORD: "${POSTGRES_PASSWORD:-airflow_local_dev_only}"
    command:
      - "/bin/sh"
      - "-ec"
      - >-
        DB_EXISTS=$$(psql -v ON_ERROR_STOP=1 -h airflow-postgres -U "${POSTGRES_USER:-airflow}" -d "${POSTGRES_DB:-airflow}" -tAc "SELECT 1 FROM pg_database WHERE datname = '${DATAHUB_PG_DB:-datahub}'");
        if [ "$${DB_EXISTS}" != "1" ]; then
        psql -v ON_ERROR_STOP=1 -h airflow-postgres -U "${POSTGRES_USER:-airflow}" -d "${POSTGRES_DB:-airflow}" -c "CREATE DATABASE \"${DATAHUB_PG_DB:-datahub}\"";
        fi;
        psql -v ON_ERROR_STOP=1 -h airflow-postgres -U "${POSTGRES_USER:-airflow}" -d "${DATAHUB_PG_DB:-datahub}" -f /init/02_datahub_bootstrap.sql
    volumes:
      - ./sql/02_datahub_bootstrap.sql:/init/02_datahub_bootstrap.sql:ro
    deploy:
      resources:
        limits:
          cpus: "0.5"
          memory: 256M
    networks:
      - governance_net

  datahub-kafka:
    image: confluentinc/cp-kafka:7.6.1
    container_name: fsds-gov-datahub-kafka
    environment:
      KAFKA_NODE_ID: "1"
      KAFKA_PROCESS_ROLES: "broker,controller"
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT"
      KAFKA_LISTENERS: "PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093"
      KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://datahub-kafka:9092"
      KAFKA_INTER_BROKER_LISTENER_NAME: "PLAINTEXT"
      KAFKA_CONTROLLER_QUORUM_VOTERS: "1@datahub-kafka:9093"
      KAFKA_CONTROLLER_LISTENER_NAMES: "CONTROLLER"
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1"
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1"
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1"
      CLUSTER_ID: "FOn80WYVW4OPBvng2yU0rA"
    healthcheck:
      test: ["CMD-SHELL", "kafka-topics --bootstrap-server localhost:9092 --list || exit 1"]
      interval: 15s
      timeout: 10s
      retries: 6
      start_period: 25s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1536M
    networks:
      - governance_net

  datahub-elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.15.3
    container_name: fsds-gov-datahub-es
    environment:
      discovery.type: single-node
      xpack.security.enabled: "false"
      ES_JAVA_OPTS: "-Xms512m -Xmx512m"
    volumes:
      - datahub_es_data:/usr/share/elasticsearch/data
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:9200/_cluster/health || exit 1"]
      interval: 15s
      timeout: 5s
      retries: 6
      start_period: 25s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1536M
    networks:
      - governance_net

  datahub-gms:
    image: acryldata/datahub-gms:v1.0.0
    container_name: fsds-gov-datahub-gms
    depends_on:
      airflow-postgres:
        condition: service_healthy
      datahub-postgres-setup:
        condition: service_completed_successfully
      datahub-kafka:
        condition: service_healthy
      datahub-elasticsearch:
        condition: service_healthy
    environment:
      EBEAN_DATASOURCE_DRIVER: "org.postgresql.Driver"
      EBEAN_DATASOURCE_HOST: "airflow-postgres:5432"
      EBEAN_DATASOURCE_URL: "jdbc:postgresql://airflow-postgres:5432/${DATAHUB_PG_DB:-datahub}"
      EBEAN_DATASOURCE_USERNAME: "${POSTGRES_USER:-airflow}"
      EBEAN_DATASOURCE_PASSWORD: "${POSTGRES_PASSWORD:-airflow_local_dev_only}"
      KAFKA_BOOTSTRAP_SERVER: "datahub-kafka:9092"
      ELASTICSEARCH_HOST: datahub-elasticsearch
      ELASTICSEARCH_PORT: "9200"
    ports:
      - "127.0.0.1:${DATAHUB_GMS_PORT:-8082}:8080"
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:8080/health || exit 1"]
      interval: 20s
      timeout: 5s
      retries: 6
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "1.5"
          memory: 2G
    networks:
      - governance_net

  datahub-frontend:
    image: acryldata/datahub-frontend-react:v1.0.0
    container_name: fsds-gov-datahub-frontend
    depends_on:
      datahub-gms:
        condition: service_healthy
    environment:
      DATAHUB_GMS_HOST: datahub-gms
      DATAHUB_GMS_PORT: "8080"
    ports:
      - "127.0.0.1:${DATAHUB_UI_PORT:-9002}:9002"
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:9002/admin || exit 1"]
      interval: 20s
      timeout: 5s
      retries: 6
      start_period: 30s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1G
    networks:
      - governance_net

networks:
  governance_net:
    driver: bridge

volumes:
  airflow_pg_data:
  airflow_redis_data:
  datahub_es_data:
KIỂM TRA NĂNG LỰC TƯƠNG TÁC

Quiz Chẩn đoán & Hệ thống Gợi ý Bài tập

Tự kiểm tra 8 câu hỏi trọng tâm kèm giải thích công thức toán học và xem gợi ý từng bước cho 6 Bài tập Trụ cột 5.

Điểm hiện tại 0 / 8
Câu 1 • Pipeline Idempotency: Atomic Partition Overwrite vs. Non-Idempotent Cron Append
Trên tập thực nghiệm 7 ngày \(\times\) 400 đơn (2,800 đơn hàng, 299,524.31 USD) của Lab 11 (test_03), chuyện gì xảy ra khi tác vụ phân vùng 2026-10-04 (400 đơn, 43,290.30 USD) gặp sự cố và chạy lại 1 lần bằng INSERT INTO thô so với Atomic Partition Swap (DELETE + INSERT)?
Câu 2 • Deterministic Backfills: Airflow logical_date ds vs. Wall-Clock datetime.now()
Khi chạy backfill lịch sử 7 ngày (2026-10-01 đến 2026-10-07) vào ngày 2026-10-10 qua AIP-78 (test_04), vì sao gọi datetime.now() hoặc đặt tham số TaskFlow tên logical_date: str = "{{ ds }}" lại gây lỗi?
Câu 3 • Airflow 3 Data Passing: Object-Store URI Pointers and Task Execution API
Trong Airflow 3.x (Lab 11, test_05), vì sao việc trả về trực tiếp lô 50,000 đơn hàng qua XCom làm nghẽn hệ thống và mẫu kiến trúc Task Execution API (AIP-72) xử lý việc giao tiếp từ Worker thế nào?
Câu 4 • Airflow 3.x Triggerer, Deadline Alerts and Durable Execution Comparison
Trên bể 16 worker slots với 48 shard chờ 600s (test_06), DeferrableOperator và Deadline Alerts (Airflow 3.1) vận hành ra sao, và khi nào cần chuyển sang Temporal / Restate thay vì Airflow?
Câu 5 • Data Validation Frameworks and Zero-Copy Iceberg WAP Branching
Nhận định kỹ thuật nào ĐÚNG nhất khi kết hợp bộ ba xác thực (Pandera, Great Expectations, SodaCL) với kiến trúc zero-copy Apache Iceberg Write–Audit–Publish (WAP) trên Apache Polaris (1.x)?
Câu 6 • ODCS v3.1.0 Data Contracts and Short-Circuit Quarantine Gate
Trong Lab 11 (Tests 07–10, 13b), hợp đồng ODCS v3.1.0 (schema[].properties[], quality[], slaProperties[]) kết hợp @task.short_circuit phản ứng thế nào trước lỗi Schema Drift, 18 đơn âm, đơn > 500,000 USD, Null Spike 12.5% và trễ 47 phút?
Câu 7 • DataHub v1.0+ Column Lineage, OpenLineage Facets and RLS/DDM Separation
Trên đồ thị phả hệ DataHub v1.0+ (22 cột / 17 cạnh, Tests 11–12), thuật toán lan truyền PII hoạt động ra sao và thành phần nào chịu trách nhiệm thực thi RLS/DDM runtime khi dùng Apache Polaris?
Câu 8 • Part 2 Mini Coursework Integration and Airflow 3.0.1 Stack Audits
Để hoàn thành Mini Coursework Phần 2 (Ch 07 -> Ch 12) và vượt qua kiểm toán tĩnh infra_audit.py của Lab 11 (Tests 14–17), hệ thống phải xác minh tập bất biến nào?

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 Tính Bất biến và Backfill theo logical_date 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)

Viết điều kiện \(f^{(k)}(D_t) \equiv f(D_t)\), giải thích vì sao phải dùng tham số ds thay cho logical_date: str trong TaskFlow Airflow 3, và đối chiếu cách DELETE + INSERT theo partition_dt ngăn cộng đúp khi retry.

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy pytest -k "test_03 or test_04" -v và đối chiếu mục idempotency_replay_audit và logical_date_backfill_audit trong artifacts/t2_ch12_lab11_results.json.

Tiêu chí Đáp án & Số đối chứng

Retry 1 phân vùng bằng INSERT thô gây +100.0% double-count (800 vs 400 dòng, 86,580.60 vs 43,290.30 USD) và +57.95% theo tuần (4,400 dòng); Atomic Swap giữ 2,800 dòng với 0.0 USD sai lệch. Dùng datetime.now() làm 0/7 phân vùng lịch sử có dữ liệu (2,800 dòng đổ nhầm sang 2026-10-10), còn ds/logical_date đạt 7/7 (100.0%).

Bài tập 2 — Truyền dữ liệu XCom URI và Kiến trúc Airflow 3 Triggerer 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)

So sánh kích thước gói JSON 50,000 dòng với trần 48 KB qua Task Execution API (AIP-72), cơ chế DeadlineAlert (3.1) thay SLA trên Triggerer, và ranh giới chọn Temporal/Restate cho AI Agent dài ngày.

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy pytest -k "test_05 or test_06" -v và đọc hàm run_xcom_and_sensor_concurrency_benchmark trong src/orchestration_governance_lab/dag_and_backfill_engine.py.

Tiêu chí Đáp án & Số đối chứng

Raw JSON XCom tốn 6,304,985 B (6.013 MB) so với ObjectStore URI 63 B (100,079.1x nhỏ hơn). Cảm biến poke chiếm 16/16 (100.0%) worker slots, dồn 32 hàng đợi và đốt 28,800 slot-giây; deferrable=True giữ 0/16 (0.0%) worker slots với 48 coroutines trong Triggerer.

Bài tập 3 — Hợp đồng Dữ liệu ODCS v3.1.0 và Ngắt mạch Circuit Breaker 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)

Đối chiếu Pandera, Great Expectations và SodaCL kết hợp zero-copy Iceberg WAP + Apache Polaris, rồi phân tích cách @task.short_circuit kiểm tra schema[].properties[] (customer_id required: false) và quality[] (amount_usd_min/amount_usd_max).

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy pytest -k "test_07 or test_08 or test_09 or test_10 or test_13" -v để xem các kịch bản lỗi (excessive_amount > 500k USD, null_spike không lẫn SCHEMA_DRIFT) và kiểm định Hypothesis.

Tiêu chí Đáp án & Số đối chứng

Không có ngắt mạch đẩy 8,000 dòng bẩn xuống Gold (100% ô nhiễm); Contract Circuit Breaker ODCS v3.1.0 bắt trọn Schema Drift, 18 đơn < 0.01, đơn > 500,000.0 USD, Null Spike 12.5% (với schema_violations=0), SLA 47m > 30m, cách ly sang quarantine_orders_dead_letter và bảo toàn 0 dòng ô nhiễm Gold (0.0%).

Bài tập 4 — Phả hệ DataHub, OpenLineage Iceberg và Phân tách RLS DDM 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)

Theo dõi luồng MCP -> Kafka -> GMS (PG Ebean) -> Elasticsearch kèm OpenLineage 1.x Iceberg ScanReport/CommitReport facets, điều kiện dừng PII tại SHA256_DOMAIN_MASK, và vai trò Polaris vs Unity Catalog vs Trino + Ranger/OPA.

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy pytest -k "test_11 or test_12" -v và kiểm tra các khóa trong datahub_column_lineage_impact của tệp artifacts JSON.

Tiêu chí Đáp án & Số đối chứng

Đồ thị 22 cột / 17 cạnh qua 5 tầng phủ 9/9 (100.0%) thẻ PII/Financial hạ lưu và dừng chính xác tại flink.customer_risk_1h#email_domain_hash; sửa gross_amount_cents đánh trúng 4 cột trên 4 datasets (Iceberg, Flink, ClickHouse, Feast) và 4 đội. Polaris vend credentials, nhường thực thi RLS/DDM cho engine như Trino + Ranger/OPA.

Bài tập 5 — Kiểm toán Hạ tầng Airflow 3 và DataHub cùng Bảo mật AST 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)

Rà soát 13 dịch vụ trong docker-compose.yml (8 Airflow + 5 DataHub gồm datahub-postgres-setup, 00_init_databases.sql + 02_datahub_bootstrap.sql tách DB datahub, Kafka Tx=1, 127.0.0.1:), tách try/except cho S3KeySensor, và 4 hàm kiểm toán trong infra_audit.py + ruff --select AIR.

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy pytest -k "test_01 or test_14 or test_15 or test_16" -v và đối chiếu sql/01_governance_audit.sql.

Tiêu chí Đáp án & Số đối chứng

docker-compose.yml đạt 13 dịch vụ pin tag (8 Airflow + 5 DataHub gồm datahub-postgres-setup), tách riêng DB datahub (00_init_databases.sql + 02_datahub_bootstrap.sql), Kafka Tx=1, Fernet 32B, KRaft 22-char, 127.0.0.1:; AST medallion_governance_dag.py tách riêng airflow.sdk và S3KeySensor, đạt Asset, @task.short_circuit, 2 DAGs; YAML (8/8) và SQL (7/7, customer_id nullable) đều PASS.

Bài tập 6 — Đề án Mini Coursework Phần 2 Tích hợp Ch 07 đến Ch 12 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)

Lập sơ đồ kết nối Lab 06 (Kafka CDC) -> Lab 07 (Iceberg WAP/Polaris) -> Lab 08/09 (Spark/Flink) -> Lab 10 (ClickHouse/Feast) -> Lab 11 (Airflow 3/DataHub v1.0) theo Checklist §2.2.

Gợi ý Bước 2 (Chi tiết Kỹ thuật)

Chạy đầy đủ scripts/run_lab_demo.py, ruff check src tests scripts dags, ruff check --select AIR dags, mypy src, và pytest -p no:cacheprovider -v.

Tiêu chí Đáp án & Số đối chứng

Hoàn thành lộ trình 2 tuần tích hợp 5 chặng Phần 2, sinh artifacts/t2_ch12_lab11_results.json (6 KPI, 4 Bar, 4 Table, 6 spans OTel), 24/24 test cases xanh (0 skip), 0 lỗi ruff (AIR30x) / mypy, và 0 tệp .parquet/.duckdb* rác.