---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Prove rollback restores exact prior state — by actually doing it. 1. Snapshot the full index state of every article in the batch. 2. Roll one tier back. Verify every row matches its pre-change."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T21:08:13Z"
site: "main"
source_path: "copecheck/prove_rollback.py"
---

# !/usr/bin/env python3

Source path: `copecheck/prove_rollback.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-25T21:08:13Z`

```py
#!/usr/bin/env python3
"""Prove rollback restores exact prior state — by actually doing it.

1. Snapshot the full index state of every article in the batch.
2. Roll one tier back. Verify every row matches its pre-change state exactly.
3. Re-apply that tier. Verify we are back to post-change state.
4. Confirm figure scores and provenance never moved at any point.

Operates on PRODUCTION but is net-zero: it ends in exactly the state it began.
"""
import os
import subprocess
import sys

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

BATCH = sys.argv[1]
TIER = sys.argv[2] if len(sys.argv) > 2 else "T1c-duplicate-title"
PY = os.path.join(HERE, "venv", "bin", "python3")

PASS, FAIL = [], []


def check(name, cond, detail=""):
    (PASS if cond else FAIL).append(name)
    print(f"  [{'PASS' if cond else 'FAIL'}] {name} {detail}")


def state(slugs):
    with db.conn() as c:
        qs = ",".join("?" * len(slugs))
        return {r["slug"]: (r["index_status"], r["index_reason"],
                            r["indexed_source"])
                for r in c.execute(
                    f"SELECT slug,index_status,index_reason,indexed_source "
                    f"FROM articles WHERE slug IN ({qs})", slugs)}


def fingerprint():
    with db.conn() as c:
        return (
            [tuple(r) for r in c.execute(
                "SELECT id,cope_score,prev_score,total_quotes FROM figures "
                "ORDER BY id")],
            c.execute("SELECT COUNT(*) FROM article_provenance").fetchone()[0],
            c.execute("SELECT COUNT(*) FROM cope_entry_provenance").fetchone()[0],
            c.execute("SELECT COUNT(*) FROM cope_entries").fetchone()[0],
            c.execute("SELECT COUNT(*) FROM articles").fetchone()[0],
        )


def indexable():
    with db.conn() as c:
        return c.execute("SELECT COUNT(*) FROM articles WHERE index_status "
                         "IN ('index','trial_index')").fetchone()[0]


with db.conn() as c:
    rows = c.execute(
        "SELECT slug, old_index_status, old_index_reason, old_indexed_source, "
        "new_index_status FROM prune_batches WHERE batch=? AND tier=?",
        (BATCH, TIER)).fetchall()

if not rows:
    print(f"no rows for batch={BATCH} tier={TIER}")
    sys.exit(1)

slugs = [r["slug"] for r in rows]
expected_old = {r["slug"]: (r["old_index_status"], r["old_index_reason"],
                            r["old_indexed_source"]) for r in rows}
print(f"batch : {BATCH}")
print(f"tier  : {TIER}  ({len(slugs)} articles)\n")

fp0 = fingerprint()
idx0 = indexable()
post_change = state(slugs)
print(f"indexable now: {idx0}")
check("all rows currently noindex (post-change state)",
      all(v[0] == "noindex" for v in post_change.values()))

print(f"\n--- STEP 1: rolling back tier {TIER} ---")
out = subprocess.run([PY, os.path.join(HERE, "prune_rollback.py"),
                      BATCH, "--tier", TIER],
                     capture_output=True, text=True, cwd=HERE)
print("   " + out.stdout.strip().replace("\n", "\n   "))
if out.returncode != 0:
    print(out.stderr)

restored = state(slugs)
mismatches = [s for s in slugs if restored.get(s) != expected_old.get(s)]
check("every article restored to its EXACT prior state",
      not mismatches, f"{len(mismatches)} mismatches" if mismatches else "")
for s in mismatches[:5]:
    print(f"      {s}\n        got      {restored.get(s)}"
          f"\n        expected {expected_old.get(s)}")

idx1 = indexable()
check("indexable count rose by exactly the tier size",
      idx1 == idx0 + len(slugs), f"{idx0} -> {idx1} (+{idx1-idx0})")
check("figure scores / provenance unchanged by rollback",
      fingerprint() == fp0)

print(f"\n--- STEP 2: re-applying tier {TIER} ---")
with db.conn() as c:
    c.execute("BEGIN IMMEDIATE")
    n = 0
    for r in c.execute(
        "SELECT * FROM prune_batches WHERE batch=? AND tier=? "
        "AND rolled_back_at IS NOT NULL", (BATCH, TIER)).fetchall():
        c.execute("UPDATE articles SET index_status=?, index_reason=?, "
                  "index_checked_at=CURRENT_TIMESTAMP WHERE slug=?",
                  (r["new_index_status"], r["new_index_reason"], r["slug"]))
        c.execute("UPDATE prune_batches SET rolled_back_at=NULL WHERE id=?",
                  (r["id"],))
        n += 1
print(f"   re-applied {n} rows")

again = state(slugs)
check("re-apply reproduces post-change state exactly",
      again == post_change)
idx2 = indexable()
check("indexable count back to starting value",
      idx2 == idx0, f"{idx0} -> {idx2}")
check("figure scores / provenance unchanged throughout",
      fingerprint() == fp0)

print(f"\n{'='*58}\nPASSED {len(PASS)}  FAILED {len(FAIL)}")
if FAIL:
    print("FAILURES:", FAIL)
sys.exit(1 if FAIL else 0)
```
