profiling: improve 3.12 error message for calling lsprof twice stable
authorPierre-Yves David <pierre-yves.david@octobus.net>
Wed, 11 Sep 2024 12:02:38 +0200
branchstable
changeset 51684 1bb71046f5e0
parent 51683 17e2d5c46716
child 51685 102770bbf270
profiling: improve 3.12 error message for calling lsprof twice Python 3.12 prevent lsprof to be enabled if it is already enabled. This break the use of lsprof in `hg serve` as both the initial `serve` command and the request serving want to profile. The "stat" profiler (the default) does not have this problem, so we focus on improving the error message for now.
mercurial/profiling.py
--- a/mercurial/profiling.py	Wed Sep 11 00:41:37 2024 +0200
+++ b/mercurial/profiling.py	Wed Sep 11 12:02:38 2024 +0200
@@ -7,6 +7,7 @@
 
 
 import contextlib
+import sys
 
 from .i18n import _
 from .pycompat import (
@@ -54,7 +55,23 @@
             )
         )
     p = lsprof.Profiler()
-    p.enable(subcalls=True)
+    try:
+        p.enable(subcalls=True)
+    except ValueError as exc:
+        if str(exc) != "Another profiling tool is already active":
+            raise
+        if not hasattr(sys, "monitoring"):
+            raise
+        # python >=3.12 prevent more than one profiler to run at the same
+        # time, tries to improve the report to help the user understand
+        # what is going on.
+        other_tool_name = sys.monitoring.get_tool(sys.monitoring.PROFILER_ID)
+        if other_tool_name == "cProfile":
+            msg = 'cannot recursively call `lsprof`'
+            raise error.Abort(msg) from None
+        else:
+            m = 'failed to start "lsprofile"; another profiler already running: %s'
+            raise error.Abort(_(m) % other_tool_name) from None
     try:
         yield
     finally: