---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Dry-run or quarantine high-confidence non-article extractions in the main DB.\"\"\" from __future__ import annotations import argparse import json import sqlite3 from collections import Counter."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-08-24T12:39:23Z"
site: "main"
source_path: "copecheck/quarantine_bad_extractions.py"
---

# !/usr/bin/env python3

Source path: `copecheck/quarantine_bad_extractions.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-08-24T12:39:23Z`

```py
#!/usr/bin/env python3
"""Dry-run or quarantine high-confidence non-article extractions in the main DB."""
from __future__ import annotations

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

from content_quality import extraction_quality_issue

MIGRATION_REASONS = {
    "google_consent", "yahoo_consent", "linkedin_consent",
    "javascript_challenge", "publisher_consent", "access_block",
    "consent_interstitial", "not_found_page",
}


def find_bad_rows(conn: sqlite3.Connection) -> list[dict]:
    conn.row_factory = sqlite3.Row
    bad = []
    for row in conn.execute(
        """SELECT id, slug, status, index_status, body
             FROM articles
            WHERE COALESCE(status, '') != 'quarantined'"""
    ):
        reason = extraction_quality_issue(row["body"] or "")
        # Existing short rows may be intentionally snippet-backed legacy pages.
        # Quarantine only deterministic interstitial/error pages in the backfill;
        # the live ingestion gate rejects all too-short future fetches.
        if reason in MIGRATION_REASONS:
            item = dict(row)
            item["reason"] = reason
            bad.append(item)
    return bad


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-quality-{stamp}")
    # The caller holds BEGIN IMMEDIATE on its writer.  A second read
    # connection captures the last committed state without deadlocking the
    # lock-owning handle, while the reserved lock prevents another writer from
    # changing the database before the quarantine transaction commits.
    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", type=Path, required=True)
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    connection = (
        sqlite3.connect(args.db)
        if args.apply
        else sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True)
    )
    with connection as conn:
        conn.row_factory = sqlite3.Row
        if args.apply:
            conn.execute("BEGIN IMMEDIATE")
        rows = find_bad_rows(conn)
        ids = [row["id"] for row in rows]
        linked_entries = 0
        if ids:
            placeholders = ",".join("?" for _ in ids)
            linked_entries = conn.execute(
                f"""SELECT COUNT(*)
                      FROM cope_entries ce
                      JOIN articles a ON a.slug=ce.article_slug
                     WHERE a.id IN ({placeholders})""",
                ids,
            ).fetchone()[0]
        summary = {
            "mode": "apply" if args.apply else "dry-run",
            "database": str(args.db),
            "rows": len(rows),
            "linked_cope_entries": linked_entries,
            "by_reason": dict(sorted(Counter(row["reason"] for row in rows).items())),
            "by_previous_index_status": dict(sorted(Counter(row["index_status"] or "unset" for row in rows).items())),
        }
        if args.apply and linked_entries:
            conn.rollback()
            summary["error"] = "refusing to quarantine rows that still have published cope entries"
            print(json.dumps(summary, indent=2, sort_keys=True))
            return 2
        if args.apply and rows:
            summary["backup"] = str(backup_database(args.db))
            for row in rows:
                conn.execute(
                    """UPDATE articles
                          SET status='quarantined',
                              error=?,
                              index_status='noindex',
                              index_reason=?,
                              index_checked_at=CURRENT_TIMESTAMP
                        WHERE id=?""",
                    (
                        f"extraction_quality:{row['reason']}",
                        f"quarantined non-article extraction: {row['reason']}",
                        row["id"],
                    ),
                )
            conn.execute("DELETE FROM articles_fts")
            conn.execute(
                """INSERT INTO articles_fts (slug, title, source, snippet, one_liner, verdict_md)
                   SELECT slug, title, source, snippet, one_liner, verdict_md
                     FROM articles
                    WHERE status='analysed'"""
            )
        if args.apply:
            conn.commit()
    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0


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