From e466e47c496d073d849e89ef8f0fcd43c6a06ae6 Mon Sep 17 00:00:00 2001 From: Kegan Dougal <7190048+kegsay@users.noreply.github.com> Date: Thu, 19 Mar 2026 14:59:10 +0000 Subject: [PATCH] Decrease GC tick frequency; only create instance IDs if we'll use them Both _maybe_gc and random_string_insecure_fast feature in CPU profiles. --- synapse/logging/context.py | 18 +++++++++++++++--- synapse/metrics/_gc.py | 3 ++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/synapse/logging/context.py b/synapse/logging/context.py index b6535be388..6cb2c54d79 100644 --- a/synapse/logging/context.py +++ b/synapse/logging/context.py @@ -693,7 +693,11 @@ class PreserveLoggingContext: self, new_context: LoggingContextOrSentinel = SENTINEL_CONTEXT ) -> None: self._new_context = new_context - self._instance_id = random_string_insecure_fast(5) + self._instance_id = ( + random_string_insecure_fast(5) + if logcontext_debug_logger.isEnabledFor(logging.DEBUG) + else "" + ) def __enter__(self) -> None: logcontext_debug_logger.debug( @@ -889,7 +893,11 @@ def run_in_background( Note that the returned Deferred does not follow the synapse logcontext rules. """ - instance_id = random_string_insecure_fast(5) + instance_id = ( + random_string_insecure_fast(5) + if logcontext_debug_logger.isEnabledFor(logging.DEBUG) + else "" + ) calling_context = current_context() logcontext_debug_logger.debug( "run_in_background(%s): called with logcontext=%s", instance_id, calling_context @@ -1052,7 +1060,11 @@ def make_deferred_yieldable(deferred: "defer.Deferred[T]") -> "defer.Deferred[T] restores the old context once the awaitable completes (execution passes from the reactor back to the code). """ - instance_id = random_string_insecure_fast(5) + instance_id = ( + random_string_insecure_fast(5) + if logcontext_debug_logger.isEnabledFor(logging.DEBUG) + else "" + ) logcontext_debug_logger.debug( "make_deferred_yieldable(%s): called with logcontext=%s", instance_id, diff --git a/synapse/metrics/_gc.py b/synapse/metrics/_gc.py index 1da871f18f..e0439b84c1 100644 --- a/synapse/metrics/_gc.py +++ b/synapse/metrics/_gc.py @@ -141,7 +141,8 @@ def install_gc_manager() -> None: # We can ignore the lint here since this looping call does not hold a `HomeServer` # reference so can be cleaned up by other means on shutdown. gc_task = task.LoopingCall(_maybe_gc) # type: ignore[prefer-synapse-clock-looping-call] - gc_task.start(0.1) + # tick every second. Previously this was every 100ms. Increased to reduce CPU time spent inside _maybe_gc. + gc_task.start(1.0) #