---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Undo a prune batch, restoring each article's exact prior index state. prune_rollback.py <batch> roll the whole batch back prune_rollback.py <batch> --tier X roll back just one tier."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T16:57:59Z"
site: "main"
source_path: "copecheck/prune_rollback.py"
---

# !/usr/bin/env python3

Source path: `copecheck/prune_rollback.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-25T16:57:59Z`

```py
#!/usr/bin/env python3
"""Undo a prune batch, restoring each article's exact prior index state.

  prune_rollback.py <batch>            roll the whole batch back
  prune_rollback.py <batch> --tier X   roll back just one tier
  prune_rollback.py --list             show batches
"""
import argparse
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import db  # noqa: E402


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("batch", nargs="?")
    ap.add_argument("--tier")
    ap.add_argument("--list", action="store_true")
    a = ap.parse_args()

    with db.conn() as c:
        if a.list or not a.batch:
            rows = c.execute("""
                SELECT batch, tier, COUNT(*) n,
                       SUM(rolled_back_at IS NOT NULL) undone,
                       MIN(applied_at) at
                  FROM prune_batches GROUP BY batch, tier
                 ORDER BY at DESC, tier""").fetchall()
            if not rows:
                print("no batches recorded")
                return 0
            print(f"{'batch':<28} {'tier':<26} {'rows':>6} {'undone':>7}  applied")
            for r in rows:
                print(f"{r['batch']:<28} {r['tier']:<26} {r['n']:>6} "
                      f"{r['undone']:>7}  {r['at']}")
            return 0

        q = ("SELECT * FROM prune_batches WHERE batch=? "
             "AND rolled_back_at IS NULL")
        p = [a.batch]
        if a.tier:
            q += " AND tier=?"
            p.append(a.tier)
        c.execute("BEGIN IMMEDIATE")
        rows = c.execute(q, p).fetchall()
        if not rows:
            print("nothing to roll back for", a.batch,
                  f"(tier={a.tier})" if a.tier else "")
            return 0

        restored = skipped = 0
        for r in rows:
            cur = c.execute("SELECT index_status FROM articles WHERE slug=?",
                            (r["slug"],)).fetchone()
            if not cur:
                skipped += 1
                continue
            # Only restore if the article is still in the state we set. If
            # something else changed it since, leave it alone and report.
            if cur["index_status"] != r["new_index_status"]:
                skipped += 1
                continue
            c.execute(
                """UPDATE articles
                      SET index_status=?, index_reason=?,
                          indexed_source=COALESCE(?, indexed_source),
                          index_checked_at=CURRENT_TIMESTAMP
                    WHERE slug=?""",
                (r["old_index_status"], r["old_index_reason"],
                 r["old_indexed_source"], r["slug"]))
            c.execute("UPDATE prune_batches SET rolled_back_at=CURRENT_TIMESTAMP "
                      "WHERE id=?", (r["id"],))
            restored += 1

        idx = c.execute("SELECT COUNT(*) FROM articles WHERE index_status IN "
                        "('index','trial_index')").fetchone()[0]
        print(f"restored {restored}, skipped {skipped} "
              f"(changed since apply)")
        print(f"indexable now: {idx}")
    return 0


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