Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Run the notification scheduler once and make threshold sends idempotent (#299)

Omega (QA)51d4a5702d0a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9883e3c..5b1b9f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@
- **Paperless-ngx 3.x uploads resolve again (#298):** the task poll only understood the Paperless API v9 shapes, so against Paperless-ngx 3.x (API v10) it never recognized a finished task: the detail lookup 404s, the list reply is a paginated page object, the status is lower case, and the document arrives in `related_document_ids`. The poll now unwraps paginated pages, compares the status case-insensitively, and reads `related_document_ids[0]` (with the `result_data` text as a fallback), so uploads resolve in seconds again instead of timing out after 10 minutes and saving with no document link. The v9 shapes keep working unchanged. The upload route also releases its database connection before the poll starts instead of holding it idle in transaction for the whole wait, and takes a fresh one only for the ownership claim afterwards.
- _Files: `backend/paperless_handler.py`, `backend/file_routes.py`, `tests/mock_paperless.py`, `tests/test_paperless_api_v10.py`_
+- **One notification scheduler, no duplicate emails (#299):** with `preload_app` the app was built in the gunicorn master, where no worker id is set, so the scheduler started there and every forked worker inherited a running copy; each copy sent the same notification. The scheduler now starts exactly once, in the master from the gunicorn `when_ready` hook, `create_app` never starts it under gunicorn, and each worker discards the copy it inherits before serving (the job is removed and the scheduler marked stopped, never shut down, since joining its dead thread would hang). Apprise threshold sends are also claimed up front with `INSERT ... ON CONFLICT DO NOTHING RETURNING`, so even if two copies of the job ever run at once only the one that inserted the row sends, and a failed send releases its claim so the threshold stays due and retries. Forked workers no longer close the database pool they inherit, which used to send a Terminate on the shared socket and kill the master's connection; the pool reference is dropped instead and a fresh pool is created per worker.
+ - _Files: `backend/notifications.py`, `backend/db_handler.py`, `backend/gunicorn_config.py`, `tests/test_scheduler_single_process.py`_
+
- **Warranty expiration change history (#209):** editing a warranty's expiration date, duration, or lifetime status now records the transition (previous value, new value, timestamp, editor, and an optional reason up to 255 characters) in a new `warranty_expiry_history` table without automatically mutating dates from claims. Warranties with recorded changes show a subtle clickable history badge next to the expiration date across the dashboard and Status page, opening an Expiry History modal; the Status page detail row and the Edit Warranty modal also display the change history, and the Edit Warranty modal dynamically reveals the optional reason field only when expiration inputs are modified.
- _Files: `backend/migrations/057_create_warranty_expiry_history.sql`, `backend/warranties_routes.py`, `backend/statistics_routes.py`, `frontend/js/components/expiryHistory.js`, `frontend/js/components/editModal.js`, `frontend/js/components/warrantyRenderer.js`, `frontend/js/components/ui.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/index.js`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `frontend/status.js`, `frontend/style.css`, `frontend/sw.js`, `locales/*/translation.json`, `tests/test_warranty_expiry_history.py`_
diff --git a/backend/db_handler.py b/backend/db_handler.py
index d12211b..cab28b5 100644
--- a/backend/db_handler.py
+++ b/backend/db_handler.py
@@ -88,26 +88,27 @@ _checked_out: Dict[int, Tuple[pool.AbstractConnectionPool, threading.BoundedSema
_init_lock = threading.Lock()
def _close_stale_pool_if_forked(current_pid: int) -> None:
- """Close any existing pool if it was created in a different process.
+ """Drop any pool created in a different process.
- Gunicorn with preload_app=True forks workers after the app (and pool) may be
- initialized. Psycopg2 connections/pools are not fork-safe. If we detect that
- the pool was created in a different PID, we proactively close it in this
- process so a fresh, per-process pool can be created.
+ Gunicorn with preload_app=True forks workers after the app (and
+ pool) may be initialized. Psycopg2 connections/pools are not
+ fork-safe. If we detect that the pool was created in a different
+ PID, drop the reference so a fresh, per-process pool is created.
+
+ Do NOT close the inherited connections: closing one sends a
+ Terminate message on the socket the parent still shares, which
+ kills the parent's connection ("server closed the connection
+ unexpectedly", #299). Dropping the reference is safe: the child's
+ copies of the sockets are closed by the kernel without a
+ Terminate message, and the parent keeps its own references.
"""
global connection_pool, pool_pid, _pool_slots
if connection_pool is not None and pool_pid is not None and pool_pid != current_pid:
- logger.warning(f"[DB_HANDLER] Detected PID change (pool pid {pool_pid} -> current pid {current_pid}). Closing stale pool and reinitializing...")
- try:
- # Close all connections owned by this (forked) process copy of the pool
- connection_pool.closeall()
- except Exception as close_err:
- logger.warning(f"[DB_HANDLER] Error while closing stale pool in forked process: {close_err}")
- finally:
- connection_pool = None
- pool_pid = None
- _pool_slots = None
- _checked_out.clear()
+ logger.warning(f"[DB_HANDLER] Detected PID change (pool pid {pool_pid} -> current pid {current_pid}). Discarding inherited pool and reinitializing...")
+ connection_pool = None
+ pool_pid = None
+ _pool_slots = None
+ _checked_out.clear()
def init_db_pool(max_retries=5, retry_delay=5):
global connection_pool, pool_pid, _pool_slots # Ensure we're modifying the global variable in this module
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
index 6e75ed2..146927c 100644
--- a/backend/gunicorn_config.py
+++ b/backend/gunicorn_config.py
@@ -8,6 +8,15 @@ Optimized for memory efficiency with configurable modes.
import os
+# Mark this process tree as running under gunicorn, before the app
+# loads. The notification scheduler must start exactly once, in the
+# master from when_ready (#299), so create_app checks this flag and
+# does not start it. It cannot be set in on_starting: under
+# preload_app the app loads in Arbiter.__init__, before start() calls
+# on_starting. Workers inherit the flag through the fork, and tell
+# themselves apart with GUNICORN_WORKER_ID (set in post_fork).
+os.environ["WARRACKER_GUNICORN_MASTER"] = "1"
+
# CRITICAL: Apply gevent monkey patching VERY EARLY to prevent SSL RecursionError
# This must happen before any other imports that might use SSL
memory_mode = os.environ.get('WARRACKER_MEMORY_MODE', 'optimized').lower()
@@ -98,12 +107,47 @@ def on_starting(server):
"""Called just before the master process is initialized."""
print("Server is starting with memory-optimized configuration")
+def when_ready(server):
+ """Called in the master once the arbiter is ready, before workers spawn.
+
+ Start the single notification scheduler here (#299). create_app
+ does not start it under gunicorn, and workers discard the copy
+ they inherit in post_fork, so exactly one scheduler runs.
+ """
+ try:
+ try:
+ from backend.notifications import init_scheduler
+ from backend.db_handler import get_db_connection, release_db_connection
+ except ImportError:
+ from notifications import init_scheduler
+ from db_handler import get_db_connection, release_db_connection
+ app = server.app.wsgi()
+ if init_scheduler(app, get_db_connection, release_db_connection, force=True):
+ print("Notification scheduler started in the gunicorn master")
+ else:
+ print("Warning: notification scheduler did not start in the gunicorn master")
+ except Exception as e:
+ print(f"Warning: failed to start notification scheduler in the gunicorn master: {e}")
+
def post_fork(server, worker):
"""Called just after a worker has been forked."""
os.environ["GUNICORN_WORKER_ID"] = str(worker.age - 1)
os.environ["GUNICORN_WORKER_PROCESS_NAME"] = f"worker-{worker.age - 1}"
os.environ["GUNICORN_WORKER_CLASS"] = worker_class
-
+
+ # Discard the scheduler inherited from the master (#299): the
+ # master owns the single scheduler, and a forked copy would send
+ # duplicate notifications. This runs before the worker starts
+ # serving, so the inherited scheduler never fires here.
+ try:
+ try:
+ from backend.notifications import discard_inherited_scheduler
+ except ImportError:
+ from notifications import discard_inherited_scheduler
+ discard_inherited_scheduler()
+ except Exception as e:
+ print(f"Warning: could not discard inherited scheduler: {e}")
+
print(f"Worker {worker.pid} (ID: {worker.age - 1}) forked with memory optimization")
def pre_fork(server, worker):
diff --git a/backend/notifications.py b/backend/notifications.py
index c43795f..db62aee 100644
--- a/backend/notifications.py
+++ b/backend/notifications.py
@@ -30,6 +30,11 @@ except ImportError:
BACKGROUND_SCHEDULER_AVAILABLE = False
BackgroundScheduler = None
+try:
+ from apscheduler.schedulers.base import STATE_STOPPED
+except ImportError:
+ STATE_STOPPED = 0
+
try:
from apscheduler.schedulers.gevent import GeventScheduler
GEVENT_SCHEDULER_AVAILABLE = True
@@ -476,6 +481,62 @@ def mark_thresholds_sent(due_pairs, channel, conn):
except Exception:
pass
+
+def claim_thresholds(due_pairs, channel, conn):
+ """Claim due thresholds so only one process sends each one (#299).
+
+ Inserts the notification_log row up front and returns only the
+ pairs this process actually inserted (INSERT ... ON CONFLICT DO
+ NOTHING RETURNING). A concurrent copy of the job that loses the
+ race gets no row back and sends nothing, so a threshold is never
+ sent twice even if two processes run the job at once. The caller
+ must delete the claimed rows again (unclaim_thresholds) if the
+ send fails, so a failed send stays due and retries on the next
+ tick instead of being lost.
+ """
+ claimed = []
+ try:
+ with conn.cursor() as cur:
+ for w, threshold in due_pairs:
+ cur.execute(
+ """INSERT INTO notification_log (warranty_id, days_before, channel)
+ VALUES (%s, %s, %s) ON CONFLICT DO NOTHING
+ RETURNING warranty_id, days_before""",
+ (w.get('warranty_id'), threshold, channel),
+ )
+ if cur.fetchone():
+ claimed.append((w, threshold))
+ conn.commit()
+ except Exception as e:
+ logger.error(f"Error claiming threshold notifications: {e}")
+ try:
+ conn.rollback()
+ except Exception:
+ pass
+ return []
+ return claimed
+
+
+def unclaim_thresholds(pairs, channel, conn):
+ """Delete claimed rows again so a failed send stays due (#299)."""
+ if not pairs:
+ return
+ try:
+ with conn.cursor() as cur:
+ for w, threshold in pairs:
+ cur.execute(
+ "DELETE FROM notification_log WHERE warranty_id = %s "
+ "AND days_before = %s AND channel = %s",
+ (w.get('warranty_id'), threshold, channel),
+ )
+ conn.commit()
+ except Exception as e:
+ logger.error(f"Error releasing claimed threshold notifications: {e}")
+ try:
+ conn.rollback()
+ except Exception:
+ pass
+
def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual, get_db_connection, release_db_connection):
"""Process and send Apprise notifications"""
# ---> FIX: Get the handler from the application context <---
@@ -490,7 +551,13 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
return
logger.info(f"Processing Apprise notifications for {len(eligible_user_ids)} eligible users.")
-
+
+ # Thresholds claimed by this run and thresholds already recorded as
+ # sent. If the run fails part-way, the claimed-but-unrecorded ones
+ # are released again so they stay due and retry (#299).
+ claimed_pairs = []
+ recorded_pairs = []
+
try:
# Reload configuration to ensure we have the latest settings from the database
apprise_handler.reload_configuration()
@@ -574,6 +641,25 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
if not due_pairs:
logger.info("No threshold notifications due; skipping Apprise send")
return
+ # Claim the due thresholds up front (#299): only the pairs this
+ # process actually inserts are sent, so a concurrent copy of the
+ # job cannot send the same threshold twice.
+ claim_conn = None
+ try:
+ claim_conn = get_db_connection()
+ claimed_pairs = claim_thresholds(due_pairs, 'apprise', claim_conn)
+ except Exception as e:
+ logger.error(f"Error claiming threshold notifications: {e}")
+ finally:
+ if claim_conn:
+ try:
+ release_db_connection(claim_conn)
+ except Exception:
+ pass
+ if not claimed_pairs:
+ logger.info("No threshold notifications claimed; skipping Apprise send")
+ return
+ due_pairs = claimed_pairs
warranties_for_apprise = [w for w, _ in due_pairs]
logger.info(f"{len(warranties_for_apprise)} warranties due for a threshold notification")
@@ -582,6 +668,7 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
try:
rc = get_db_connection()
mark_thresholds_sent(pairs, 'apprise', rc)
+ recorded_pairs.extend(pairs)
except Exception as e:
logger.error(f"Error recording sent notifications: {e}")
finally:
@@ -591,6 +678,20 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
except Exception:
pass
+ def _unclaim(pairs):
+ rc = None
+ try:
+ rc = get_db_connection()
+ unclaim_thresholds(pairs, 'apprise', rc)
+ except Exception as e:
+ logger.error(f"Error releasing claimed notifications: {e}")
+ finally:
+ if rc:
+ try:
+ release_db_connection(rc)
+ except Exception:
+ pass
+
if notification_mode == 'global':
# GLOBAL MODE: Send one consolidated notification
logger.info("Sending GLOBAL Apprise notification")
@@ -598,13 +699,15 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
logger.info(f"Global Apprise notification result: {'Success' if success else 'Failed'}")
if success:
_record_sent(due_pairs)
-
+ else:
+ _unclaim(due_pairs)
+
elif notification_mode == 'individual':
# INDIVIDUAL MODE: Send one notification per user
logger.info("Sending INDIVIDUAL Apprise notifications")
sent_count = 0
error_count = 0
-
+
# Group due warranties by user
user_warranties = {}
user_pairs = {}
@@ -612,7 +715,7 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
uid = w['user_id']
user_warranties.setdefault(uid, []).append(w)
user_pairs.setdefault(uid, []).append((w, threshold))
-
+
# Send notification for each user
for user_id, warranties in user_warranties.items():
try:
@@ -624,17 +727,33 @@ def process_apprise_notifications(all_warranties, eligible_user_ids, is_manual,
else:
error_count += 1
logger.warning(f"Individual Apprise notification failed for user {user_id}")
+ _unclaim(user_pairs[user_id])
except Exception as e:
logger.error(f"Error sending individual Apprise notification for user {user_id}: {e}")
error_count += 1
-
+ _unclaim(user_pairs[user_id])
+
logger.info(f"Individual Apprise notifications completed: {sent_count} sent, {error_count} errors")
-
+
else:
logger.warning(f"Unknown Apprise notification mode: '{notification_mode}'. Skipping Apprise notifications.")
-
+ _unclaim(due_pairs)
+
except Exception as e:
logger.error(f"Error sending Apprise notifications: {e}")
+ # A failure part-way through must not leave claimed thresholds
+ # marked as sent: release the ones that were never recorded so
+ # they stay due and retry on the next tick.
+ unsent = [p for p in claimed_pairs if p not in recorded_pairs]
+ if unsent:
+ try:
+ rc = get_db_connection()
+ try:
+ unclaim_thresholds(unsent, 'apprise', rc)
+ finally:
+ release_db_connection(rc)
+ except Exception:
+ pass
def send_expiration_notifications(manual_trigger=False, get_db_connection=None, release_db_connection=None):
"""
@@ -774,62 +893,92 @@ def send_expiration_notifications(manual_trigger=False, get_db_connection=None,
notification_lock.release()
def should_run_scheduler():
- """Check if this is the main process that should run the scheduler."""
- # This environment variable is set by the post_fork hook in gunicorn_config.py
+ """Check if this process should start the scheduler from create_app.
+
+ Under gunicorn the scheduler is started exactly once, in the master
+ from when_ready, so create_app must never start it there: the master
+ would start it before forking and every worker would inherit a
+ running copy (#299). Workers never run create_app under preload
+ anyway. Outside gunicorn (dev server, single process) the single
+ process runs it. WARRACKER_GUNICORN_MASTER is set by the gunicorn
+ config at import time, before the preloaded app loads.
+ """
worker_id = os.environ.get('GUNICORN_WORKER_ID')
- # Case 1: Multi-worker environment (e.g., 'optimized', 'performance' modes).
- # The worker_id is explicitly set. Only worker '0' should run the scheduler.
if worker_id is not None:
- if worker_id == '0':
- logger.info(f"✅ Scheduler will run in this primary worker (ID: {worker_id}).")
- return True
- else:
- logger.info(f"ℹ️ Scheduler will NOT run in this secondary worker (ID: {worker_id}).")
- return False
+ logger.info(f"ℹ️ Scheduler will NOT run in this worker (ID: {worker_id}); it runs in the gunicorn master.")
+ return False
+
+ if os.environ.get('WARRACKER_GUNICORN_MASTER'):
+ logger.info("ℹ️ Scheduler will NOT run in the gunicorn master from create_app; it is started from when_ready.")
+ return False
- # Case 2: Single-worker environment (e.g., 'ultra-light' mode or Flask dev server).
- # The worker_id is not set (is None). In this case, the single worker must run the scheduler.
logger.info(f"✅ Scheduler will run: Single-worker environment detected (Worker ID not set).")
return True
-def init_scheduler(app, get_db_connection, release_db_connection):
- """Initialize the scheduler if this is the appropriate worker"""
+
+def discard_inherited_scheduler():
+ """Drop a scheduler inherited across a fork, without closing it.
+
+ Under gunicorn with preload_app the master starts the scheduler
+ before forking, so every worker inherits a running copy (#299).
+ That copy must never send. Shutting it down would join its thread,
+ which is a copy of the master's dead thread, so instead remove its
+ only job and mark it stopped: the loop then exits on its next
+ wakeup having sent nothing. The master keeps the real scheduler.
+ Safe to call when no scheduler exists.
+ """
global scheduler, scheduler_initialized
-
- if should_run_scheduler():
- try:
- # Initialize scheduler if not already done
- if scheduler is None:
- # First try GeventScheduler if gevent is available and we're in a gevent worker
- worker_class = os.environ.get('GUNICORN_WORKER_CLASS', '')
-
- if GEVENT_SCHEDULER_AVAILABLE and worker_class == 'gevent':
- try:
- scheduler = GeventScheduler(
- job_defaults={
- 'coalesce': True,
- 'max_instances': 1,
- 'misfire_grace_time': 300
- }
- )
- logger.info("Using GeventScheduler for gevent worker compatibility")
- except Exception as gevent_error:
- logger.warning(f"Failed to initialize GeventScheduler: {gevent_error}")
- logger.info("Falling back to BackgroundScheduler")
- if BACKGROUND_SCHEDULER_AVAILABLE:
- scheduler = BackgroundScheduler(
- job_defaults={
- 'coalesce': True,
- 'max_instances': 1,
- 'misfire_grace_time': 300
- }
- )
- logger.info("Using BackgroundScheduler (GeventScheduler fallback)")
- else:
- logger.error("BackgroundScheduler not available for fallback")
- return False
- else:
+ if scheduler is None:
+ return
+ try:
+ scheduler.remove_job('notification_job')
+ except Exception:
+ pass
+ try:
+ scheduler.state = STATE_STOPPED
+ except Exception:
+ pass
+ scheduler = None
+ scheduler_initialized = False
+ logger.info("ℹ️ Discarded scheduler inherited from the gunicorn master; this worker will not send notifications.")
+
+
+def init_scheduler(app, get_db_connection, release_db_connection, force=False):
+ """Initialize the scheduler if this is the appropriate process.
+
+ With force=True the should_run_scheduler check is skipped; the
+ gunicorn when_ready hook uses that to start the single scheduler
+ in the master. A second call is a no-op when the job already
+ exists, so create_app and when_ready (or app.py) cannot add the
+ job twice.
+ """
+ global scheduler, scheduler_initialized
+
+ if not force and not should_run_scheduler():
+ logger.info("ℹ️ Scheduler not started in this process")
+ scheduler_initialized = False
+ return False
+
+ try:
+ # Initialize scheduler if not already done
+ if scheduler is None:
+ # First try GeventScheduler if gevent is available and we're in a gevent worker
+ worker_class = os.environ.get('GUNICORN_WORKER_CLASS', '')
+
+ if GEVENT_SCHEDULER_AVAILABLE and worker_class == 'gevent':
+ try:
+ scheduler = GeventScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
+ )
+ logger.info("Using GeventScheduler for gevent worker compatibility")
+ except Exception as gevent_error:
+ logger.warning(f"Failed to initialize GeventScheduler: {gevent_error}")
+ logger.info("Falling back to BackgroundScheduler")
if BACKGROUND_SCHEDULER_AVAILABLE:
scheduler = BackgroundScheduler(
job_defaults={
@@ -838,38 +987,58 @@ def init_scheduler(app, get_db_connection, release_db_connection):
'misfire_grace_time': 300
}
)
- if worker_class == 'gevent':
- logger.info("Using BackgroundScheduler with gevent worker (GeventScheduler not available)")
- else:
- logger.info(f"Using BackgroundScheduler with {worker_class} worker")
+ logger.info("Using BackgroundScheduler (GeventScheduler fallback)")
else:
- logger.error("No scheduler available (BackgroundScheduler not found)")
+ logger.error("BackgroundScheduler not available for fallback")
return False
-
- # ---> FIX: Create a wrapper that pushes an app context <---
- def notification_job_with_context():
- with app.app_context():
- send_expiration_notifications(
- manual_trigger=False,
- get_db_connection=get_db_connection,
- release_db_connection=release_db_connection
+ else:
+ if BACKGROUND_SCHEDULER_AVAILABLE:
+ scheduler = BackgroundScheduler(
+ job_defaults={
+ 'coalesce': True,
+ 'max_instances': 1,
+ 'misfire_grace_time': 300
+ }
)
+ if worker_class == 'gevent':
+ logger.info("Using BackgroundScheduler with gevent worker (GeventScheduler not available)")
+ else:
+ logger.info(f"Using BackgroundScheduler with {worker_class} worker")
+ else:
+ logger.error("No scheduler available (BackgroundScheduler not found)")
+ return False
+
+ # ---> FIX: Create a wrapper that pushes an app context <---
+ def notification_job_with_context():
+ with app.app_context():
+ send_expiration_notifications(
+ manual_trigger=False,
+ get_db_connection=get_db_connection,
+ release_db_connection=release_db_connection
+ )
- # Schedule the new context-aware wrapper
+ # Only add the job once: a second init_scheduler call (from
+ # app.py after create_app, or from when_ready after create_app)
+ # used to re-add it and fail with ConflictingIdError.
+ if scheduler.get_job('notification_job') is None:
scheduler.add_job(func=notification_job_with_context, trigger="interval", minutes=2, id='notification_job')
- scheduler.start()
+ if not scheduler.running:
+ scheduler.start()
logger.info("✅ Notification scheduler started - checking every 2 minutes")
-
- # Add a shutdown hook
- atexit.register(lambda: scheduler.shutdown())
- scheduler_initialized = True
- return True
- except Exception as e:
- logger.error(f"❌ Failed to start scheduler: {e}")
- scheduler_initialized = False
- return False
- else:
- logger.info("ℹ️ Scheduler not started in this worker")
+
+ # Add a shutdown hook. Guard against the scheduler having
+ # been discarded (set to None) by a forked worker, or
+ # already stopped by another hook; the hook is inherited
+ # across the fork too, so more than one may be registered.
+ atexit.register(lambda: scheduler.shutdown()
+ if scheduler is not None and scheduler.running
+ else None)
+ else:
+ logger.info("ℹ️ Notification scheduler already running; keeping the existing job")
+ scheduler_initialized = True
+ return True
+ except Exception as e:
+ logger.error(f"❌ Failed to start scheduler: {e}")
scheduler_initialized = False
return False
diff --git a/tests/test_scheduler_single_process.py b/tests/test_scheduler_single_process.py
new file mode 100644
index 0000000..cc3be0a
--- /dev/null
+++ b/tests/test_scheduler_single_process.py
@@ -0,0 +1,231 @@
+"""Notification scheduler runs in exactly one process (#299).
+
+create_app must never start the scheduler under gunicorn (the master
+would start it before forking and every worker would inherit a running
+copy); the single scheduler is started in the master from when_ready.
+Threshold sends are claimed up front so a concurrent copy cannot send
+the same threshold twice, and a forked worker discards the inherited
+database pool without closing it (closing would kill the master's
+connections).
+"""
+import os
+import types
+from datetime import date, timedelta
+
+import pytest
+from flask import Flask
+
+import backend.db_handler as db_handler
+import backend.notifications as notifications
+from backend.notifications import (
+ claim_thresholds,
+ discard_inherited_scheduler,
+ filter_to_due_thresholds,
+ init_scheduler,
+ mark_thresholds_sent,
+ should_run_scheduler,
+ unclaim_thresholds,
+)
+
+TODAY = date.today()
+
+
+def _set_env(monkeypatch, master=False, worker=None):
+ """Set exactly the scheduler environment for one scenario."""
+ monkeypatch.delenv("WARRACKER_GUNICORN_MASTER", raising=False)
+ monkeypatch.delenv("GUNICORN_WORKER_ID", raising=False)
+ if master:
+ monkeypatch.setenv("WARRACKER_GUNICORN_MASTER", "1")
+ if worker is not None:
+ monkeypatch.setenv("GUNICORN_WORKER_ID", str(worker))
+
+
+# --- should_run_scheduler: only a non-gunicorn process starts it ---
+
+def test_should_run_in_dev_server(monkeypatch):
+ _set_env(monkeypatch)
+ assert should_run_scheduler() is True
+
+
+def test_should_not_run_in_gunicorn_master(monkeypatch):
+ _set_env(monkeypatch, master=True)
+ assert should_run_scheduler() is False
+
+
+def test_should_not_run_in_any_gunicorn_worker(monkeypatch):
+ for worker_id in ("0", "1", "2"):
+ _set_env(monkeypatch, master=True, worker=worker_id)
+ assert should_run_scheduler() is False
+
+
+def test_should_not_run_in_worker_without_master_flag(monkeypatch):
+ _set_env(monkeypatch, worker="0")
+ assert should_run_scheduler() is False
+
+
+def test_should_run_in_gunicorn_master_without_config_flag(monkeypatch):
+ # Fallback for a gunicorn invocation that does not use our config:
+ # nothing marks the master, so the old single-process behavior
+ # applies rather than losing notifications entirely.
+ _set_env(monkeypatch)
+ assert should_run_scheduler() is True
+
+
+# --- claim_thresholds: only one of two concurrent claims wins ---
+
+def _user_id(db_connection, username):
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))
+ return cur.fetchone()[0]
+
+
+def _insert_warranty(db_connection, user_id):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO warranties (product_name, purchase_date, "
+ "expiration_date, user_id, is_lifetime, archived_at, voided_at) "
+ "VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id",
+ ("Claim Test", TODAY - timedelta(days=300),
+ TODAY + timedelta(days=7), user_id, False, None, None),
+ )
+ return cur.fetchone()[0]
+
+
+def due_pair(client, user_factory, db_connection):
+ user = user_factory()
+ wid = _insert_warranty(db_connection, _user_id(db_connection, user["username"]))
+ return ({"warranty_id": wid}, 7)
+
+
+def test_claim_wins_once_across_two_connections(due_pair):
+ conn1 = db_handler.get_db_connection()
+ conn2 = db_handler.get_db_connection()
+ try:
+ assert claim_thresholds([due_pair], "apprise", conn1) == [due_pair]
+ assert claim_thresholds([due_pair], "apprise", conn2) == []
+ finally:
+ db_handler.release_db_connection(conn1)
+ db_handler.release_db_connection(conn2)
+
+
+def test_unclaim_makes_threshold_due_again(due_pair):
+ conn = db_handler.get_db_connection()
+ try:
+ assert claim_thresholds([due_pair], "apprise", conn) == [due_pair]
+ assert claim_thresholds([due_pair], "apprise", conn) == []
+ unclaim_thresholds([due_pair], "apprise", conn)
+ assert claim_thresholds([due_pair], "apprise", conn) == [due_pair]
+ finally:
+ db_handler.release_db_connection(conn)
+
+
+def test_mark_after_claim_keeps_record(due_pair):
+ conn = db_handler.get_db_connection()
+ try:
+ claim_thresholds([due_pair], "apprise", conn)
+ mark_thresholds_sent([due_pair], "apprise", conn)
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT COUNT(*) FROM notification_log "
+ "WHERE warranty_id = %s AND days_before = %s AND channel = %s",
+ (due_pair[0]["warranty_id"], 7, "apprise"),
+ )
+ assert cur.fetchone()[0] == 1
+ assert claim_thresholds([due_pair], "apprise", conn) == []
+ finally:
+ db_handler.release_db_connection(conn)
+
+
+def test_filter_excludes_claimed_threshold(due_pair):
+ conn = db_handler.get_db_connection()
+ try:
+ claim_thresholds([due_pair], "apprise", conn)
+ assert filter_to_due_thresholds(
+ [due_pair[0]], [30, 7], "apprise", conn) == []
+ finally:
+ db_handler.release_db_connection(conn)
+
+
+# --- discard_inherited_scheduler: a forked copy never sends ---
+
+def test_discard_with_no_scheduler_is_a_noop(monkeypatch):
+ monkeypatch.setattr(notifications, "scheduler", None)
+ monkeypatch.setattr(notifications, "scheduler_initialized", False)
+ discard_inherited_scheduler()
+ assert notifications.scheduler is None
+ assert notifications.scheduler_initialized is False
+
+
+def test_discard_removes_job_and_marks_stopped(monkeypatch):
+ removed = []
+ fake = types.SimpleNamespace(
+ remove_job=lambda job_id: removed.append(job_id),
+ state=1,
+ )
+ monkeypatch.setattr(notifications, "scheduler", fake)
+ monkeypatch.setattr(notifications, "scheduler_initialized", True)
+ discard_inherited_scheduler()
+ assert removed == ["notification_job"]
+ assert fake.state == 0
+ assert notifications.scheduler is None
+ assert notifications.scheduler_initialized is False
+
+
+# --- init_scheduler: a second call cannot add the job twice ---
+
+def test_init_scheduler_twice_adds_one_job(monkeypatch):
+ _set_env(monkeypatch)
+ app = Flask(__name__)
+ # The app fixture already started a scheduler in this process; set
+ # it aside so this test owns the scheduler it makes, then restore
+ # it live (shutting down a scheduler this test did not create
+ # would leave a dead reference behind for the atexit hook).
+ saved_scheduler = notifications.scheduler
+ saved_initialized = notifications.scheduler_initialized
+ saved_retry = notifications.scheduler_retry_attempted
+ notifications.scheduler = None
+ notifications.scheduler_initialized = False
+ notifications.scheduler_retry_attempted = False
+ mine = None
+ try:
+ assert init_scheduler(
+ app, db_handler.get_db_connection,
+ db_handler.release_db_connection) is True
+ assert init_scheduler(
+ app, db_handler.get_db_connection,
+ db_handler.release_db_connection) is True
+ mine = notifications.scheduler
+ assert [j.id for j in mine.get_jobs()] == ["notification_job"]
+ finally:
+ if mine is not None:
+ try:
+ mine.shutdown()
+ except Exception:
+ pass
+ notifications.scheduler = saved_scheduler
+ notifications.scheduler_initialized = saved_initialized
+ notifications.scheduler_retry_attempted = saved_retry
+
+
+# --- _close_stale_pool_if_forked: discard without closing ---
+
+def test_forked_pool_is_discarded_and_recreated(db_connection):
+ real_pool = db_handler.connection_pool
+ assert real_pool is not None
+ db_handler.pool_pid = os.getpid() + 999999
+ try:
+ db_handler._close_stale_pool_if_forked(os.getpid())
+ assert db_handler.connection_pool is None
+ assert db_handler.pool_pid is None
+ conn = db_handler.get_db_connection()
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT 1")
+ assert cur.fetchone()[0] == 1
+ finally:
+ db_handler.release_db_connection(conn)
+ finally:
+ # The discarded pool is gone for good; the fresh pool created
+ # above is the live one now. Nothing to restore.
+ pass