# Publish Alberta apprenticeship classroom planning data from collections import Counter import csv import hashlib import io import json from pathlib import Path import re from pyspark.sql.types import IntegerType, StringType, StructField, StructType landing = Path("/lakehouse/default/Files/apprenticeship") fields = { "capacity": ("provider", "seats", "attendance"), "grants": ("provider", "end_year", "alg_dollars"), "registrations": ("program", "end_year", "new_registrations"), } # SHA-256 of the exact CSVs distributed with this dated release. expected_hashes = { "capacity": "8ad43e2b4cb4384aa75e654cdabe69e9ed890455ce6d362f28593b4ac5502ee0", "grants": "404d06dea221045f70e83cf8218b7bf7dd1e8631904f1afe9aec3c8c06017444", "registrations": "151f3fe302c96fbc3bfb3ef2a5693f0e0e78868ef1dc2635a34d74843757892e", } project_marker = "alberta-apprenticeship-classrooms" # Read a consistent release def read_rows(folder, name): raw = (folder / f"{name}.csv").read_bytes() columns = fields[name] reader = csv.reader(io.StringIO(raw.decode("utf-8-sig"), newline=""), strict=True) if tuple(next(reader, ())) != columns: raise ValueError(f"{name}: expected columns {', '.join(columns)}") rows = [] keys = set() for record in reader: if len(record) != len(columns): raise ValueError(f"{name}: wrong number of fields on line {reader.line_num}") label = record[0] if not label or label != label.strip() or label.casefold() == "total": raise ValueError(f"{name}: invalid detail label on line {reader.line_num}") if not all(re.fullmatch(r"[0-9]{1,9}", v) for v in record[1:]): raise ValueError(f"{name}: expected nonnegative whole numbers on line {reader.line_num}") row = (label, *(int(v) for v in record[1:])) key = row[:1] if name == "capacity" else row[:2] if key in keys: raise ValueError(f"{name}: duplicate detail key {key}") keys.add(key) rows.append(row) return rows, hashlib.sha256(raw).hexdigest() def validate(rows, hashes): capacity, grants, regs = (rows[name] for name in fields) if len(capacity) != 15 or any(seats <= 0 or attended > seats for _, seats, attended in capacity): raise ValueError("Invalid Table 6 provider roster or attendance") if (sum(r[1] for r in capacity), sum(r[2] for r in capacity)) != (28125, 25852): raise ValueError("Table 6 seats or attendance do not reconcile") providers = {r[0] for r in capacity} if any(provider not in providers for provider, _, _ in grants): raise ValueError("A grant institution does not match the capacity roster") for label, facts, totals, count in ( ("grants", grants, {2024: 53690611, 2025: 75519533}, 11), ("registrations", regs, {2024: 25758, 2025: 25650}, 47), ): sums = Counter() roster = {year: set() for year in totals} for name, year, value in facts: if year not in totals: raise ValueError(f"{label}: unapproved academic year ending {year}") roster[year].add(name) sums[year] += value if sums != totals or any(len(names) != count for names in roster.values()) or roster[2024] != roster[2025]: raise ValueError(f"{label}: published controls or detail roster differ") if hashes != expected_hashes: raise ValueError("The landed CSVs differ from this edition. Upload the original packaged files.") # Publish the three managed Delta tables def read_stamp(table): # OPTIMIZE can rewrite file layout, and VACUUM removes obsolete files, without changing the logical rows. # Inspect only the latest remaining operation. A foreign write with no tag must never expose an older tag. from pyspark.sql import functions as F maintenance = ("OPTIMIZE", "VACUUM START", "VACUUM END") change = (spark.sql(f"DESCRIBE HISTORY {table}") .where(~F.col("operation").isin(*maintenance)) .orderBy(F.desc("version")).select("userMetadata").first()) try: stamp = json.loads(change.userMetadata) if change and change.userMetadata else {} except (TypeError, ValueError): stamp = {} if not isinstance(stamp, dict) or stamp.get("project") != "alberta-apprenticeship-classrooms" or not stamp.get("release_id"): raise ValueError(f"The latest data commit for {table} does not identify this project. Use a dedicated lakehouse.") return stamp["release_id"] def current_stamp(table): return read_stamp(table) if spark.catalog.tableExists(table) else None def publish(folder): rows = {} hashes = {} for name in fields: rows[name], hashes[name] = read_rows(folder, name) validate(rows, hashes) release = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest() status = {name: current_stamp("apprentice_" + name) for name in fields} for name, columns in fields.items(): if status[name] == release: continue schema = StructType([ StructField(col, StringType() if i == 0 else IntegerType(), False) for i, col in enumerate(columns) ]) frame = spark.createDataFrame(rows[name], schema) stamp = {"project": project_marker, "release_id": release, "csv_sha256": hashes[name]} mode = "errorifexists" if status[name] is None else "overwrite" # CREATE TABLE AS SELECT reads commit metadata from the session on some Delta runtimes. # Save and restore it so later operations in this notebook cannot inherit this project's stamp. metadata_key = "spark.databricks.delta.commitInfo.userMetadata" before = spark.conf.get(metadata_key, None) payload = json.dumps(stamp) spark.conf.set(metadata_key, payload) try: (frame.coalesce(1).write.format("delta").mode(mode) .option("userMetadata", payload).saveAsTable("apprentice_" + name)) finally: if before is None: spark.conf.unset(metadata_key) else: spark.conf.set(metadata_key, before) if any(current_stamp("apprentice_" + name) != release for name in fields): raise RuntimeError("Table releases differ. Retry the publish notebook before refreshing the model.") return {"release_id": release, "capacity_rows": len(rows["capacity"]), "grant_rows": len(rows["grants"]), "registration_rows": len(rows["registrations"]), "offered": sum(row[1] for row in rows["capacity"]), "attendance": sum(row[2] for row in rows["capacity"])} print(json.dumps(publish(landing), indent=2))