Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

GitHub Activity Lakehouse

An incremental Spark Structured Streaming pipeline that ingests GH Archive events into Delta Lake bronze / silver / gold tables, with per-stream checkpointing and idempotent MERGE upserts for exactly-once recovery. Backfilled 131M events (four weeks of GH Archive, January 1–28 2024) on a single 8-core machine, and keeps up hour by hour afterwards, processing only what is new.


Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     GH Archive (data.gharchive.org)                  β”‚
β”‚              Hourly .json.gz  ~50 MB/file  (NDJSON format)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚  download_gharchive()
                               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  data/raw/   2024-01-15-0.json.gz, 2024-01-15-1.json.gz, ...        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚  stream 1: bronze_ingest
                               β”‚  file source Β· maxFilesPerTrigger Β· ckpt/bronze
                               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  BRONZE  data/bronze/   (Delta Lake, partitioned by date)            β”‚
β”‚  β€’ Verbatim event in _raw_json + id, type, created_at, _source_file  β”‚
β”‚  β€’ Insert-only MERGE on id β†’ append-only, never duplicated           β”‚
β”‚  β€’ Malformed lines β†’ quarantine/bronze (txnAppId/txnVersion append)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚  stream 2: silver_transform
                               β”‚  Delta source Β· ckpt/silver
                               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  SILVER  data/silver/   (Delta Lake, partitioned by date, CDF on)    β”‚
β”‚  β€’ Explicit PySpark schema applied (GH_EVENT_SCHEMA)                 β”‚
β”‚  β€’ Upsert MERGE on id, pruned to the batch's date partitions         β”‚
β”‚  β€’ Computed columns: date, repo_name, actor_login, event_type        β”‚
β”‚  β€’ Data-quality checks + quarantine for bad records                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚  stream 3: gold_incremental           β”‚
                     β”‚  Change Data Feed Β· ckpt/gold         β”‚
                     β”‚  recompute touched keys β†’ MERGE       β”‚
                     β–Ό                                       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”               β”‚
β”‚  GOLD  data/gold/   (Delta Lake)           β”‚               β”‚
β”‚  β€’ daily_active_repos/                     β”‚   DQ checks   β”‚
β”‚  β€’ pr_merge_time/                          β”‚  data/quarantine/
β”‚  β€’ top_growing_repos/                      β”‚               β”‚
β”‚  β€’ contributor_retention/                  β”‚               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β”‚

Project Structure

github-activity-lakehouse/
β”œβ”€β”€ .github/workflows/ci.yml     # GitHub Actions CI (Python 3.11, Java 11)
β”œβ”€β”€ conf/config.py               # Central configuration (paths, settings)
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ pipeline.py              # Orchestrates the 3 streams (availableNow / continuous)
β”‚   β”œβ”€β”€ bronze/ingest.py         # Raw files β†’ Bronze stream (insert-only MERGE)
β”‚   β”œβ”€β”€ silver/schema.py         # Explicit GH event StructType
β”‚   β”œβ”€β”€ silver/transform.py      # Bronze β†’ Silver stream (upsert MERGE, CDF)
β”‚   β”œβ”€β”€ silver/dq.py             # Data quality checks + quarantine
β”‚   β”œβ”€β”€ gold/aggregations.py     # Gold table definitions + batch rebuild
β”‚   β”œβ”€β”€ gold/incremental.py      # Silver CDF β†’ Gold stream (scoped recompute MERGE)
β”‚   β”œβ”€β”€ utils/streaming.py       # Triggers, idempotent MERGE / append helpers
β”‚   └── utils/spark_session.py   # SparkSession factory with Delta config
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ conftest.py              # Shared pytest fixtures (spark, sample_df)
β”‚   β”œβ”€β”€ fixtures/sample_events.json  # 10 realistic fake GH events
β”‚   β”œβ”€β”€ test_bronze.py
β”‚   β”œβ”€β”€ test_silver.py
β”‚   β”œβ”€β”€ test_gold.py
β”‚   └── test_streaming.py        # Incremental runs + crash/replay recovery
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ download_data.py         # CLI to download GH Archive files
β”‚   └── run_pipeline.py          # CLI to run pipeline stages
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Makefile
└── README.md

Quick Start

# 1. Clone the repo
git clone https://github.com/saisha-l/github-activity-lakehouse-.git github-activity-lakehouse
cd github-activity-lakehouse

# 2. Install dependencies (requires Python 3.11, Java 17)
make install

# 3. Download 3 days of data (72 hourly files)
make download

# 4. Run the incremental pipeline (processes only new data, then exits)
make pipeline

# Four-week backfill (2024-01-01..28, ~131M events, ~70 GB of Delta tables).
# Downloads 3 days at a time and deletes raw files once ingested; override
# the window with BACKFILL_START / BACKFILL_END
SPARK_DRIVER_MEMORY=12g make backfill

Backfill results (131M events)

make backfill over 2024-01-01 β†’ 2024-01-28 on one 8-core / 30 GB machine (local Spark 3.5.1, Delta 3.1.0, Java 17):

