---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Quarantine legacy REC rows that contain no usable published metric.\"\"\" from __future__ import annotations import argparse import json import sqlite3 from datetime import datetime, timezone."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-08-24T12:57:08Z"
site: "uk"
source_path: "copecheck-uk/quarantine_invalid_rec_rows.py"
---

# !/usr/bin/env python3

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

```py
#!/usr/bin/env python3
"""Quarantine legacy REC rows that contain no usable published metric."""
from __future__ import annotations

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


INVALID_WHERE = """
    perm_index IS NULL
    AND temp_index IS NULL
    AND staff_avail_index IS NULL
    AND vacancies_index IS NULL
    AND COALESCE(consecutive_months_below_50, 0) <= 0
"""


def backup_database(db_path: Path) -> Path:
    """Back up committed state while the caller holds ``BEGIN IMMEDIATE``."""
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    backup_path = db_path.with_name(f"{db_path.name}.bak-rec-quality-{stamp}")
    # sqlite3.Connection.backup() can stall when source and write-lock owner
    # are the same connection.  A second read connection sees the last
    # committed snapshot while the caller's reserved lock prevents writers.
    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:
            # Prevent the fetcher from inserting a row after the backup but
            # before DELETE re-evaluates INVALID_WHERE.
            connection.execute("BEGIN IMMEDIATE")
        rows = [dict(row) for row in connection.execute(
            f"SELECT * FROM rec_report WHERE {INVALID_WHERE} ORDER BY id"
        )]
        summary = {
            "database": str(args.db),
            "mode": "apply" if args.apply else "dry-run",
            "rows": len(rows),
            "report_months": [row.get("report_month") for row in rows],
        }
        if args.apply and rows:
            summary["backup"] = str(backup_database(args.db))
            connection.execute("""
                CREATE TABLE IF NOT EXISTS rec_report_quarantine (
                    quarantine_id INTEGER PRIMARY KEY AUTOINCREMENT,
                    original_id INTEGER UNIQUE NOT NULL,
                    report_month TEXT,
                    perm_index REAL,
                    temp_index REAL,
                    staff_avail_index REAL,
                    vacancies_index REAL,
                    key_quote TEXT,
                    source_url TEXT,
                    consecutive_months_below_50 INTEGER,
                    fetched_at TEXT,
                    reason TEXT NOT NULL,
                    quarantined_at TEXT DEFAULT CURRENT_TIMESTAMP
                )
            """)
            connection.execute(f"""
                INSERT OR IGNORE INTO rec_report_quarantine (
                    original_id, report_month, perm_index, temp_index,
                    staff_avail_index, vacancies_index, key_quote, source_url,
                    consecutive_months_below_50, fetched_at, reason
                )
                SELECT id, report_month, perm_index, temp_index,
                       staff_avail_index, vacancies_index, key_quote, source_url,
                       consecutive_months_below_50, fetched_at,
                       'no usable published REC metric'
                  FROM rec_report
                 WHERE {INVALID_WHERE}
            """)
            connection.execute(f"DELETE FROM rec_report WHERE {INVALID_WHERE}")
        if args.apply:
            connection.commit()

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


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