---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Normalise legacy VACS02 observation keys and quarantine malformed rows.\"\"\" from __future__ import annotations import argparse import json import re import sqlite3 from datetime import."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-24T12:57:08Z"
site: "uk"
source_path: "copecheck-uk/normalize_vacs02_snapshots.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/normalize_vacs02_snapshots.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-24T12:57:08Z`

```py
#!/usr/bin/env python3
"""Normalise legacy VACS02 observation keys and quarantine malformed rows."""
from __future__ import annotations

import argparse
import json
import re
import sqlite3
from datetime import datetime, timezone
from pathlib import Path


def normalise_industry(value) -> str:
    name = re.sub(r"\s+", " ", str(value or "")).strip()
    return re.sub(r"(?<=\D)\d+$", "", name).strip()


def period_end_month(period_label) -> str | None:
    match = re.fullmatch(
        r"[A-Za-z]{3}[- ]([A-Za-z]{3})\s+(\d{4})",
        str(period_label or "").strip(),
    )
    if not match:
        return None
    try:
        month = datetime.strptime(match.group(1), "%b").month
    except ValueError:
        return None
    return f"{int(match.group(2)):04d}-{month:02d}"


def row_recency(row: dict) -> tuple[str, int]:
    return str(row.get("fetched_at") or ""), int(row.get("id") or 0)


def analyse_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
    """Return canonical winners and rows that should be quarantined."""
    winners: dict[tuple[str, str], dict] = {}
    quarantined: list[dict] = []
    for original in rows:
        row = dict(original)
        row["_original_snapshot_date"] = row.get("snapshot_date")
        row["_original_industry"] = row.get("industry")
        snapshot_date = period_end_month(row.get("period_label"))
        industry = normalise_industry(row.get("industry"))
        if snapshot_date is None or not industry:
            row["quarantine_reason"] = "invalid VACS02 period or industry label"
            quarantined.append(row)
            continue
        row["snapshot_date"] = snapshot_date
        row["industry"] = industry
        key = (snapshot_date, industry.casefold())
        previous = winners.get(key)
        if previous is None:
            winners[key] = row
            continue
        if row_recency(row) > row_recency(previous):
            previous["quarantine_reason"] = "duplicate observation period and industry"
            quarantined.append(previous)
            winners[key] = row
        else:
            row["quarantine_reason"] = "duplicate observation period and industry"
            quarantined.append(row)
    return sorted(winners.values(), key=lambda row: row["id"]), quarantined


def backup_database(db_path: Path) -> Path:
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    backup_path = db_path.with_name(f"{db_path.name}.bak-vacs02-normalise-{stamp}")
    with sqlite3.connect(db_path) as source, sqlite3.connect(backup_path) as target:
        source.backup(target)
    return backup_path


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--db", required=True, type=Path)
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    database = (
        sqlite3.connect(args.db)
        if args.apply
        else sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True)
    )
    with database as connection:
        connection.row_factory = sqlite3.Row
        if args.apply:
            connection.execute("BEGIN IMMEDIATE")
        original_rows = [
            dict(row)
            for row in connection.execute("SELECT * FROM vacs02_snapshot ORDER BY id")
        ]
        winners, quarantined = analyse_rows(original_rows)
        canonical_by_id = {row["id"]: row for row in winners}
        changed_winners = sum(
            row["snapshot_date"] != canonical_by_id[row["id"]]["snapshot_date"]
            or row["industry"] != canonical_by_id[row["id"]]["industry"]
            for row in original_rows
            if row["id"] in canonical_by_id
        )
        changes = changed_winners + len(quarantined)
        summary = {
            "database": str(args.db),
            "mode": "apply" if args.apply else "dry-run",
            "rows_before": len(original_rows),
            "rows_after": len(winners),
            "canonical_rows_changed": changed_winners,
            "rows_quarantined": len(quarantined),
            "invalid_rows": sum(
                row["quarantine_reason"].startswith("invalid") for row in quarantined
            ),
            "duplicate_rows": sum(
                row["quarantine_reason"].startswith("duplicate") for row in quarantined
            ),
        }
        if args.apply and changes:
            summary["backup"] = str(backup_database(args.db))
            connection.execute("""
                CREATE TABLE IF NOT EXISTS vacs02_snapshot_quarantine (
                    quarantine_id INTEGER PRIMARY KEY AUTOINCREMENT,
                    original_id INTEGER UNIQUE NOT NULL,
                    snapshot_date TEXT,
                    industry TEXT,
                    vacancies_000s REAL,
                    period_label TEXT,
                    source_url TEXT,
                    fetched_at TEXT,
                    reason TEXT NOT NULL,
                    quarantined_at TEXT DEFAULT CURRENT_TIMESTAMP
                )
            """)
            for row in quarantined:
                connection.execute("""
                    INSERT OR IGNORE INTO vacs02_snapshot_quarantine (
                        original_id, snapshot_date, industry, vacancies_000s,
                        period_label, source_url, fetched_at, reason
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                """, (
                    # Quarantine is an audit ledger: retain the stored legacy
                    # values even when the duplicate was found after
                    # canonicalising its key for comparison.
                    row["id"], row.get("_original_snapshot_date"),
                    row.get("_original_industry"),
                    row.get("vacancies_000s"), row.get("period_label"),
                    row.get("source_url"), row.get("fetched_at"),
                    row["quarantine_reason"],
                ))
            connection.execute("DELETE FROM vacs02_snapshot")
            for row in winners:
                connection.execute("""
                    INSERT INTO vacs02_snapshot (
                        id, snapshot_date, industry, vacancies_000s,
                        period_label, source_url, fetched_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?)
                """, (
                    row["id"], row["snapshot_date"], row["industry"],
                    row.get("vacancies_000s"), row.get("period_label"),
                    row.get("source_url"), row.get("fetched_at"),
                ))
        if args.apply:
            connection.commit()

    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```
