---
type: "Source File"
title: "\"\"\"Shared daily publish cap for CopeCheck."
description: "\"\"\"Shared daily publish cap for CopeCheck. Every pipeline that can promote an article to an indexable state (news scanner via db.set_verdict, brave scorer / URL submissions / cope pipeline via db.add_cope_entry)."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-09-25T16:30:38Z"
site: "main"
source_path: "copecheck/publish_gate.py"
---

# """Shared daily publish cap for CopeCheck.

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

```py
"""Shared daily publish cap for CopeCheck.

Every pipeline that can promote an article to an indexable state
(news scanner via db.set_verdict, brave scorer / URL submissions /
cope pipeline via db.add_cope_entry) funnels through claim_slot().

Design
------
* One ledger table counts *indexable promotions* per UTC day across all
  pipelines, so the cap is global rather than per-script.
* Candidates that miss out are NOT dropped. They stay fully analysed in
  the articles table at index_status='noindex' and are recorded in
  publish_queue with the index status they were supposed to get. A
  drainer promotes them on later days, highest priority first.
* Re-promoting a slug that already holds a slot today is idempotent and
  does not consume a second slot.
* Manual submissions are exempt: they are recorded for audit but never
  counted against the cap and never blocked.

Configure with COPECHECK_DAILY_PUBLISH_CAP (default 5).
"""

import os
import sqlite3
from datetime import datetime, timezone

DEFAULT_CAP = 5
# Queue entries older than this are dropped as stale rather than published
# late; news value decays and back-publishing month-old items is noise.
QUEUE_TTL_DAYS = 14

INDEXABLE_STATUSES = {"index", "trial_index"}


def daily_cap():
    try:
        return max(0, int(os.environ.get("COPECHECK_DAILY_PUBLISH_CAP", DEFAULT_CAP)))
    except (TypeError, ValueError):
        return DEFAULT_CAP


def manual_override_active():
    """True when this process is acting on Ben's behalf rather than a scanner.

    Set COPECHECK_PUBLISH_MANUAL=1 for interactive/manual runs (the URL
    submission processor, an admin CLI). Manual publishes are recorded for
    audit but never blocked and never counted against the daily cap, so Ben
    can always add something himself on a day the scanners have filled it.
    """
    return os.environ.get("COPECHECK_PUBLISH_MANUAL", "").strip().lower() in (
        "1", "true", "yes", "on",
    )


def today_utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%d")


SCHEMA = """
CREATE TABLE IF NOT EXISTS publish_ledger (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    slug         TEXT NOT NULL,
    publish_date TEXT NOT NULL,
    channel      TEXT,
    index_status TEXT,
    priority     REAL DEFAULT 0,
    exempt       INTEGER NOT NULL DEFAULT 0,
    published_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_publish_ledger_slug
    ON publish_ledger(slug);
CREATE INDEX IF NOT EXISTS idx_publish_ledger_date
    ON publish_ledger(publish_date, exempt);

CREATE TABLE IF NOT EXISTS publish_queue (
    slug           TEXT PRIMARY KEY,
    desired_status TEXT NOT NULL,
    desired_reason TEXT,
    desired_source TEXT,
    channel        TEXT,
    priority       REAL DEFAULT 0,
    queued_at      TEXT DEFAULT CURRENT_TIMESTAMP,
    attempts       INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_publish_queue_priority
    ON publish_queue(priority DESC, queued_at ASC);
"""


def ensure_schema(c):
    """Idempotently create the gate tables. Safe to call on every open."""
    c.executescript(SCHEMA)


def published_today(c, day=None):
    """Count of cap-consuming promotions made on `day` (default: today UTC)."""
    day = day or today_utc()
    row = c.execute(
        "SELECT COUNT(*) n FROM publish_ledger "
        "WHERE publish_date = ? AND exempt = 0",
        (day,),
    ).fetchone()
    return row[0] if not hasattr(row, "keys") else row["n"]


def remaining_today(c, day=None):
    return max(0, daily_cap() - published_today(c, day))


def holds_slot(c, slug):
    """True if this slug has already been granted a slot (any day)."""
    return c.execute(
        "SELECT 1 FROM publish_ledger WHERE slug = ? LIMIT 1", (slug,)
    ).fetchone() is not None


def claim_slot(c, slug, channel="scanner", index_status="index",
               priority=0.0, manual=False, day=None):
    """Try to claim one of today's publish slots for `slug`.

    Must be called inside an existing write transaction on `c`.
    Returns True if the caller may set an indexable index_status.
    """
    if not slug:
        return False
    day = day or today_utc()

    # Already published/promoted before: re-promotion is free and idempotent.
    if holds_slot(c, slug):
        return True

    exempt = 1 if (manual or manual_override_active()) else 0
    if not exempt and published_today(c, day) >= daily_cap():
        return False

    try:
        c.execute(
            """INSERT INTO publish_ledger
               (slug, publish_date, channel, index_status, priority, exempt)
               VALUES (?, ?, ?, ?, ?, ?)""",
            (slug, day, channel, index_status, priority, exempt),
        )
    except sqlite3.IntegrityError:
        # Raced with another worker that claimed the same slug: that is fine,
        # the slug is published either way and only one slot was consumed.
        return True
    # Claiming a slot supersedes any queue entry for that slug.
    c.execute("DELETE FROM publish_queue WHERE slug = ?", (slug,))
    return True


def enqueue(c, slug, desired_status, desired_reason=None, desired_source=None,
            channel="scanner", priority=0.0):
    """Record a candidate that was capped out so it can publish later."""
    if not slug:
        return
    c.execute(
        """INSERT INTO publish_queue
             (slug, desired_status, desired_reason, desired_source,
              channel, priority)
           VALUES (?, ?, ?, ?, ?, ?)
           ON CONFLICT(slug) DO UPDATE SET
             desired_status = excluded.desired_status,
             desired_reason = excluded.desired_reason,
             desired_source = excluded.desired_source,
             channel        = excluded.channel,
             priority       = MAX(publish_queue.priority, excluded.priority)""",
        (slug, desired_status, desired_reason, desired_source,
         channel, priority),
    )


def queue_depth(c):
    row = c.execute("SELECT COUNT(*) FROM publish_queue").fetchone()
    return row[0]
```
