---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Promote queued CopeCheck candidates into today's remaining publish slots. Runs hourly. Highest priority first (relevance score, with curated figure-linked evidence boosted), oldest first as."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T16:29:15Z"
site: "main"
source_path: "copecheck/drain_publish_queue.py"
---

# !/usr/bin/env python3

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

```py
#!/usr/bin/env python3
"""Promote queued CopeCheck candidates into today's remaining publish slots.

Runs hourly. Highest priority first (relevance score, with curated
figure-linked evidence boosted), oldest first as the tiebreak. Entries that
have sat in the queue longer than QUEUE_TTL_DAYS are dropped as stale rather
than published late.

  --dry-run   show what would be promoted, change nothing
  --limit N   promote at most N (still bounded by remaining daily slots)
"""

import argparse
import os
import sys
from datetime import datetime, timedelta, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db  # noqa: E402
import publish_gate as gate  # noqa: E402


def log(msg):
    stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    print(f"[{stamp}] {msg}", flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--limit", type=int, default=None)
    args = ap.parse_args()

    cutoff = (datetime.now(timezone.utc)
              - timedelta(days=gate.QUEUE_TTL_DAYS)).strftime("%Y-%m-%d %H:%M:%S")

    with db.conn() as c:
        gate.ensure_schema(c)
        c.execute("BEGIN IMMEDIATE")

        stale = c.execute(
            "SELECT COUNT(*) FROM publish_queue WHERE queued_at < ?", (cutoff,)
        ).fetchone()[0]
        if stale and not args.dry_run:
            c.execute("DELETE FROM publish_queue WHERE queued_at < ?", (cutoff,))
        if stale:
            log(f"dropped {stale} stale queue entries (older than "
                f"{gate.QUEUE_TTL_DAYS}d)")

        remaining = gate.remaining_today(c)
        if args.limit is not None:
            remaining = min(remaining, args.limit)
        depth = gate.queue_depth(c)
        log(f"cap={gate.daily_cap()} published_today={gate.published_today(c)} "
            f"slots_remaining={remaining} queue_depth={depth}")

        if remaining <= 0:
            log("no slots remaining; nothing to do")
            return 0

        rows = c.execute(
            """SELECT q.slug, q.desired_status, q.desired_reason,
                      q.desired_source, q.channel, q.priority
                 FROM publish_queue q
                 JOIN articles a ON a.slug = q.slug
                WHERE q.queued_at >= ?
                  AND a.status = 'analysed'
             ORDER BY q.priority DESC, q.queued_at ASC
                LIMIT ?""",
            (cutoff, remaining),
        ).fetchall()

        promoted = 0
        for r in rows:
            slug = r["slug"]
            if args.dry_run:
                log(f"DRY-RUN would promote {slug} -> {r['desired_status']} "
                    f"(priority {r['priority']:.1f})")
                promoted += 1
                continue
            if not gate.claim_slot(c, slug, channel=r["channel"] or "queue",
                                   index_status=r["desired_status"],
                                   priority=r["priority"]):
                log("cap reached mid-drain; stopping")
                break
            c.execute(
                """UPDATE articles
                      SET index_status = ?,
                          index_reason = ?,
                          index_checked_at = CURRENT_TIMESTAMP,
                          indexed_source = COALESCE(?, indexed_source)
                    WHERE slug = ?""",
                (r["desired_status"],
                 (r["desired_reason"] or "promoted from publish queue")
                 + " (queued)",
                 r["desired_source"], slug),
            )
            c.execute("DELETE FROM publish_queue WHERE slug = ?", (slug,))
            log(f"promoted {slug} -> {r['desired_status']} "
                f"(priority {r['priority']:.1f})")
            promoted += 1

        log(f"done: {promoted} promoted, queue depth now "
            f"{gate.queue_depth(c)}")
    return 0


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