---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Archive exact repeat-seed Careers evidence rows and prevent recurrence.\"\"\" from __future__ import annotations import argparse import json import os import sqlite3 from datetime import."
resource: "https://careers.copecheck.com"
tags: ["copecheck", "careers", "source-file", "py"]
timestamp: "2026-08-24T13:09:16Z"
site: "careers"
source_path: "copecheck-careers/migrate_exact_evidence_duplicates.py"
---

# !/usr/bin/env python3

Source path: `copecheck-careers/migrate_exact_evidence_duplicates.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T13:09:16Z`

```py
#!/usr/bin/env python3
"""Archive exact repeat-seed Careers evidence rows and prevent recurrence."""
from __future__ import annotations

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


ARCHIVE_SCHEMA = """
CREATE TABLE IF NOT EXISTS cope_entries_duplicate_archive (
    archive_id INTEGER PRIMARY KEY AUTOINCREMENT,
    original_id INTEGER NOT NULL UNIQUE,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    quote TEXT NOT NULL,
    source_url TEXT,
    source_title TEXT,
    cope_score REAL NOT NULL,
    cope_type TEXT,
    analysis_md TEXT,
    model TEXT,
    created_at TEXT,
    archived_at TEXT NOT NULL,
    reason TEXT NOT NULL
);
"""

PARTITION = """
entity_type, entity_id, quote,
COALESCE(source_url, ''), COALESCE(source_title, ''), cope_score,
COALESCE(cope_type, ''), COALESCE(analysis_md, ''), COALESCE(model, '')
"""


def duplicate_ids(con: sqlite3.Connection) -> list[int]:
    return [row[0] for row in con.execute(f"""
        SELECT id FROM (
            SELECT id, ROW_NUMBER() OVER (
                PARTITION BY {PARTITION} ORDER BY id
            ) AS occurrence
            FROM cope_entries
        )
        WHERE occurrence > 1
        ORDER BY id
    """)]


def backup_database(source: Path, backup: Path) -> None:
    source_uri = f"file:{source.resolve()}?mode=ro"
    with sqlite3.connect(source_uri, uri=True) as src, sqlite3.connect(backup) as dst:
        src.backup(dst)
    stat = source.stat()
    os.chmod(backup, stat.st_mode & 0o777)
    try:
        os.chown(backup, stat.st_uid, stat.st_gid)
    except PermissionError:
        pass


def run(db_path: Path, apply: bool = False, backup_path: Path | None = None) -> dict:
    if not db_path.is_file():
        raise FileNotFoundError(db_path)
    uri = f"file:{db_path.resolve()}?mode={'rw' if apply else 'ro'}"
    con = sqlite3.connect(uri, uri=True, timeout=30)
    try:
        before = con.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
        ids = duplicate_ids(con)
        report = {
            "mode": "apply" if apply else "dry-run",
            "rows_before": before,
            "exact_duplicates": len(ids),
            "rows_after": before - len(ids) if apply else before,
            "backup": None,
        }
        if not apply:
            return report

        con.execute("BEGIN IMMEDIATE")
        locked_ids = duplicate_ids(con)
        if locked_ids != ids:
            raise RuntimeError("duplicate set changed while acquiring migration lock")
        archive_exists = bool(con.execute(
            """SELECT 1 FROM sqlite_master
                 WHERE type='table' AND name='cope_entries_duplicate_archive'"""
        ).fetchone())
        index_exists = bool(con.execute(
            """SELECT 1 FROM sqlite_master
                 WHERE type='index' AND name='uq_cope_entries_exact_evidence'"""
        ).fetchone())
        if not ids and archive_exists and index_exists:
            con.rollback()
            return report
        if backup_path is None:
            stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
            backup_path = db_path.with_name(f"{db_path.name}.pre-evidence-dedupe-{stamp}.bak")
        if backup_path.exists():
            raise FileExistsError(backup_path)
        backup_database(db_path, backup_path)
        con.execute(ARCHIVE_SCHEMA)
        if ids:
            archived_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
            placeholders = ",".join("?" for _ in ids)
            con.execute(
                f"""INSERT OR IGNORE INTO cope_entries_duplicate_archive
                    (original_id, entity_type, entity_id, quote, source_url,
                     source_title, cope_score, cope_type, analysis_md, model,
                     created_at, archived_at, reason)
                    SELECT id, entity_type, entity_id, quote, source_url,
                           source_title, cope_score, cope_type, analysis_md, model,
                           created_at, ?, 'exact_repeat_seed'
                    FROM cope_entries WHERE id IN ({placeholders})""",
                (archived_at, *ids),
            )
            archived_ids = {
                row[0] for row in con.execute(
                    f"""SELECT original_id FROM cope_entries_duplicate_archive
                          WHERE original_id IN ({placeholders})""",
                    ids,
                )
            }
            if archived_ids != set(ids):
                raise RuntimeError("not every duplicate observation reached the archive")
            con.execute(f"DELETE FROM cope_entries WHERE id IN ({placeholders})", ids)
        con.execute(f"""CREATE UNIQUE INDEX IF NOT EXISTS uq_cope_entries_exact_evidence
            ON cope_entries({PARTITION})""")
        after = con.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0]
        if after != before - len(ids):
            raise RuntimeError("cope evidence row-count reconciliation failed")
        if duplicate_ids(con):
            raise RuntimeError("exact duplicates remain after migration")
        integrity = con.execute("PRAGMA integrity_check").fetchone()[0]
        if integrity != "ok":
            raise RuntimeError(f"integrity check failed: {integrity}")
        con.commit()
        report["rows_after"] = after
        report["archive_rows"] = con.execute(
            "SELECT COUNT(*) FROM cope_entries_duplicate_archive"
        ).fetchone()[0]
        report["backup"] = str(backup_path)
        report["integrity_check"] = integrity
        return report
    except Exception:
        con.rollback()
        raise
    finally:
        con.close()


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("db", type=Path)
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--backup", type=Path)
    args = parser.parse_args()
    print(json.dumps(run(args.db, apply=args.apply, backup_path=args.backup), indent=2))
    return 0


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