# NAIT enrolment pathways ยท annual publication # Copy history.csv, cohorts.csv and manifest.json from one extractor run into this folder. landing_folder = "Files/nait_pathways" import csv import hashlib import io import json import re from datetime import date from pathlib import Path from urllib.parse import urlparse from pyspark.sql import functions as F from pyspark.sql.types import IntegerType, StringType, StructField, StructType lakehouse_mount = Path("/lakehouse/default") history_fields = ["cohort_end_year", "lookback_years", "institution_code", "institution_name", "learners", "source_url"] cohort_fields = ["cohort_end_year", "cohort_size", "source_url"] numeric_fields = {"cohort_end_year", "lookback_years", "learners", "cohort_size"} def read_extract(landing, name, fields): # An entire annual package is a few thousand aggregate cells and fits on the driver. # Take immutable byte snapshots so all Spark actions use the exact files fingerprinted. contents = (landing / (name + ".csv")).read_bytes() reader = csv.reader(io.StringIO(contents.decode("utf-8-sig"), newline=""), strict=True) if next(reader, None) != fields: raise ValueError(f"{name}.csv: expected columns {fields}") values = [] for record in reader: if len(record) != len(fields): raise ValueError(f"{name}.csv: wrong field count at line {reader.line_num}") row = [] for column, original in zip(fields, record): value = original.strip() if column == "learners" and value == "": row.append(None) elif column in numeric_fields: if not re.fullmatch(r"[0-9]{1,9}", value): raise ValueError(f"{name}.csv: invalid integer {column} on line {reader.line_num}") row.append(int(value)) else: if not value: raise ValueError(f"{name}.csv: blank {column} on line {reader.line_num}") if column == "source_url": url = urlparse(value) if (url.scheme != "https" or url.netloc != "acat.alberta.ca" or not url.path.startswith("/media/") or not url.path.lower().endswith(".pdf") or url.query or url.fragment): raise ValueError(f"{name}.csv: unrecognised ACAT report URL on line {reader.line_num}") row.append(value) values.append(tuple(row)) if not values: raise ValueError(f"{name}.csv: empty input") schema = StructType([StructField(column, IntegerType() if column in numeric_fields else StringType(), column == "learners") for column in fields]) return spark.createDataFrame(values, schema), hashlib.sha256(contents).hexdigest() # Checks before publication def require_empty(df, message): example = df.take(1) if example: raise ValueError(f"{message}: {example[0].asDict()}") def validate(history, cohorts, manifest): by_year = cohorts.orderBy("cohort_end_year").collect() years = [r.cohort_end_year for r in by_year] if (len(years) != 10 or years[-1] > date.today().year + 1 or years != list(range(years[0], years[-1] + 1))): raise ValueError(f"Cohorts must contain exactly ten consecutive academic years: {years}") if min(r.cohort_size for r in by_year) < 1 or len({r.source_url for r in by_year}) != len(years): raise ValueError("Each cohort requires a positive denominator and its own ACAT report URL") sources = manifest["sources"] if not isinstance(sources, list) or sorted(row["cohort_end_year"] for row in sources) != years: raise ValueError("Manifest years differ from the published cohorts") controls = {row["cohort_end_year"]: row for row in sources} for cohort in by_year: control = controls[cohort.cohort_end_year] if (control["cohort_size"] != cohort.cohort_size or control["headcount_control"] != cohort.cohort_size or control["source_url"] != cohort.source_url or not re.fullmatch(r"[0-9a-f]{64}", control["sha256"])): raise ValueError(f"Manifest source or denominator differs for {cohort.cohort_end_year}") # The join also verifies that each cell cites its own cohort's source report. joined = history.join(cohorts.withColumnRenamed("source_url", "cohort_source"), "cohort_end_year", "left") invalid = (F.col("cohort_size").isNull() | (F.col("source_url") != F.col("cohort_source")) | ~F.col("lookback_years").between(0, 5) | ~F.col("institution_code").rlike(r"^[A-Z0-9]+$") | (F.col("learners") > F.col("cohort_size"))) require_empty(joined.where(invalid), "Invalid cohort, lookback, code, source or count") grouped = (history.groupBy("cohort_end_year", "institution_code") .agg(F.count("*").alias("cells"), F.countDistinct("lookback_years").alias("lags"), F.countDistinct("institution_name").alias("names"))) require_empty(grouped.where((F.col("cells") != 6) | (F.col("lags") != 6) | (F.col("names") != 1)), "Missing/duplicate lookback or inconsistent institution name") names = history.select("institution_code", "institution_name").distinct().collect() if len({row.institution_code for row in names}) != len(names) or len({row.institution_name for row in names}) != len(names): raise ValueError("A canonical institution code maps to multiple names, or a name to multiple codes") profile = history.where((F.col("institution_code") == "NA") & (F.col("lookback_years") == 0)) require_empty(cohorts.join(profile.select("cohort_end_year", "learners"), "cohort_end_year", "left") .where(F.col("learners").isNull() | (F.col("learners") != F.col("cohort_size"))), "NAIT's current-year count must match every printed cohort size") for row in grouped.groupBy("cohort_end_year").agg(F.count("*").alias("institutions"), F.sum("cells").alias("observations")).collect(): control = controls[row.cohort_end_year] if row.institutions < 2 or row.institutions != control["institution_count"] or row.observations != control["observation_count"]: raise ValueError(f"Roster or observation count differs from manifest for {row.cohort_end_year}") return years # Publish both table grains def latest_release(table): if not spark.catalog.tableExists(table): return None first = spark.sql(f"DESCRIBE HISTORY {table} LIMIT 1").select("userMetadata").first() if not first or not first.userMetadata: return None return json.loads(first.userMetadata).get("release_id") def publish(): landing = lakehouse_mount / landing_folder history, h_hash = read_extract(landing, "history", history_fields) cohorts, c_hash = read_extract(landing, "cohorts", cohort_fields) manifest_bytes = (landing / "manifest.json").read_bytes() provenance = json.loads(manifest_bytes) manifest_hash = hashlib.sha256(manifest_bytes).hexdigest() if provenance["files"] != {"cohorts.csv": c_hash, "history.csv": h_hash}: raise ValueError("Landing CSVs do not match the release manifest SHA-256") years = validate(history, cohorts, provenance) release = hashlib.sha256((h_hash + c_hash + manifest_hash).encode("ascii")).hexdigest() audit = dict(release_id=release, history_sha256=h_hash, cohorts_sha256=c_hash, manifest_sha256=manifest_hash, first_cohort_end=years[0], latest_cohort_end=years[-1], cohort_rows=len(years), history_cells=history.count(), blank_counts=history.where(F.col("learners").isNull()).count()) if spark.catalog.tableExists("nait_cohorts"): prior = spark.table("nait_cohorts").agg(F.max("cohort_end_year")).first()[0] if prior and years[-1] < prior: raise ValueError(f"Cannot replace a release containing a later cohort ending in {prior}") frames = {"nait_cohorts": cohorts, "nait_history": history} for table, frame in frames.items(): if latest_release(table) != release: (frame.coalesce(1).write.format("delta").mode("overwrite") .option("userMetadata", json.dumps(audit)).saveAsTable(table)) if any(latest_release(table) != release for table in frames): raise RuntimeError("Delta release IDs differ; rerun this batch before refreshing Power BI") return audit print(json.dumps(publish(), indent=2))