---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Collapse duplicate report rows by canonical source while preserving old share IDs.\"\"\" import argparse import fcntl import json import os import shutil import sys import tempfile from datetime."
resource: "https://labs.copecheck.com"
tags: ["copecheck", "labs", "source-file", "py"]
timestamp: "2026-08-24T09:51:28Z"
site: "labs"
source_path: "labs/tools/dedupe_report_submissions.py"
---

# !/usr/bin/env python3

Source path: `labs/tools/dedupe_report_submissions.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T09:51:28Z`

```py
#!/usr/bin/env python3
"""Collapse duplicate report rows by canonical source while preserving old share IDs."""
import argparse
import fcntl
import json
import os
import shutil
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

import server  # noqa: E402


def load_rows(path: Path) -> list[dict]:
    rows = []
    with path.open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            try:
                item = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ValueError(f"Malformed JSON on line {line_number}: {exc}") from exc
            if not isinstance(item, dict) or not item.get("id"):
                raise ValueError(f"Invalid report row on line {line_number}")
            rows.append(item)
    return rows


def dedupe_rows(rows: list[dict]) -> list[dict]:
    groups: dict[str, list[dict]] = {}
    order: list[str] = []
    for row in rows:
        key = server._report_item_key(row)
        if key not in groups:
            groups[key] = []
            order.append(key)
        groups[key].append(row)

    output = []
    for key in order:
        candidates = groups[key]
        winner = dict(max(candidates, key=lambda row: (row.get("submitted_at", ""), row.get("id", ""))))
        legacy_ids = {
            legacy
            for row in candidates
            for legacy in ([row.get("id")] + list(row.get("legacy_ids") or []))
            if legacy
        }
        if not key.startswith("id|"):
            winner["source_key"] = key
            winner["canonical_source_url"] = server.canonical_report_url(winner.get("source_url", ""))
            winner["id"] = key[:12]
            winner["share_url"] = f"https://labs.copecheck.com/report/{winner['id']}"
        legacy_ids.discard(winner.get("id"))
        if legacy_ids:
            winner["legacy_ids"] = sorted(legacy_ids)
        else:
            winner.pop("legacy_ids", None)
        output.append(winner)
    return output


def write_atomic(path: Path, rows: list[dict]) -> None:
    original_stat = path.stat()
    fd, tmp_name = tempfile.mkstemp(prefix=f"{path.stem}-", suffix=path.suffix, dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            for row in rows:
                handle.write(json.dumps(row, ensure_ascii=False) + "\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.chmod(tmp_name, original_stat.st_mode & 0o7777)
        try:
            os.chown(tmp_name, original_stat.st_uid, original_stat.st_gid)
        except PermissionError:
            pass
        os.replace(tmp_name, path)
    finally:
        if os.path.exists(tmp_name):
            os.unlink(tmp_name)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--path", type=Path, default=server.REPORT_SUBMISSIONS_PATH)
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    lock_path = args.path.with_name(f"{args.path.stem}.lock")
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open("a+", encoding="utf-8") as lock_file:
        # If maintenance is invoked as root, do not leave a root-owned lock
        # that the normal ``ben`` gunicorn workers cannot reopen.
        source_stat = args.path.stat()
        try:
            os.fchown(lock_file.fileno(), source_stat.st_uid, source_stat.st_gid)
        except PermissionError:
            pass
        # The live Flask app uses the same advisory lock for report upserts.
        # Hold it across read, backup and replace so a concurrent score cannot
        # disappear between migration input and atomic output.
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
        rows = load_rows(args.path)
        deduped = dedupe_rows(rows)
        summary = {
            "path": str(args.path),
            "rows_before": len(rows),
            "rows_after": len(deduped),
            "duplicates_removed": len(rows) - len(deduped),
            "mode": "apply" if args.apply else "dry-run",
        }
        if args.apply and deduped != rows:
            stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
            backup = args.path.with_name(f"{args.path.name}.bak-{stamp}")
            shutil.copy2(args.path, backup)
            write_atomic(args.path, deduped)
            summary["backup"] = str(backup)
    print(json.dumps(summary, indent=2))
    return 0


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