diff --git a/mathics/core/evaluation.py b/mathics/core/evaluation.py index 8363ed033..ac8c3cf2a 100644 --- a/mathics/core/evaluation.py +++ b/mathics/core/evaluation.py @@ -2,6 +2,7 @@ import os import sys +import threading import time from abc import ABC from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload @@ -58,11 +59,11 @@ SymbolPost = Symbol("System`$Post") # MIN_RECURSION_LIMIT is the smallest value allowed for $RecursionLimit, as in WMA: -# $RecursionLimit = 10 there gives "value must be Infinity or an integer at least 20". +# $RecursionLimit = 10 gives "value must be Infinity or an integer at least 20". MIN_RECURSION_LIMIT = 20 -# MAX_RECURSION_DEPTH gives the maximum value allowed for $RecursionLimit. it's usually set to its +# MAX_RECURSION_DEPTH gives the maximum value allowed for $RecursionLimit. It's usually set to its # default settings.DEFAULT_MAX_RECURSION_DEPTH. MAX_RECURSION_DEPTH = max( @@ -72,7 +73,7 @@ def python_recursion_depth(n) -> int: - # convert Mathics3 recursion depth to Python recursion depth. this estimates how many Python calls + # Convert Mathics3 recursion depth to Python recursion depth. This estimates how many Python calls # we need at worst to process one Mathics3 recursion. A recursive # definition matched through a Condition or PatternTest, as in # Combinatorica's DepthFirstTraversal, takes a little over 30. @@ -80,13 +81,54 @@ def python_recursion_depth(n) -> int: def python_stack_size(n) -> int: # n is a Mathics3 recursion depth - # python_stack_frame_size is the (maximum) number of bytes Python needs for one call on the stack. - python_stack_frame_size = 512 # value estimated experimentally + # python_stack_frame_size is the C stack, in bytes, that one Python call takes on + # average. Since Python 3.11, a call from Python code to Python code takes none, + # so this is far below the size of a C frame. Measured on macOS arm64 with + # Python 3.11 and 3.14: a Combinatorica DepthFirstTraversal, and a recursive + # definition matched through PatternTest with a Module, take 0.7 to 1.4 KB + # per Mathics3 level. 100 gives 4 KB per level, so 400 MB for 100000 levels: + # address space reserved for the thread; only the part used is allocated. + python_stack_frame_size = 100 return python_recursion_depth(n) * python_stack_frame_size +# How deep a Python recursion can go is bounded by the C stack, not only by +# sys.setrecursionlimit: matching a pattern with a Condition, for instance, +# goes through C calls that take C stack on every Mathics3 level. +# +# - Python 3.11 does not check the C stack: running out of it crashes the +# process with a segmentation fault. +# - Python 3.12 and 3.13 count C calls against a fixed limit, whatever the +# size of the stack, and raise RecursionError when it is reached. +# - Python 3.14 checks the C stack against its real size and raises +# RecursionError when it runs out. +# +# The main thread has a small stack, typically 8 MB: a recursive Combinatorica +# DepthFirstTraversal runs out of it before 3000 levels. Where a larger stack +# lets an evaluation go deeper, 3.11 and 3.14 on, Evaluation.evaluate() runs +# on a thread whose stack is sized for the deepest recursion allowed. + +USE_EVALUATION_THREAD = sys.platform != "emscripten" and not ( + (3, 12) <= sys.version_info[:2] < (3, 14) +) + +# MAX_INFINITE_RECURSION_DEPTH is how deep $RecursionLimit = Infinity lets an +# evaluation go. Without a thread on Python 3.11, nothing would stop a crash. + +MAX_INFINITE_RECURSION_DEPTH = ( + max(MAX_RECURSION_DEPTH, settings.DEFAULT_MAX_INFINITE_RECURSION_DEPTH) + if USE_EVALUATION_THREAD or sys.version_info >= (3, 12) + else MAX_RECURSION_DEPTH +) + +# threading.stack_size() takes only whole pages: round up to whole MiB. +_MIB = 2**20 +_stack_size = python_stack_size(max(MAX_RECURSION_DEPTH, MAX_INFINITE_RECURSION_DEPTH)) +EVALUATION_THREAD_STACK_SIZE = (_stack_size + _MIB - 1) // _MIB * _MIB + + def set_python_recursion_limit(n) -> None: - "Sets the required python recursion limit given $RecursionLimit value" + "Sets the required Python recursion limit given $RecursionLimit value" python_depth = python_recursion_depth(n) sys.setrecursionlimit(python_depth) if sys.getrecursionlimit() != python_depth: @@ -115,7 +157,7 @@ def get_data(self) -> Dict[str, Any]: class Evaluation: - """An Evaluation object contains everyting about the evaluation + """An Evaluation object contains everything about the evaluation environment, such as evaluation definitions, exception and formatting information, and a grab bag of other things. @@ -153,6 +195,19 @@ def __init__( self.compound_out_depth = 1 self.quiet_all = False self.recursion_depth = 0 + # The $RecursionLimit that inc_recursion_depth() last checked against, + # for the message when Python itself runs out of stack. + self.recursion_limit = MAX_RECURSION_DEPTH + + # A SIGINT that arrived while the evaluation runs on its own thread: + # check_stopped() calls it, with the frame it was called from, in the + # evaluating thread. + self.interrupt_request: Optional[Callable] = None + # True while the evaluating thread shows the interrupt menu. + self.interrupt_menu_open = False + # The thread _evaluate() runs on: the only one that takes an + # interrupt_request. + self.evaluating_thread: Optional[threading.Thread] = None # iteration is used to keep track of evaluation chains and is # compared against $IterationLimit. @@ -197,7 +252,7 @@ def parse_feeder_returning_code(self, feeder) -> tuple: def parse_feeder_returning_code_and_messages(self, feeder) -> tuple: """ Parse a single expression from feeder, print the messages it produces and - return the result, the source code for this and evaluated + return the result, the source code for this and the evaluated messages created in evaluation. If there was a SyntaxError, the source code returned is "" and the result is None. @@ -220,10 +275,69 @@ def evaluate(self, query, timeout=None, format=None): """ Evaluate a Mathics3 expression and return the result of evaluation. - On return self.exc_result will contain status of various - exception type of result like $Aborted, Overflow, Break, or Continue. - If none of the above applies self.exc_result is Null + On return, self.exc_result will contain status of various + exception types of result like $Aborted, Overflow, Break, or Continue. + If none of the above applies, self.exc_result is SymbolNull. + """ + if USE_EVALUATION_THREAD and not getattr( + threading.current_thread(), "mathics3_evaluation", False + ): + return self._evaluate_on_thread(query, timeout, format) + return self._evaluate(query, timeout, format) + + def _evaluate_on_thread(self, query, timeout, format): + """ + Run _evaluate() on a thread whose stack holds the deepest recursion + allowed, and wait for it. See USE_EVALUATION_THREAD. """ + outcome: Dict[str, Any] = {} + + def run(): + try: + outcome["result"] = self._evaluate(query, timeout, format) + except BaseException as exc: # SystemExit from Quit[] included + outcome["exception"] = exc + + try: + previous_stack_size = threading.stack_size(EVALUATION_THREAD_STACK_SIZE) + try: + worker = threading.Thread( + target=run, name="Mathics3 evaluation", daemon=True + ) + worker.mathics3_evaluation = True # type: ignore[attr-defined] + worker.start() + finally: + threading.stack_size(previous_stack_size) + except (RuntimeError, ValueError, MemoryError): + # No thread with that stack here: evaluate on this one. + return self._evaluate(query, timeout, format) + + # A SIGINT handler that looks through the interrupted frames for a + # local named "evaluation" finds it here, and sees from + # evaluating_thread that it must hand the interrupt over. + evaluation = self # noqa: F841 + evaluating_thread = worker # noqa: F841 + while True: + try: + worker.join() + break + except KeyboardInterrupt: + # Signals reach only the main thread: pass it on. + from timed_threads import async_raise + + if worker.is_alive() and worker.ident is not None: + try: + async_raise(worker.ident, KeyboardInterrupt) + except ValueError: + pass # the thread has just finished + + if "exception" in outcome: + raise outcome["exception"] + return outcome["result"] + + def _evaluate(self, query, timeout=None, format=None): + if self.evaluating_thread is None or not self.evaluating_thread.is_alive(): + self.evaluating_thread = threading.current_thread() from mathics.core.convert.expression import to_expression from mathics.core.expression import Expression from mathics.core.rules import RewriteRule @@ -351,14 +465,9 @@ def evaluate(): except RecursionError: # Python ran out of stack before $RecursionLimit was # reached: report it the same way. - self.message( - "$RecursionLimit", - "reclim", - self.definitions.get_config_value( - "System`$RecursionLimit", MAX_RECURSION_DEPTH - ) - or MAX_RECURSION_DEPTH, - ) + # The limit in effect where it ran out, not the one + # restored since by the Blocks that were left. + self.message("$RecursionLimit", "reclim", self.recursion_limit) self.exc_result = SymbolAborted except ReturnInterrupt as ret: self.exc_result = ret.expr @@ -387,6 +496,9 @@ def evaluate(): finally: self.stop() self.deadline = None + # A Ctrl-C that came too late for this evaluation to take it + # must not open the interrupt menu in the next one. + self.interrupt_request = None # $Line could have changed during the evaluation. line_no = self.definitions.get_line_no() line_no += 1 @@ -434,10 +546,10 @@ def format_output(self, expr, format=None): """ This function takes an expression `expr` and a format `format`. If `format` is None, then returns `expr`. Otherwise, - produce an str with the proper format. + it produces a str with the proper format. Notice that this function can be overwritten by the front-ends, so it should not be - used in Builtin classes where it is expected a front-end independent result. + used in Builtin classes where a front-end-independent result is expected. """ from mathics.format.box import format_element @@ -607,6 +719,13 @@ def check_stopped(self) -> None: self.stopped = True if self.stopped: raise TimeoutInterrupt + interrupt_request = self.interrupt_request + if ( + interrupt_request is not None + and threading.current_thread() is self.evaluating_thread + ): + self.interrupt_request = None + interrupt_request(sys._getframe(1)) def inc_recursion_depth(self) -> None: self.check_stopped() @@ -616,11 +735,12 @@ def inc_recursion_depth(self) -> None: if limit is None: # $RecursionLimit is Infinity, as in Block[{$RecursionLimit = Infinity}, ...], # which does not go through the assignment that sets the Python limit. - # Go as deep as the Python stack is set up to hold. - limit = MAX_RECURSION_DEPTH + # Go as deep as the stack is set up to hold. + limit = MAX_INFINITE_RECURSION_DEPTH if sys.getrecursionlimit() < python_recursion_depth(limit): set_python_recursion_limit(limit) limit = max(limit, MIN_RECURSION_LIMIT) + self.recursion_limit = limit self.recursion_depth += 1 if self.recursion_depth > limit: self.error("$RecursionLimit", "reclim", limit) @@ -709,7 +829,7 @@ class Output(ABC): def max_stored_size(self, output_settings) -> int: """ - Return the largeet number of history items allowed. + Return the largest number of history items allowed. """ return output_settings.MAX_STORED_SIZE @@ -747,7 +867,7 @@ class Result: * MathML * None - defaults to text - In the future "form" will be renamed "format" or something like this. + In the future, "form" will be renamed "format" or something like this. """ def __init__( diff --git a/mathics/eval/datetime.py b/mathics/eval/datetime.py index f6153902c..d882d6447 100644 --- a/mathics/eval/datetime.py +++ b/mathics/eval/datetime.py @@ -54,6 +54,11 @@ def eval_pause(sleeptime: float, evaluation): time.sleep(step_duration) if evaluation.timeout: break + if evaluation.interrupt_request is not None: + # Ctrl-C while the evaluation runs on its own thread: the + # interrupt menu runs here, as a signal would have cut into + # the sleep on the main thread. + evaluation.check_stopped() if sleeptime < time.time() - start: break return diff --git a/mathics/interrupt.py b/mathics/interrupt.py index c47470565..885171b53 100644 --- a/mathics/interrupt.py +++ b/mathics/interrupt.py @@ -7,8 +7,9 @@ import signal import subprocess import sys +import threading +from collections.abc import Callable from types import FrameType -from typing import Callable, Optional from mathics import settings from mathics.core.evaluation import Evaluation @@ -44,7 +45,7 @@ def inspect_eval_loop(evaluation: Evaluation): if not settings.ENABLE_SYSTEM_COMMANDS: evaluation.message("Run", "dis") else: - subprocess.run(source_code[1:], shell=True) + subprocess.run(source_code[1:], check=False, shell=True) if shell.definitions is not None: shell.definitions.increment_line_no(1) continue @@ -55,7 +56,6 @@ def inspect_eval_loop(evaluation: Evaluation): shell.print_result(result, strict_wl_output=True) except TimeoutInterrupt: print("\nTimeout occurred - ignored.") - pass except ReturnInterrupt: evaluation.last_eval = None evaluation.exc_result = None @@ -76,7 +76,9 @@ def inspect_eval_loop(evaluation: Evaluation): def Mathics3_interrupt_handler( - evaluation: Optional[Evaluation], interrupted_frame: FrameType, print_fn: Callable + evaluation: Evaluation | None, + interrupted_frame: FrameType | None, + print_fn: Callable, ): try: import readline # noqa @@ -96,7 +98,7 @@ def Mathics3_interrupt_handler( if not settings.ENABLE_SYSTEM_COMMANDS: print_fn("Execution of external commands is disabled.") else: - breakpoint() + breakpoint() # noqa # type: ignore[name-defined] elif user_input in ("exit", "quit"): print_fn("Mathics3 exited because of an interrupt.") sys.exit(3) @@ -107,7 +109,7 @@ def Mathics3_interrupt_handler( inspect_eval_loop(evaluation) elif user_input in ("show", "s"): - # In some cases we can better, by going back to the caller + # In some cases, we can do better by going back to the caller # and reconstructing the actual call with arguments. eval_frame = find_Mathics3_evaluation_method(interrupted_frame) if eval_frame is None: @@ -130,7 +132,7 @@ def Mathics3_interrupt_handler( """Your options are: abort (or a) to abort current calculation continue (or c) to continue - debugger (or d) to to enter a Python debugger + debugger (or d) to enter a Python debugger exit (or quit) to exit Mathics3 inspect (or i) to enter an interactive dialog show (or s) to show current operation (and then continue) @@ -144,17 +146,17 @@ def Mathics3_interrupt_handler( except TimeoutInterrupt: # There might have been a Pause[] set before we entered # this handler. If that happens, we can clear the - # error. Ideally the interrupt REPL would would have clear + # error. Ideally the interrupt REPL would have cleared # all timeout signals, but Python doesn't support that, as # far as I know. # - # Here, we note we have time'd out. This also silences + # Here, we note we have timed out. This also silences # other handlers that we've handled this. if evaluation is not None: evaluation.timeout = True break except ReturnInterrupt: - # the interrupt shell probably isssued a Return[]. + # the interrupt shell probably issued a Return[]. # Respect that. break except RuntimeError: @@ -163,11 +165,14 @@ def Mathics3_interrupt_handler( pass -def Mathics3_basic_signal_handler(sig, interrupted_frame): +def Mathics3_basic_signal_handler( + sig: int, interrupted_frame: FrameType | None +) -> None: """ Custom signal handler for SIGINT (Ctrl+C). """ - evaluation: Optional[Evaluation] = None + evaluation: Evaluation | None = None + # Find an evaluation object to pass to the Mathics3 interrupt handler while interrupted_frame is not None: if ( @@ -175,7 +180,57 @@ def Mathics3_basic_signal_handler(sig, interrupted_frame): ) is not None and isinstance(evaluation, Evaluation): break interrupted_frame = interrupted_frame.f_back - print_fn = evaluation.print_out if evaluation is not None else print + + print_fn: Callable[..., None] = ( + evaluation.print_out + if evaluation is not None + else (lambda *args, **kwargs: print(*args, **kwargs)) + ) + if ( + interrupted_frame is not None + and (evaluating_thread := interrupted_frame.f_locals.get("evaluating_thread")) + is not None + and evaluating_thread is not threading.current_thread() + ): + if evaluation is None: + return + + # The evaluation runs on a thread of its own (see + # Evaluation._evaluate_on_thread), and only the main thread gets + # signals. Let the evaluating thread run the handler, where it can + # stop the evaluation, at its next check. + if getattr(evaluation, "interrupt_menu_open", False): + # The menu is on the screen already; it reads the answer. + return + + def handle_in_evaluating_thread(frame: FrameType) -> None: + assert evaluation is not None + evaluation.interrupt_menu_open = True + try: + print_fn("") + Mathics3_interrupt_handler(evaluation, frame, print_fn) + finally: + evaluation.interrupt_menu_open = False + + evaluation.interrupt_request = handle_in_evaluating_thread + + def still_waiting() -> None: + assert evaluation is not None + # A step that does not check for interrupts, such as a long + # call into SymPy, delays the menu: say that Ctrl-C was seen. + # Plain print: print_fn formats through Mathics3, which would + # take the pending interrupt on this timer thread. + if evaluation.interrupt_request is handle_in_evaluating_thread: + print( + "\n(interrupt: the menu opens when the current step finishes)", + flush=True, + ) + + timer = threading.Timer(0.5, still_waiting) + timer.daemon = True + timer.start() + return + print_fn("") if interrupted_frame is None: print("Unable to find Evaluation frame to start on") diff --git a/mathics/settings.py b/mathics/settings.py index 6b38c37b8..8ea3f7f78 100644 --- a/mathics/settings.py +++ b/mathics/settings.py @@ -26,6 +26,12 @@ def get_srcdir(): # without setting a custom thread stack size. DEFAULT_MAX_RECURSION_DEPTH = 512 +# How deep $RecursionLimit = Infinity, as in Block[{$RecursionLimit = Infinity}, ...], +# lets an evaluation go. It is not bounded by the 512 above because an +# evaluation runs on a thread with a stack sized for it (see +# mathics.core.evaluation), or on a Python that checks its own C recursion. +DEFAULT_MAX_INFINITE_RECURSION_DEPTH = 100000 + # Maximum number of digits allows in a string representation of a string number. # We picked this to be able to handle 1989 ^ 1989. DEFAULT_MAX_STR_DIGITS = 7000 diff --git a/test/builtin/test_evaluation.py b/test/builtin/test_evaluation.py index 276054d52..20207f618 100644 --- a/test/builtin/test_evaluation.py +++ b/test/builtin/test_evaluation.py @@ -8,6 +8,8 @@ import pytest +from mathics.core import evaluation as core_evaluation + @pytest.mark.parametrize( ("str_expr", "msgs", "str_expected", "fail_msg"), @@ -34,10 +36,10 @@ "a Block value is evaluated before the variable is reset", ), ( - "ClearAll[f]; f[n_] := 1 + f[n + 1]; Block[{$RecursionLimit = Infinity}, f[0]]", - ("Recursion depth of 512 exceeded.",), - "$Aborted", - "Infinity goes as deep as the Python stack is set up for, then stops", + "ClearAll[f]; f[0] = 0; f[n_] := 1 + f[n - 1]; Block[{$RecursionLimit = Infinity}, f[2000]]", + None, + "2000", + "Infinity is not bounded by the largest integer $RecursionLimit", ), ("ClearAll[f];", None, None, None), ( @@ -112,7 +114,9 @@ "{h, 3}", "Release in the left-hand side of a definition", ), - ("ClearAll[f, h, x];", None, None, None), + # a = a + a above is left defined otherwise, and the next test file + # in the same worker that uses a hits the recursion limit + ("ClearAll[a, f, h, x];", None, None, None), ], ) def test_evaluation(str_expr, msgs, str_expected, fail_msg): @@ -179,3 +183,77 @@ def test_evaluate_timeout(str_expr): assert [m.text for m in result.out] == ["Timeout reached."] # The next evaluation has no limit left over. assert session.evaluate_as_in_cli("Length[Table[i, {i, 10}]]").result == "10" + + +def test_infinite_recursion_limit(monkeypatch): + """$RecursionLimit = Infinity goes as deep as MAX_INFINITE_RECURSION_DEPTH, + then stops, and the message gives the limit in effect inside the Block.""" + monkeypatch.setattr(core_evaluation, "MAX_INFINITE_RECURSION_DEPTH", 1000) + check_evaluation_as_in_cli( + "ClearAll[f]; f[n_] := 1 + f[n + 1]; Block[{$RecursionLimit = Infinity}, f[0]]", + "$Aborted", + "Infinity goes as deep as the stack is set up for, then stops", + ("Recursion depth of 1000 exceeded.",), + ) + check_evaluation_as_in_cli("ClearAll[f];") + + +def test_recursion_error_reports_limit_in_effect(monkeypatch): + """A RecursionError from Python is reported with the $RecursionLimit in + effect where it happened, not the one restored after leaving the Block.""" + from mathics.core.evaluation import Evaluation + + original = Evaluation.inc_recursion_depth + + def inc_recursion_depth(self): + original(self) + if self.recursion_depth > 600: + raise RecursionError + + monkeypatch.setattr(Evaluation, "inc_recursion_depth", inc_recursion_depth) + check_evaluation_as_in_cli( + "ClearAll[f]; f[n_] := 1 + f[n + 1]; Block[{$RecursionLimit = Infinity}, f[0]]", + "$Aborted", + None, + ( + "Recursion depth of %d exceeded." + % core_evaluation.MAX_INFINITE_RECURSION_DEPTH, + ), + ) + check_evaluation_as_in_cli("ClearAll[f];") + + +@pytest.mark.skipif( + not core_evaluation.USE_EVALUATION_THREAD, + reason="evaluations run on the calling thread on this platform", +) +def test_evaluation_runs_on_a_thread_with_a_large_stack(monkeypatch): + """Evaluation.evaluate() runs the evaluation on a thread whose stack is + sized for the deepest recursion allowed, and hands back its result and + its exceptions.""" + import threading + + from mathics.session import MathicsSession + + seen = {} + original = core_evaluation.Evaluation._evaluate + + def _evaluate(self, query, timeout=None, format=None): + seen["thread"] = threading.current_thread() + return original(self, query, timeout, format) + + monkeypatch.setattr(core_evaluation.Evaluation, "_evaluate", _evaluate) + session = MathicsSession() + assert session.evaluate_as_in_cli("1 + 1").result == "2" + assert seen["thread"] is not threading.main_thread() + assert getattr(seen["thread"], "mathics3_evaluation", False) + # The stack size is set only while the thread is started. + assert threading.stack_size() == 0 + + def failing(self, query, timeout=None, format=None): + raise SystemExit(7) + + monkeypatch.setattr(core_evaluation.Evaluation, "_evaluate", failing) + with pytest.raises(SystemExit) as exc_info: + session.evaluate_as_in_cli("1 + 1") + assert exc_info.value.code == 7 diff --git a/test/test_interrupt.py b/test/test_interrupt.py new file mode 100644 index 000000000..e3b3f2b81 --- /dev/null +++ b/test/test_interrupt.py @@ -0,0 +1,223 @@ +""" +Ctrl-C while an evaluation runs on its own thread (see +Evaluation._evaluate_on_thread). + +The unit tests hand an interrupt request to an evaluation directly. The +terminal tests run the mathics CLI in a pseudo-terminal and press Ctrl-C +there, so that the terminal driver sends SIGINT exactly as for a person at +the keyboard, then answer the interrupt> menu. +""" + +import os +import re +import sys +import threading +import time + +import pytest + +from mathics.core import evaluation as core_evaluation +from mathics.session import MathicsSession + +# ---- unit tests --------------------------------------------------------------- + + +def test_pause_takes_a_pending_interrupt(): + """Pause[] runs the interrupt menu when Ctrl-C comes in its sleep, as a + signal cut into the sleep when the evaluation ran on the main thread.""" + session = MathicsSession() + evaluation = session.evaluation + taken = [] + + def request(frame): + taken.append(time.time()) + from mathics.core.interrupt import AbortInterrupt + + raise AbortInterrupt + + def press_ctrl_c(): + time.sleep(0.5) + evaluation.interrupt_request = request + + threading.Thread(target=press_ctrl_c, daemon=True).start() + start = time.time() + result = session.evaluate_as_in_cli("Pause[10]; 7") + assert result.result == "$Aborted" + assert taken and taken[0] - start < 3, "the menu waited for the pause to end" + + +def test_interrupt_left_after_an_evaluation_is_dropped(monkeypatch): + """A Ctrl-C that came too late for one evaluation (after its last check) + does not open the menu in the next one.""" + session = MathicsSession() + evaluation = session.evaluation + taken = [] + original_stop = core_evaluation.Evaluation.stop + + def stop_with_a_late_ctrl_c(self): + original_stop(self) + self.interrupt_request = lambda frame: taken.append(frame) + + monkeypatch.setattr(core_evaluation.Evaluation, "stop", stop_with_a_late_ctrl_c) + session.evaluate_as_in_cli("1 + 1") + monkeypatch.setattr(core_evaluation.Evaluation, "stop", original_stop) + assert evaluation.interrupt_request is None + assert session.evaluate_as_in_cli("Pause[0.2]; 2 + 2").result == "4" + assert taken == [] + + +def test_other_threads_do_not_take_the_interrupt(): + """Only the evaluating thread runs the menu: formatting output on + another thread (as the interrupt notice once did) must not.""" + session = MathicsSession() + evaluation = session.evaluation + session.evaluate_as_in_cli("1") + taken = [] + evaluation.interrupt_request = lambda frame: taken.append(frame) + other = threading.Thread(target=evaluation.check_stopped) + other.start() + other.join() + assert taken == [] and evaluation.interrupt_request is not None + evaluation.interrupt_request = None + + +# ---- terminal tests ----------------------------------------------------------- + +pty = pytest.importorskip("pty") +needs_terminal = pytest.mark.skipif( + sys.platform.startswith("win") + or not hasattr(os, "login_tty") + or not core_evaluation.USE_EVALUATION_THREAD, + reason="needs a pseudo-terminal and the evaluation thread", +) + + +# Runs the CLI with the pseudo-terminal as its controlling terminal, so that +# Ctrl-C there sends it SIGINT. pty.fork() would fork this (multi-threaded) +# process; subprocess starts a fresh one, and login_tty() does the rest. +LOGIN_TTY = ( + "import os, sys; os.login_tty(os.open(sys.argv[1], os.O_RDWR)); " + "os.execv(sys.executable, [sys.executable, '-m', 'mathics', '--no-completion', '--colors', 'NoColor'])" +) + + +class Terminal: + """The mathics CLI in a pseudo-terminal.""" + + def __init__(self): + import subprocess + + self.fd, self.child = pty.openpty() + self.proc = subprocess.Popen( + [sys.executable, "-c", LOGIN_TTY, os.ttyname(self.child)], + env=dict(os.environ, TERM="dumb", COLUMNS="200"), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + # Kept open until close(): on Linux, reading the master side fails + # with EIO while no process has the other side open, which is the + # case until the CLI has opened it. + self.buf = b"" + + def wait_for(self, pattern, timeout, start=0): + import select + + rx = re.compile(pattern.encode()) + end = time.time() + timeout + while True: + m = rx.search(self.buf, start) + if m or time.time() >= end: + return m + ready, _, _ = select.select([self.fd], [], [], min(0.2, end - time.time())) + if ready: + try: + data = os.read(self.fd, 65536) + except OSError: + return rx.search(self.buf, start) + self.buf += data + + def pause(self, seconds): + self.wait_for("(?!x)x", seconds) # keep reading while waiting + + def type(self, line): + # readline flushes what is typed before it has set the terminal up, + # and a person does not type within milliseconds of the prompt. + self.pause(0.8) + mark = len(self.buf) + os.write(self.fd, line.encode() + b"\r") + assert self.wait_for(re.escape(line[:10]), 5, mark), f"{line!r} was not echoed" + + def key(self, ch): + self.pause(0.5) + os.write(self.fd, ch.encode()) + + def screen(self, start=0): + return self.buf[start:].decode(errors="replace").replace("\r", "") + + def close(self): + self.proc.kill() + # On macOS a killed process cannot finish exiting while output it + # wrote to the terminal is unread, so close the terminal first. + os.close(self.fd) + os.close(self.child) + self.proc.wait(timeout=30) + + +@pytest.fixture +def terminal(): + t = Terminal() + assert t.wait_for(r"In\[1\]:= ", 60), "no prompt: " + t.screen()[-300:] + yield t + t.close() + + +def interrupt(t, workload, run_for=2.0): + t.type(workload) + t.pause(run_for) + mark = len(t.buf) + pressed = time.time() + t.key("\x03") + assert t.wait_for("interrupt> ", 20, mark), "no menu: " + t.screen(mark) + return mark, time.time() - pressed + + +@needs_terminal +def test_abort_a_loop(terminal): + mark, waited = interrupt(terminal, "Do[i, {i, 10^8}]") + assert waited < 2 + terminal.type("a") + assert terminal.wait_for(r"Out\[1\]= \$Aborted", 15, mark), terminal.screen(mark) + terminal.type("6*7") + assert terminal.wait_for(r"Out\[2\]= 42", 15, mark), terminal.screen(mark) + + +@pytest.mark.parametrize("answer", ["c", "s"]) +@needs_terminal +def test_continue_or_show_during_pause(terminal, answer): + mark, waited = interrupt(terminal, "Pause[8]; 7") + # well under the 6 s left of the pause: the menu did not wait for it + assert waited < 5, "the menu waited for the pause to end" + terminal.type(answer) + assert terminal.wait_for(r"Out\[1\]= 7", 20, mark), terminal.screen(mark) + + +@needs_terminal +def test_second_ctrl_c_opens_no_second_menu(terminal): + mark, _ = interrupt(terminal, "Do[i, {i, 10^8}]") + terminal.key("\x03") + terminal.type("a") + assert terminal.wait_for(r"Out\[1\]= \$Aborted", 15, mark), terminal.screen(mark) + terminal.pause(1.5) + assert terminal.screen(mark).count("interrupt> ") == 1, terminal.screen(mark) + + +@needs_terminal +def test_abort_a_long_step(terminal): + """A step that does not check for interrupts (a long Expand in SymPy) + delays the menu; a notice says Ctrl-C was seen.""" + mark, waited = interrupt(terminal, "Length[Expand[(x+y+z+w)^40]]", run_for=1.0) + if waited > 0.6: + assert "(interrupt:" in terminal.screen(mark) + terminal.type("a") + assert terminal.wait_for(r"Out\[1\]= \$Aborted", 30, mark), terminal.screen(mark)