Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

soft_deactivation: Allow a dedicated queue for soft reactivations.

Aman Agrawal7fd8bfb1c6e6
diff --git a/docs/production/system-configuration.md b/docs/production/system-configuration.md
index 8bb1dd275ac..9e920725ab5 100644
--- a/docs/production/system-configuration.md
+++ b/docs/production/system-configuration.md
@@ -148,6 +148,17 @@ using remote servers for PostgreSQL, memcached, Redis, and RabbitMQ.
[docker-memory-limit]: https://docs.docker.com/reference/compose-file/deploy/#memory
+#### `dedicated_soft_reactivation_queue`
+
+When a long-term-idle user returns, Zulip backfills the message-history
+rows that were skipped while they were idle; this "soft reactivation"
+can take many seconds. By default it runs in the shared `deferred_work`
+queue, alongside jobs such as data exports that can take minutes. Set
+this to true to process soft reactivations in a dedicated queue (and, in
+multiprocess mode, a dedicated worker process), so they aren't delayed
+behind such jobs. This costs an additional worker process, so it is most
+useful on large servers; smaller servers should leave it disabled.
+
#### `rolling_restart`
If set to true, when using `./scripts/restart-server` to restart
diff --git a/docs/subsystems/queuing.md b/docs/subsystems/queuing.md
index 18b37f15ca5..c65edcd5eea 100644
--- a/docs/subsystems/queuing.md
+++ b/docs/subsystems/queuing.md
@@ -44,7 +44,7 @@ To add a new queue processor:
`./manage.py process_queue --queue=user_activity`.
- So that supervisord will know to run the queue processor in
- production, you will need to add to the `queues` variable in
+ production, you will need to add to the `base_queues` variable in
`puppet/zulip/manifests/app_frontend_base.pp`; the list there is
used to generate `/etc/supervisor/conf.d/zulip.conf`.
diff --git a/puppet/kandra/files/nagios4/conf.d/services.cfg b/puppet/kandra/files/nagios4/conf.d/services.cfg
index c487e4910c4..41ae36e20ea 100644
--- a/puppet/kandra/files/nagios4/conf.d/services.cfg
+++ b/puppet/kandra/files/nagios4/conf.d/services.cfg
@@ -382,6 +382,12 @@ define service {
check_command check_rabbitmq_consumers!outgoing_webhooks
}
+define service {
+ use rabbitmq-consumer-service
+ service_description Check RabbitMQ soft_reactivation consumers
+ check_command check_rabbitmq_consumers!soft_reactivation
+}
+
define service {
use rabbitmq-consumer-service
service_description Check RabbitMQ thumbnail consumers
diff --git a/puppet/zulip/manifests/app_frontend_base.pp b/puppet/zulip/manifests/app_frontend_base.pp
index 8b87f7c9e66..0360b57b087 100644
--- a/puppet/zulip/manifests/app_frontend_base.pp
+++ b/puppet/zulip/manifests/app_frontend_base.pp
@@ -150,7 +150,7 @@ class zulip::app_frontend_base {
# of memory.
$queues_multiprocess_default = $zulip::common::total_memory_mb > 3800
$queues_multiprocess = zulipconf('application_server', 'queue_workers_multiprocess', $queues_multiprocess_default)
- $queues = [
+ $base_queues = [
'deferred_work',
'digest_emails',
'email_mirror',
@@ -165,6 +165,12 @@ class zulip::app_frontend_base {
'user_activity',
'user_activity_interval',
]
+ # Soft reactivations normally share the deferred_work queue; larger
+ # servers can opt into a dedicated queue (and worker process) for them.
+ $queues = zulipconf('application_server', 'dedicated_soft_reactivation_queue', false) ? {
+ true => $base_queues + ['soft_reactivation'],
+ default => $base_queues,
+ }
if $zulip::common::total_memory_mb > 24000 {
$uwsgi_default_processes = 16
diff --git a/scripts/lib/check_rabbitmq_queue.py b/scripts/lib/check_rabbitmq_queue.py
index 669522df441..33f3cce6dd5 100644
--- a/scripts/lib/check_rabbitmq_queue.py
+++ b/scripts/lib/check_rabbitmq_queue.py
@@ -28,6 +28,11 @@ normal_queues = [
"user_activity_interval",
]
+# Soft reactivations share the deferred_work queue unless a server opts
+# into a dedicated queue; only then is there a consumer to monitor.
+if get_config(get_config_file(), "application_server", "dedicated_soft_reactivation_queue", False):
+ normal_queues.append("soft_reactivation")
+
mobile_notification_shards = int(
get_config(get_config_file(), "application_server", "mobile_notification_shards", "1")
)
@@ -50,6 +55,10 @@ states = {
MAX_SECONDS_TO_CLEAR: defaultdict[str, int] = defaultdict(
lambda: 30,
deferred_work=600,
+ # Soft reactivations are the deferred_work backfills split into their
+ # own queue; keep deferred_work's generous clear-time budget so the slow
+ # backfills that motivated the split don't trip false alerts.
+ soft_reactivation=600,
digest_emails=1200,
missedmessage_mobile_notifications=120,
embed_links=60,
@@ -59,6 +68,7 @@ MAX_SECONDS_TO_CLEAR: defaultdict[str, int] = defaultdict(
CRITICAL_SECONDS_TO_CLEAR: defaultdict[str, int] = defaultdict(
lambda: 60,
deferred_work=900,
+ soft_reactivation=900,
missedmessage_mobile_notifications=180,
digest_emails=1800,
embed_links=90,
diff --git a/zerver/lib/soft_deactivation.py b/zerver/lib/soft_deactivation.py
index 8ef93e9902e..325d6199d3a 100644
--- a/zerver/lib/soft_deactivation.py
+++ b/zerver/lib/soft_deactivation.py
@@ -399,7 +399,10 @@ def queue_soft_reactivation(user_profile_id: int) -> None:
"type": "soft_reactivate",
"user_profile_id": user_profile_id,
}
- queue_event_on_commit("deferred_work", event)
+ if settings.DEDICATED_SOFT_REACTIVATION_QUEUE:
+ queue_event_on_commit("soft_reactivation", event)
+ else:
+ queue_event_on_commit("deferred_work", event)
def soft_reactivate_if_personal_notification(
diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.py
index b666e909f0a..fdb82d4e6cd 100644
--- a/zerver/tests/test_queue_worker.py
+++ b/zerver/tests/test_queue_worker.py
@@ -13,6 +13,7 @@ import orjson
import time_machine
from django.conf import settings
from django.db.utils import IntegrityError
+from django.test import override_settings
from typing_extensions import override
from zerver.lib.email_mirror_helpers import encode_email_address, get_channel_email_token
@@ -33,6 +34,7 @@ from zerver.worker.email_senders import ImmediateEmailSenderWorker
from zerver.worker.embed_links import FetchLinksEmbedData
from zerver.worker.missedmessage_emails import MissedMessageWorker
from zerver.worker.missedmessage_mobile_notifications import PushNotificationsWorker
+from zerver.worker.queue_processors import get_active_worker_queues
from zerver.worker.user_activity import UserActivityWorker
Event: TypeAlias = dict[str, Any]
@@ -828,3 +830,11 @@ class WorkerTest(ZulipTestCase):
with self.assertRaises(base_worker.WorkerDeclarationError):
TestWorker()
+
+ def test_soft_reactivation_queue_is_opt_in(self) -> None:
+ # The soft_reactivation worker only runs when a server opts into a
+ # dedicated queue; otherwise it must not appear in the active set, so
+ # the production-install queue-processor consistency check passes.
+ self.assertNotIn("soft_reactivation", get_active_worker_queues())
+ with override_settings(DEDICATED_SOFT_REACTIVATION_QUEUE=True):
+ self.assertIn("soft_reactivation", get_active_worker_queues())
diff --git a/zerver/tests/test_soft_deactivation.py b/zerver/tests/test_soft_deactivation.py
index 48167246276..c9e81b1b3b6 100644
--- a/zerver/tests/test_soft_deactivation.py
+++ b/zerver/tests/test_soft_deactivation.py
@@ -1,6 +1,7 @@
from collections.abc import Set as AbstractSet
from unittest import mock
+from django.test import override_settings
from django.utils.timezone import now as timezone_now
from zerver.actions.alert_words import do_add_alert_words
@@ -14,6 +15,7 @@ from zerver.lib.soft_deactivation import (
do_soft_deactivate_users,
get_soft_deactivated_users_for_catch_up,
get_users_for_soft_deactivation,
+ queue_soft_reactivation,
reactivate_user_if_soft_deactivated,
)
from zerver.lib.stream_subscription import get_subscriptions_for_send_message
@@ -138,6 +140,37 @@ class UserSoftDeactivationTests(ZulipTestCase):
user.refresh_from_db()
self.assertFalse(user.long_term_idle)
+ def test_soft_reactivation_uses_deferred_work_queue_by_default(self) -> None:
+ user = self.example_user("hamlet")
+ with mock.patch("zerver.lib.soft_deactivation.queue_event_on_commit") as mock_queue:
+ queue_soft_reactivation(user.id)
+ mock_queue.assert_called_once_with(
+ "deferred_work", {"type": "soft_reactivate", "user_profile_id": user.id}
+ )
+
+ @override_settings(DEDICATED_SOFT_REACTIVATION_QUEUE=True)
+ def test_soft_reactivation_uses_dedicated_queue_when_enabled(self) -> None:
+ user = self.example_user("hamlet")
+
+ # With the option enabled, reactivations route to the dedicated queue.
+ with mock.patch("zerver.lib.soft_deactivation.queue_event_on_commit") as mock_queue:
+ queue_soft_reactivation(user.id)
+ mock_queue.assert_called_once_with(
+ "soft_reactivation", {"type": "soft_reactivate", "user_profile_id": user.id}
+ )
+
+ # And the dedicated queue's worker reactivates the user end to end.
+ self.subscribe(user, "Denmark")
+ self.send_stream_message(user, "Denmark")
+ with self.assertLogs(logger_string, level="INFO"):
+ do_soft_deactivate_users([user])
+ user.refresh_from_db()
+ self.assertTrue(user.long_term_idle)
+ with self.captureOnCommitCallbacks(execute=True):
+ queue_soft_reactivation(user.id)
+ user.refresh_from_db()
+ self.assertFalse(user.long_term_idle)
+
def test_get_users_for_catch_up(self) -> None:
users = [
self.example_user("hamlet"),
diff --git a/zerver/worker/deferred_work.py b/zerver/worker/deferred_work.py
index 5630d108153..6273f4c2f3a 100644
--- a/zerver/worker/deferred_work.py
+++ b/zerver/worker/deferred_work.py
@@ -173,6 +173,13 @@ class DeferredWorker(QueueProcessingWorker):
logger.info("Processing reupload_realm_emoji event for realm %s", realm.id)
handle_reupload_emojis_event(realm, logger)
elif event["type"] == "soft_reactivate":
+ # Soft reactivations are normally enqueued here. A server can
+ # opt into a dedicated soft_reactivation queue via the
+ # dedicated_soft_reactivation_queue setting; even then, do not
+ # remove this handler. It remains the default path, and it
+ # drains any soft_reactivate events already in this queue when
+ # that option is enabled -- stale deferred_work events can
+ # linger across upgrades for a long time.
logger.info(
"Starting soft reactivation for user_profile_id %s",
event["user_profile_id"],
diff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.py
index f85836a42fb..de3065a4248 100644
--- a/zerver/worker/queue_processors.py
+++ b/zerver/worker/queue_processors.py
@@ -2,6 +2,8 @@
import importlib
import pkgutil
+from django.conf import settings
+
import zerver.worker
from zerver.worker.base import QueueProcessingWorker, test_queues, worker_classes
@@ -25,12 +27,18 @@ def get_worker(
def get_active_worker_queues(only_test_queues: bool = False) -> list[str]:
- """Returns all (either test, or real) worker queues."""
+ """Returns the worker queues that should run on this server, honoring
+ configuration that gates a queue on a setting."""
for module_info in pkgutil.iter_modules(zerver.worker.__path__, "zerver.worker."):
importlib.import_module(module_info.name)
- return [
+ queues = [
queue_name
for queue_name in worker_classes
if bool(queue_name in test_queues) == only_test_queues
]
+ if not settings.DEDICATED_SOFT_REACTIVATION_QUEUE:
+ # Soft reactivations share the deferred_work queue unless a server
+ # opts into a dedicated queue, so its worker is not run otherwise.
+ queues = [queue_name for queue_name in queues if queue_name != "soft_reactivation"]
+ return queues
diff --git a/zerver/worker/soft_reactivation.py b/zerver/worker/soft_reactivation.py
new file mode 100644
index 00000000000..f799b3b680e
--- /dev/null
+++ b/zerver/worker/soft_reactivation.py
@@ -0,0 +1,41 @@
+# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.html
+import logging
+from typing import Any
+
+from typing_extensions import override
+
+from zerver.lib.soft_deactivation import reactivate_user_if_soft_deactivated
+from zerver.models.users import get_user_profile_by_id
+from zerver.worker.base import QueueProcessingWorker, assign_queue
+
+logger = logging.getLogger(__name__)
+
+
+@assign_queue("soft_reactivation")
+class SoftReactivationWorker(QueueProcessingWorker):
+ """Backfills the UserMessage rows skipped while a long-term-idle user was
+ soft-deactivated, in response to a signal that the user is likely about to
+ return (a notification or password-reset email).
+
+ It's undesirable for these jobs to share the deferred_work queue with jobs
+ such as realm exports, which can take many minutes: a prolonged delay in
+ processing a soft reactivation gives the returning user a bad experience,
+ and can race with the synchronous reactivation that runs when the user
+ loads the app. A server can opt into this dedicated queue via the
+ DEDICATED_SOFT_REACTIVATION_QUEUE setting.
+ """
+
+ # Soft reactivation has always run without a per-event timeout, as part of
+ # the deferred_work queue, and the backfill for a very idle user can
+ # legitimately take a while; preserve that rather than risk killing a job
+ # partway through.
+ MAX_CONSUME_SECONDS = None
+
+ @override
+ def consume(self, event: dict[str, Any]) -> None:
+ logger.info(
+ "Starting soft reactivation for user_profile_id %s",
+ event["user_profile_id"],
+ )
+ user_profile = get_user_profile_by_id(event["user_profile_id"])
+ reactivate_user_if_soft_deactivated(user_profile)
diff --git a/zproject/computed_settings.py b/zproject/computed_settings.py
index f69c9dd1711..834185e081b 100644
--- a/zproject/computed_settings.py
+++ b/zproject/computed_settings.py
@@ -1276,6 +1276,17 @@ MOBILE_NOTIFICATIONS_SHARDS = int(
)
USER_ACTIVITY_SHARDS = int(get_config("application_server", "user_activity_shards", "1"))
+# Process soft reactivations in their own queue and worker process instead of
+# sharing deferred_work. This lives here, not in default_settings, because it
+# can only be configured via zulip.conf: enabling it requires a puppet apply
+# to actually run the dedicated worker, so a settings.py override would be
+# ineffective. Off by default so small servers don't pay for an extra worker
+# process; large servers can enable it so reactivations aren't delayed behind
+# long deferred_work jobs such as realm exports.
+DEDICATED_SOFT_REACTIVATION_QUEUE = get_config(
+ "application_server", "dedicated_soft_reactivation_queue", False
+)
+
TWO_FACTOR_PATCH_ADMIN = False
# Allow the environment to override the default DSN