Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
deferred_work: Allow a dedicated queue for high-latency jobs.
Aman Agrawal4139d5fa39c4
diff --git a/docs/production/system-configuration.md b/docs/production/system-configuration.mdindex 0b5ac1c8b3d..3b4ff27b3cc 100644--- a/docs/production/system-configuration.md+++ b/docs/production/system-configuration.md@@ -185,6 +185,24 @@ multiprocess mode, a dedicated worker process), so they aren't delayedbehind such jobs. This costs an additional worker process, so it is mostuseful on large servers; smaller servers should leave it disabled.+#### `dedicated_deferred_work_high_latency_queue`++Data exports and Slack imports can each take many minutes. By default,+they run in the shared `deferred_work` queue, where they delay faster+jobs, such as marking messages as read when a user unsubscribes from a+channel. Set this to true to process them in a dedicated queue (and, in+multiprocess mode, a dedicated worker process). Like+`dedicated_soft_reactivation_queue`, this is most useful on large+servers. The change takes effect only after you run `zulip-puppet-apply`+and then restart the server with+`/home/zulip/deployments/current/scripts/restart-server`.++To turn it back off, set it to false and restart the server, then wait+until `rabbitmqctl list_queues` (run as root) shows the+`deferred_work_high_latency` queue is empty before running+`zulip-puppet-apply`. Otherwise, any exports or imports still in that+queue will never be processed.+#### `rolling_restart`If set to true, when using `./scripts/restart-server` to restartdiff --git a/puppet/kandra/files/nagios4/conf.d/services.cfg b/puppet/kandra/files/nagios4/conf.d/services.cfgindex 41ae36e20ea..8a100d692bd 100644--- a/puppet/kandra/files/nagios4/conf.d/services.cfg+++ b/puppet/kandra/files/nagios4/conf.d/services.cfg@@ -327,6 +327,12 @@ define service {check_command check_rabbitmq_consumers!deferred_work}+define service {+ use rabbitmq-consumer-service+ service_description Check RabbitMQ deferred_work_high_latency consumers+ check_command check_rabbitmq_consumers!deferred_work_high_latency+}+define service {use rabbitmq-consumer-serviceservice_description Check RabbitMQ digest digest_emails consumersdiff --git a/puppet/zulip/manifests/app_frontend_base.pp b/puppet/zulip/manifests/app_frontend_base.ppindex e6ff589be36..a9a86441f9f 100644--- a/puppet/zulip/manifests/app_frontend_base.pp+++ b/puppet/zulip/manifests/app_frontend_base.pp@@ -171,7 +171,11 @@ class zulip::app_frontend_base {true => ['soft_reactivation'],default => [],}- $queues = $base_queues + $soft_reactivation_queue+ $high_latency_queue = zulipconf('application_server', 'dedicated_deferred_work_high_latency_queue', false) ? {+ true => ['deferred_work_high_latency'],+ default => [],+ }+ $queues = $base_queues + $soft_reactivation_queue + $high_latency_queueif $zulip::common::total_memory_mb > 24000 {$uwsgi_default_processes = 16diff --git a/scripts/lib/check_rabbitmq_queue.py b/scripts/lib/check_rabbitmq_queue.pyindex 33f3cce6dd5..906a7357b94 100644--- a/scripts/lib/check_rabbitmq_queue.py+++ b/scripts/lib/check_rabbitmq_queue.py@@ -28,11 +28,16 @@ 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.+# These queues exist only when a server opts into them; until then their+# events stay in deferred_work, and there is no consumer to monitor.if get_config(get_config_file(), "application_server", "dedicated_soft_reactivation_queue", False):normal_queues.append("soft_reactivation")+if get_config(+ get_config_file(), "application_server", "dedicated_deferred_work_high_latency_queue", False+):+ normal_queues.append("deferred_work_high_latency")+mobile_notification_shards = int(get_config(get_config_file(), "application_server", "mobile_notification_shards", "1"))@@ -59,6 +64,9 @@ MAX_SECONDS_TO_CLEAR: defaultdict[str, int] = defaultdict(# 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,+ # Every job in this queue can take many minutes, so even a single job+ # in flight makes the estimated time to clear the backlog that long.+ deferred_work_high_latency=3 * 60 * 60,digest_emails=1200,missedmessage_mobile_notifications=120,embed_links=60,@@ -69,6 +77,7 @@ CRITICAL_SECONDS_TO_CLEAR: defaultdict[str, int] = defaultdict(lambda: 60,deferred_work=900,soft_reactivation=900,+ deferred_work_high_latency=6 * 60 * 60,missedmessage_mobile_notifications=180,digest_emails=1800,embed_links=90,diff --git a/tools/tests/test_check_rabbitmq_queue.py b/tools/tests/test_check_rabbitmq_queue.pyindex b60c4fc068e..cc406915aaa 100644--- a/tools/tests/test_check_rabbitmq_queue.py+++ b/tools/tests/test_check_rabbitmq_queue.py@@ -31,6 +31,22 @@ class AnalyzeQueueStatsTests(TestCase):)self.assertEqual(result["status"], OK)+ def test_high_latency_queue_tolerates_a_single_long_job(self) -> None:+ """A single 30-minute job in flight is normal for this queue, unlike+ a backlog of them."""+ stats = {+ "update_time": time.time(),+ "queue_last_emptied_timestamp": time.time() - 1800,+ "recent_average_consume_time": 1800,+ }+ # The in-flight job is unacknowledged, so rabbitmqctl counts it.+ result = analyze_queue_stats("deferred_work_high_latency", stats, 1)+ self.assertEqual(result["status"], OK)++ result = analyze_queue_stats("deferred_work_high_latency", stats, 25)+ self.assertEqual(result["status"], CRITICAL)+ self.assertIn("clearing the backlog", result["message"])+def test_queue_normal(self) -> None:"""10000 events and each takes a second => it'll take a long time to empty."""result = analyze_queue_stats(diff --git a/zerver/lib/queue.py b/zerver/lib/queue.pyindex d0aabe72833..93499870a19 100644--- a/zerver/lib/queue.py+++ b/zerver/lib/queue.py@@ -473,6 +473,12 @@ def mobile_notifications_queue_name(user_id: int) -> str:return "missedmessage_mobile_notifications"+def high_latency_queue_name() -> str:+ if settings.DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE:+ return "deferred_work_high_latency"+ return "deferred_work"++def retry_event(queue_name: str, event: dict[str, Any], failure_processor: Callable[[dict[str, Any]], None]) -> None:diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.pyindex c6000af5f72..fa91db242e1 100644--- a/zerver/tests/test_queue_worker.py+++ b/zerver/tests/test_queue_worker.py@@ -889,3 +889,11 @@ class WorkerTest(ZulipTestCase):self.assertNotIn("soft_reactivation", get_active_worker_queues())with override_settings(DEDICATED_SOFT_REACTIVATION_QUEUE=True):self.assertIn("soft_reactivation", get_active_worker_queues())++ def test_high_latency_queue_is_opt_in(self) -> None:+ """Puppet runs this worker only when the setting is enabled, and+ tools/ci/production-verify checks that the active queues match+ the running workers."""+ self.assertNotIn("deferred_work_high_latency", get_active_worker_queues())+ with override_settings(DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE=True):+ self.assertIn("deferred_work_high_latency", get_active_worker_queues())diff --git a/zerver/tests/test_realm_export.py b/zerver/tests/test_realm_export.pyindex b9694fb5318..4282bf887d8 100644--- a/zerver/tests/test_realm_export.py+++ b/zerver/tests/test_realm_export.py@@ -7,6 +7,7 @@ import botocore.exceptionsimport orjsonimport time_machinefrom django.conf import settings+from django.test import override_settingsfrom django.utils.timezone import now as timezone_nowfrom analytics.models import RealmCount@@ -229,6 +230,25 @@ class RealmExportTest(ZulipTestCase):result = self.client_delete("/json/export/realm/0")self.assert_json_error(result, "Invalid data export ID")+ @override_settings(DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE=True)+ def test_export_uses_dedicated_queue_when_enabled(self) -> None:+ self.login("iago")+ tarball_path = create_dummy_file("test-export.tar.gz")+ with (+ patch("zerver.lib.export.do_export_realm", return_value=(tarball_path, dict())),+ stdout_suppressed(),+ self.assertLogs("zerver.worker.deferred_work_high_latency", level="INFO") as info_logs,+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self.client_post("/json/export/realm")+ export_id = self.assert_json_success(result)["id"]+ self.assertTrue(+ info_logs.output[1].startswith(+ "INFO:zerver.worker.deferred_work_high_latency:Completed data export for zulip in "+ )+ )+ self.assertEqual(RealmExport.objects.get(id=export_id).status, RealmExport.SUCCEEDED)+def test_export_tarball_prefix(self) -> None:realm = self.example_user("iago").realmwith time_machine.travel(diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.pyindex b63b91a298d..ac609e4da68 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -18,6 +18,7 @@ from attr import dataclassfrom django.conf import settingsfrom django.db import IntegrityErrorfrom django.http import HttpResponse+from django.test import override_settingsfrom django.utils.timezone import now as timezone_nowfrom requests.models import PreparedRequest@@ -73,6 +74,7 @@ from zerver.data_import.slack import (from zerver.lib.exceptions import SlackImportInvalidFileErrorfrom zerver.lib.import_realm import do_import_realmfrom zerver.lib.mime_types import INLINE_MIME_TYPES+from zerver.lib.queue import high_latency_queue_namefrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import find_key_by_email, read_test_image_filefrom zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPES, BadImageError@@ -2727,7 +2729,7 @@ To Do# Set by the user performing the import.importer_set_email_address_visibility = UserProfile.EMAIL_ADDRESS_VISIBILITY_NOBODY- # Check that deferred_work for import is queued.+ # Check that the import is queued.with mock.patch("zerver.views.registration.queue_json_publish_rollback_unsafe") as m:result = self.client_post("/new/import/slack/",@@ -2746,7 +2748,7 @@ To Do)m.assert_called_once_with(- "deferred_work",+ high_latency_queue_name(),{"type": "import_slack_data","preregistration_realm_id": prereg_realm.id,@@ -2805,7 +2807,7 @@ To Dofrom zerver.lib.queue import queue_json_publish_rollback_unsafequeue_json_publish_rollback_unsafe(- "deferred_work",+ high_latency_queue_name(),{"type": "import_slack_data","preregistration_realm_id": prereg_realm.id,@@ -2913,6 +2915,13 @@ To Doresult = self.client_get(f"/realm/import/post_process/{confirmation_key}")self.assert_in_success_response(["Select your account"], result)+ @override_settings(DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE=True)+ def test_end_to_end_slack_import_with_dedicated_queue(self) -> None:+ """test_end_to_end_slack_import checks that the import is queued on+ high_latency_queue_name(), and processes it from that queue."""+ self.assertEqual(high_latency_queue_name(), "deferred_work_high_latency")+ self.test_end_to_end_slack_import()+@mock.patch("zerver.actions.data_import.do_import_realm")@mock.patch("zerver.actions.data_import.do_convert_zipfile")@mock.patch("zerver.actions.data_import.save_attachment_contents")diff --git a/zerver/views/realm_export.py b/zerver/views/realm_export.pyindex 3a923d7e62a..569c1c711da 100644--- a/zerver/views/realm_export.py+++ b/zerver/views/realm_export.py@@ -11,7 +11,7 @@ from zerver.actions.realm_export import do_delete_realm_export, notify_realm_expfrom zerver.decorator import require_realm_adminfrom zerver.lib.exceptions import JsonableError, OrganizationOwnerRequiredErrorfrom zerver.lib.export import get_realm_exports_serialized-from zerver.lib.queue import queue_event_on_commit+from zerver.lib.queue import high_latency_queue_name, queue_event_on_commitfrom zerver.lib.response import json_successfrom zerver.lib.send_email import FromAddressfrom zerver.lib.typed_endpoint import typed_endpoint@@ -107,14 +107,13 @@ def export_realm(# Allow for UI updates on a pending exportnotify_realm_export(realm)- # Using the deferred_work queue processor to avoid- # killing the process after 60s+ # Run in a queue processor to avoid killing the process after 60s.event = {"type": "realm_export","user_profile_id": user.id,"realm_export_id": row.id,}- queue_event_on_commit("deferred_work", event)+ queue_event_on_commit(high_latency_queue_name(), event)return json_success(request, data={"id": row.id})diff --git a/zerver/views/registration.py b/zerver/views/registration.pyindex 69106f0b678..3dcf271f20b 100644--- a/zerver/views/registration.py+++ b/zerver/views/registration.py@@ -80,7 +80,7 @@ from zerver.lib.i18n import (get_language_name,)from zerver.lib.pysa import mark_sanitized-from zerver.lib.queue import queue_json_publish_rollback_unsafe+from zerver.lib.queue import high_latency_queue_name, queue_json_publish_rollback_unsafefrom zerver.lib.rate_limiter import rate_limit_request_by_ip, readable_expiry_string_for_htmlfrom zerver.lib.response import json_successfrom zerver.lib.send_email import EmailNotDeliveredError, FromAddress, send_email@@ -445,7 +445,7 @@ def registration_helper(logger.info("(%s) Enqueueing Slack import", prereg_realm.string_id)queue_json_publish_rollback_unsafe(- "deferred_work",+ high_latency_queue_name(),{"type": "import_slack_data","preregistration_realm_id": prereg_realm.id,diff --git a/zerver/worker/deferred_work_high_latency.py b/zerver/worker/deferred_work_high_latency.pynew file mode 100644index 00000000000..271dc873c9e--- /dev/null+++ b/zerver/worker/deferred_work_high_latency.py@@ -0,0 +1,41 @@+# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.html+import logging+import time+from typing import Any++from typing_extensions import override++from zerver.actions.data_import import import_slack_data+from zerver.actions.realm_export import handle_realm_export_event+from zerver.worker.base import QueueProcessingWorker, assign_queue++logger = logging.getLogger(__name__)+++@assign_queue("deferred_work_high_latency")+class DeferredWorkHighLatencyWorker(QueueProcessingWorker):+ """Runs the deferred_work jobs that can take many minutes, such as+ realm exports and Slack imports, so that they don't delay the+ latency-sensitive jobs in that queue. A server can opt into this+ dedicated queue via the DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE+ setting.+ """++ MAX_CONSUME_SECONDS = None++ @override+ def consume(self, event: dict[str, Any]) -> None:+ start = time.time()+ if event["type"] == "realm_export":+ handle_realm_export_event(event, threaded=self.threaded, logger=logger)+ elif event["type"] == "import_slack_data":+ import_slack_data(event)+ else:+ raise AssertionError(f"Unexpected event type {event['type']}")++ end = time.time()+ logger.info(+ "deferred_work_high_latency processed %s event (%dms)",+ event["type"],+ (end - start) * 1000,+ )diff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.pyindex ee643c51d8b..0337ae6b1c0 100644--- a/zerver/worker/queue_processors.py+++ b/zerver/worker/queue_processors.py@@ -34,6 +34,7 @@ def get_active_worker_queues(only_test_queues: bool = False) -> list[str]:opt_in_queue_enabled = {"soft_reactivation": settings.DEDICATED_SOFT_REACTIVATION_QUEUE,+ "deferred_work_high_latency": settings.DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE,}return [queue_namediff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex a805944893a..ec1d5089af2 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -1298,6 +1298,12 @@ DEDICATED_SOFT_REACTIVATION_QUEUE = get_config("application_server", "dedicated_soft_reactivation_queue", False)+# For the deferred_work jobs that can take many minutes, such as realm+# exports and Slack imports.+DEDICATED_DEFERRED_WORK_HIGH_LATENCY_QUEUE = get_config(+ "application_server", "dedicated_deferred_work_high_latency_queue", False+)+TWO_FACTOR_PATCH_ADMIN = False# Allow the environment to override the default DSN