Table Rows
bronze 131,170,447
silver 131,170,447
gold/daily_active_repos 21,898,681
gold/contributor_retention 5,035,240
gold/pr_merge_time 2,910,093
gold/top_growing_repos 1,820,944
  • Data quality: 0 % null ids, 0 % duplicates, no schema drift, 0 quarantined rows.
  • ~28 min per 3-day chunk (~13M events); ~6 h end to end. Bronze ingests ~14k events/s.
  • Storage: ~0.54 GB per million events for Bronze + Silver with zstd (Bronze keeps every event's raw JSON).
  • The run was interrupted six times (four out-of-memory crashes, two deliberate restarts) and resumed from its checkpoints each time; Bronze and Silver still match row for row with no duplicates, i.e. exactly-once in practice.

Tuning knobs that matter at this scale (environment variables, see conf/config.py):

Variable Default Why
SPARK_DRIVER_MEMORY 4g Local mode runs everything in the driver JVM; 12g was used above.
MAX_FILES_PER_TRIGGER 24 Raw files per Bronze micro-batch; 8 (one per core) was used above.
SILVER_MAX_FILES_PER_TRIGGER 3 Bronze files (~600k events each) per Silver micro-batch.
RAW_CLEAN_SOURCE off delete removes raw files after their batch commits (make backfill sets it).
SPARK_PARQUET_CODEC zstd Half the size of snappy for Bronze's raw JSON.
SPARK_PARQUET_BLOCK_SIZE_MB 32 Raw JSON expands ~8x on read; 128 MB row groups need ~1 GB heap per task.
SPARK_LOCAL_CORES * Fewer cores = more memory per task when replaying an oversized batch.

Manual pipeline run

# Download a specific date range
PYTHONPATH=. python scripts/download_data.py --start 2024-01-01 --end 2024-01-07

# Incremental: drain whatever is new through all three streams, then exit.
# Re-run after every download (cron / Airflow / Databricks Job).
PYTHONPATH=. python scripts/run_pipeline.py --streaming --bronze --silver --gold --stats

# Long-running: all three streams concurrently, 1-minute micro-batches
PYTHONPATH=. python scripts/run_pipeline.py --streaming --bronze --silver --gold \
    --trigger-interval "1 minute"

# Batch full rebuild / repair (idempotent; does not touch checkpoints)
PYTHONPATH=. python scripts/run_pipeline.py --bronze --silver --dq --gold

Incremental Processing & Exactly-Once Recovery

Stream Source Sink write Checkpoint
bronze_ingest data/raw/ file source (maxFilesPerTrigger, default 24 = 1 day) MERGE … WHEN NOT MATCHED INSERT on id checkpoints/bronze
silver_transform Bronze Delta table MERGE upsert on id, update only if _ingested_at is newer checkpoints/silver
gold_incremental Silver Change Data Feed recompute touched keys β†’ MERGE (update / insert / delete-stale) checkpoints/gold

Why it's exactly-once. Structured Streaming checkpoints record each micro-batch's source offsets before it runs and a commit marker after it finishes. If the job dies between the Delta commit and the checkpoint commit, the restart replays the same batch with the same input. Every sink write is idempotent, so the replay changes nothing:

  • Bronze: insert-only MERGE, so already-present ids are skipped. Delta runs an insert-only merge as a pure append, so Bronze stays a valid append-only streaming source. Quarantine appends carry txnAppId/txnVersion=batchId, and Delta drops a write whose version it has already committed.
  • Silver: matched rows update only when source._ingested_at > target._ingested_at. A replay matches every row and updates none.
  • Gold: each batch recomputes the affected (date, repo), event_id, repo and actor slices from Silver with the same functions as the batch rebuild, then MERGEs them in. The output is a pure function of Silver, so a replay rewrites identical values.

tests/test_streaming.py checks this directly. It deletes the newest commits/<id> file from each checkpoint (a crash after the sink commit), restarts, and asserts the tables are unchanged. It also checks that incrementally maintained Gold equals a full batch rebuild.

Scaling notes

  • GH Archive files are gzip and can't be split (one task per file). maxFilesPerTrigger bounds each micro-batch, so memory stays flat however long the backlog is.
  • MERGE conditions include a literal date IN (...) predicate built from the batch, so Delta prunes the target down to the 1–2 partitions a batch touches instead of scanning the whole 100M+ row table.
  • Downloads land as hidden .part files and are renamed atomically, so the file stream never reads a half-written file.
  • On first start the Gold CDF stream reads the full Silver snapshot, so no separate Gold backfill is needed.

Layer Details

Bronze β€” Raw Ingestion

  • Source: GH Archive NDJSON files downloaded to data/raw/
  • Reader: readStream.format("text") with a checkpoint, so each file is read once
  • Writer: foreachBatch β†’ insert-only MERGE on id (pruned by date)
  • Output: Delta table at data/bronze/, partitioned by date
  • Columns: id, type, created_at, date, _raw_json (verbatim event), _source_file, _ingested_at
  • Bad lines: no id / created_at β†’ data/quarantine/bronze/

Silver β€” Clean & Typed

  • Source: Bronze Delta table (streaming source)
  • Writer: foreachBatch β†’ MERGE INTO on id, so late duplicates, reruns and replays are idempotent
  • Change Data Feed: enabled (delta.enableChangeDataFeed=true) to drive incremental Gold
  • Output: Delta table at data/silver/, partitioned by date
  • Transforms: explicit GH_EVENT_SCHEMA applied, computes repo_name, actor_login, event_type, adds _processed_at
  • DQ checks: null_rate, schema drift, row count, duplicate rate, quarantine of bad records

Gold β€” Aggregations

Maintained incrementally by gold/incremental.py. make rebuild recomputes everything in batch from the same definitions.

Table Description
daily_active_repos Events per repo per day + distinct actor count
pr_merge_time Hours from PR creation to merge for merged PRs (keyed by event_id)
top_growing_repos WatchEvent (star) counts per week + week-over-week growth
contributor_retention Actors active in 2+ consecutive weeks flagged as retained

Performance Tuning

Z-Ordering

Apply Z-ordering on the most common query predicates to co-locate related data:

OPTIMIZE delta.`data/silver/` ZORDER BY (repo_name, actor_login);
OPTIMIZE delta.`data/gold/daily_active_repos/` ZORDER BY (repo_name);

Adaptive Query Execution (AQE)

AQE is enabled by default in this project (spark.sql.adaptive.enabled=true). It handles:

  • Coalescing shuffle partitions β€” avoids thousands of tiny partitions after joins
  • Skew join handling β€” automatically splits oversized partitions from repos like torvalds/linux

Skew Handling

GH Archive data is inherently skewed β€” a handful of popular repos (e.g. microsoft/vscode) generate orders of magnitude more events than average repos. Mitigations:

  • spark.sql.adaptive.skewJoin.enabled=true (default in this project)
  • Salt the join key with F.concat(F.col("repo_name"), (F.rand() * 10).cast("int")) for heavy aggregations on repo_name
  • Use broadcast joins for small lookup tables (< 10 MB)

Partitioning Strategy

  • Bronze / Silver: partitioned by date β€” typical queries filter by date range
  • Gold: most Gold tables are small enough to skip partitioning; daily_active_repos is partitioned by date for time-range queries

Shuffle Partitions

Override via env var: SPARK_SHUFFLE_PARTITIONS=400 make pipeline
Default is 200 for single-node; increase to 8 Γ— num_cores for cluster mode.


Data Quality

The run_dq_checks() function in src/silver/dq.py validates:

Check Threshold Action on failure
null_rate < 5% null ids Raises DataQualityError
schema_drift All expected columns present Warning logged
row_count > 0 Warning logged
duplicate_rate Informational Logged
Quarantine null id or null created_at Written to data/quarantine/

Adjust the threshold: conf/config.py β†’ DQ_NULL_RATE_THRESHOLD.


Testing

# Full test suite
make test

# Specific test module
PYTHONPATH=. pytest tests/test_silver.py -v

# With detailed output on failure
PYTHONPATH=. pytest tests/ -v --tb=long

Tests use tmp_path fixtures so they never pollute data/.

Test coverage

  • Bronze: audit columns, date partitioning, dedup, idempotent rerun, null-id quarantine, raw JSON retained
  • Streaming: only new files are read, cross-file dedup, in-flight downloads ignored, crash-replay idempotency for Bronze / Silver / Gold, incremental Gold == batch rebuild
  • Silver: global dedup, MERGE idempotency, derived columns, date extraction, DQ null-rate detection, quarantine
  • Gold: daily_active_repos row uniqueness, pr_merge_time merged-only filter, top_growing_repos star counts, contributor retention logic

How to Run on Databricks

  1. Upload the project to your Databricks workspace (or clone via Repos).

  2. Create a cluster with:

    • Databricks Runtime 14.x LTS (includes Spark 3.5 + Delta 3.x)
    • Python 3.11
  3. Install extra libraries (only tqdm and requests are needed on Databricks β€” PySpark and Delta are pre-installed):

    tqdm==4.66.4
    requests==2.32.3
    
  4. Set environment variables in the cluster config:

    LAKEHOUSE_ROOT=dbfs:/mnt/github-lakehouse
    
  5. Run the pipeline via a Databricks Job or notebook:

    import sys
    sys.path.insert(0, "/Workspace/Repos/your-repo/github-activity-lakehouse")
    
    from src.utils.spark_session import get_spark
    from src.pipeline import run_incremental_pipeline
    
    spark = get_spark(local=False)  # use existing Databricks cluster session
    run_incremental_pipeline(spark)   # bronze β†’ silver β†’ gold, availableNow
  6. Optimise with Delta features:

    spark.sql("OPTIMIZE delta.`dbfs:/mnt/github-lakehouse/silver/` ZORDER BY (repo_name, date)")
    spark.sql("VACUUM delta.`dbfs:/mnt/github-lakehouse/silver/` RETAIN 168 HOURS")

Why I built this

I wanted to work with data engineering tools and Medallion architecture in practice.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages