IIT Madras Zanzibar · Teaching

← Z5008 Overview

Lab Explorer & Spark/Lakehouse Previews

Interactive code browser for Z5008 Lakehouse, PySpark SQL, Airflow DAG orchestration, Structured Streaming, MLlib, MLflow Registry, and Prometheus observability labs.

Labs 1–3Columnar pruning · _delta_log snapshot isolation

Lakehouse Parquet Partitioning & Delta Log

Simulates date-partitioned Parquet layout, Delta JSON commit entries, and versioned time travel.

Python Preview
from dataclasses import dataclass, asdict
import json
from pathlib import Path
import tempfile
from typing import Any


@dataclass(frozen=True)
class TxRecord:
    tx_id: str
    region: str
Labs 4–5RANK(), running totals · SQLite window fallback

Spark SQL DataFrames & Window Ranking

Runs PySpark SQL window ranking and cumulative revenue aggregations with pure-Python/SQLite fallback.

Python Preview
import sqlite3
from typing import Any


def spark_or_sqlite_window_analytics(orders: list[tuple[str, str, float, str]]) -> list[tuple[Any, ...]]:
    """Execute RANK and running cumulative sum across region partitions via PySpark or SQLite fallback."""
    try:
        from pyspark.sql import SparkSession, Window
        import pyspark.sql.functions as F

        spark = SparkSession.builder.master("local[2]").appName("Z5008-BD02").getOrCreate()
Labs 7–8Event-time tumbling windows · Late-event eviction

Spark Structured Streaming & Watermarks

Processes out-of-order sensor streams with configurable watermarks and late-drop counters.

Python Preview
from collections import defaultdict


def process_event_stream(
    events: list[tuple[int, str, float]],
    window_size: int = 10,
    watermark_delay: int = 5,
) -> tuple[dict[tuple[int, str], float], list[tuple[int, str, float]]]:
    """Process (event_time_sec, key, amount) events using watermark = max_event_time - delay."""
    max_event_time = 0
    window_sums: dict[tuple[int, str], float] = defaultdict(float)
Labs 10–11Estimator/Transformer pipelines · Precision/F1

Distributed ML Pipelines & CV Tuning

Constructs leakage-free MLlib-style feature pipelines and compares cross-validated tree models.

Python Preview
import json
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


def run_ml_experiment(c_reg: float, seed: int = 5008) -> dict[str, float]:
    """Train leakage-free Pipeline and return logged parameters and evaluation metrics."""
Labs 13–15Counter, Gauge & p50/p95/p99 Histogram formatting

Pipeline Telemetry & Prometheus Metrics

Computes interpolated latency quantiles and renders Prometheus text exposition output.

Python Preview
import math
import random


def percentile(values: list[float], p: float) -> float:
    """Compute linear-interpolated p-th percentile (0 <= p <= 100)."""
    if not values:
        raise ValueError("values must be non-empty")
    s = sorted(values)
    k = (len(s) - 1) * (p / 100.0)
    f, c = math.floor(k), math.ceil(k)
Lab 6Topological DAG · Idempotent retries & XComs

Airflow Workflow Orchestration & SLAs

Detects cycles via Kahn topological sort, tracks retry attempts, passes XCom URIs, and flags SLA misses.

Python Preview
from collections import deque
from dataclasses import dataclass, field
from typing import Callable


@dataclass
class TaskNode:
    """Declarative workflow task mirroring an Apache Airflow operator."""

    task_id: str
    fn: Callable[[dict[str, object]], object]
Labs 11–12SQLite run store · Staging -> Production gates

MLflow Experiment Tracking & Registry Gates

Logs parameters and F1/AUC metrics, ranks runs, and enforces threshold gates before Production promotion.

Python Preview
import json
import sqlite3
import tempfile
from pathlib import Path


class LocalModelRegistry:
    """SQLite-backed experiment tracker and staged model registry (Staging -> Production -> Archived)."""

    VALID_STAGES = {"None", "Staging", "Production", "Archived"}