Files
youknowdotandJeong YunWon 3f55cf4af0 Implement basic REPL execution and fix piped stdin handling (#9163)
* Preserve original main VM through C API execution

Run and finalize the original main VM while keeping the registered attachment template available without holding its mutex across Python callbacks.

Assisted-by: OpenAI Codex:model version unavailable

* Make unraisable reporting robust at hook boundaries

Keep the existing message API and traceback formatting while handling missing, disabled, audited and failing hooks without panicking.

Assisted-by: OpenAI Codex:model version unavailable

* Separate interactive warning collection from compilation

Retain ordinary warning behavior and typed module APIs while exposing record-local parser warnings and post-warning code generation. Add a source-only lazy future-import guard.

Assisted-by: OpenAI Codex:model version unavailable

* Evaluate native stdin with shared VM record semantics

Use one evaluator for basic REPL and root transports, preserve effective inspect snapshots and future flags, and carry owned host exit status through original-main finalization.

Assisted-by: OpenAI Codex:model version unavailable

* Refresh canonical REPL tests and retire fixed failures

Run update_lib migrate from pinned CPython 3.15.0, preserving three remaining platform/runtime markers and retiring the two traceback/startup failures verified on the native evaluator.

Assisted-by: OpenAI Codex:model version unavailable

* Keep the root compiler dependency for development targets

The native evaluator now compiles through the VM. Only root benchmarks and the parse_folder example use rustpython-compiler directly, so declare it as a dev dependency while preserving VM compiler features.

Assisted-by: OpenAI Codex:model version unavailable

* Validate explicit conditional failure marker retirement

Require exact selector and original decorator evidence for each conditional expected-failure marker retired by migrate. Preserve undeclared guards and reject missing, duplicate, modified or unconsumed declarations.

Assisted-by: OpenAI Codex:model version unavailable

* Refresh canonical stdin and exception audit tests

Migrate the pinned CPython 3.15.0 modules and their canonical helper fixtures through update_lib. Retire exactly four failure markers proven obsolete by hosted CI, preserving all other existing guards.

Assisted-by: OpenAI Codex:model version unavailable

* Synchronize runpy warning attribution and document remaining capabilities

Migrate whole canonical runpy.py to pass module names to compile. Use update_lib to annotate only reproduced missing-capability cases: absent _testcapi import-event tests, unsupported startup/import-time features, and the deferred frozen-loader module-attribution caller.

Assisted-by: OpenAI Codex:model version unavailable

* Propagate interrupted native stdin reads to signal dispatch

Preserve the shared input buffer and partial bytes while returning EINTR to the VM before retrying. Exercise the transport deterministically and verify a returning SIGINT handler while pipe stdin stays open.

Assisted-by: OpenAI Codex:model version unavailable

* Reject statements after a compound statement in single mode

single_mode_multiple_statements_error now reports "invalid syntax" at the
statement that follows a compound first statement, and interactive_input
runs it right after parsing as compile() does.

The lazy `from __future__` import check moved from lazy_future_import_error
into unsupported_grammar_error, so it applies to every compile mode.

Assisted-by: Claude Code:claude-opus-5-5

* Remove passing expected failure from test_runpy

test_run_module_filter_syntax_warnings_by_module passes.

Assisted-by: Claude Code:claude-opus-5-5

* Restructure stdin execution after Modules/main.c and pythonrun.c

- src/lib.rs follows pymain_run_python: pymain_run_stdin, pymain_repl,
  pymain_run_startup, pymain_run_interactive_hook and pymain_run_pyrepl
  return exit codes instead of raising SystemExit.
- VirtualMachine gains run_any_stdin (_PyRun_AnyFile),
  run_interactive_loop (_PyRun_InteractiveLoop) and run_simple_stdin;
  run_shell feeds rustyline lines into run_interactive_loop, and
  sys._baserepl calls run_any_stdin.
- print_uncaught_exception (PyErr_Print) replaces
  report_uncaught_exception, and handle_system_exit_and_keyboard_interrupt
  replaces handle_reported_exception.
- An unhandled KeyboardInterrupt is recorded and the process exits
  through SIGINT after finalization.
- Interpreter::run_main replaces run_with_exit_status and InterpreterExit;
  rustpython_capi::run_main_interpreter takes an exit-code callback.
- config_set_inspect audits cpython.PyConfig_Set and rebuilds sys.flags
  through set_flag_obj (_PySys_SetFlagObj); the inspect state is an
  AtomicBool and dict replace_by_identity is removed.
- add_main_module (PyImport_AddModuleRef("__main__")) is used by the
  interactive and simple-file paths.
- The interactive parser warning helpers take their state directly.

Assisted-by: Claude Code:claude-opus-5-5

* Exit through Py_Exit from PyErr_Print and run the basic REPL via stdin

- print_uncaught_exception (PyErr_Print) calls exit_process (Py_Exit) for a
  SystemExit when inspect mode is off, instead of returning the exception.
  run_interactive_loop no longer checks SystemExit itself and flushes after
  printing an error; sys._baserepl returns None.
- exit_process finalizes through VirtualMachine::finalize_ex, which holds
  the Py_FinalizeEx steps split out of Interpreter::finalize, and exits
  through host_env::os::exit_with_cleanup (C exit()).
- The basic REPL on a terminal (PYTHON_BASIC_REPL, or _pyrepl missing)
  runs run_any_stdin instead of the rustyline shell.
- run_shell saves the history after every line.

Assisted-by: Claude Code:claude-opus-5-5

* Display exceptions through PyErr_Display and track the main thread running __main__

- display_exception (PyErr_Display) and display_exception_to (_PyErr_Display)
  try traceback._print_exception_bltin before the native printer and flush
  the file. PyErr_Print's excepthook fallback, print_exception and
  sys.excepthook use them. A missing sys.stderr is reported with
  dump_object (PyObject_Dump); a None sys.stderr prints nothing.
- Paths gains program_name (argv[0]) from getpath. The "can't open file"
  message uses it with strerror(errno) and goes to sys.stderr.
- running_main holds the ident of the thread running __main__.
  pymain_run_python sets it around running the main code, Py_Exit clears it,
  the fork child reinitializes it, and _interpreters.is_running reads it
  instead of treating the main interpreter as always running.
- Interpreter::run_main clears the unhandled KeyboardInterrupt flag before
  running and applies exit_sigint after finalizing; finalize no longer
  does.
- run_interactive_loop returns a SystemExit raised outside inspect mode
  again and no longer flushes after printing an error; run_shell saves the
  history once after the loop.
- pymain_set_inspect reports its error through print_uncaught_exception.

Assisted-by: Claude Code:claude-opus-5-5

* Treat a parse error at the end of the source as incomplete input

A parser error that starts at the end of the source is reported as
_IncompleteInputError when incomplete input is allowed, so the
interactive loop and codeop keep reading after `try:` and its block or
after a decorator line.

Assisted-by: Claude Code:claude-opus-5-5

* Place syntax errors on tokens made up at the end of the input

A parse error on the NEWLINE, DEDENT or ENDMARKER the tokenizer makes up
at the end of the input now carries an EofToken: the number of lines
read and the last line. SyntaxError takes its lineno and text from it,
and its offset is that line's length with end_offset -1, or 0 for both
when the error is raised at the token itself (the generic syntax error
and a missing forced `:` or `(`). Exec input that does not end with a
newline is checked with one appended.

Assisted-by: Claude Code:claude-opus-5-5

* Slice the source with get when checking an indented block error at EOF

Assisted-by: Claude Code:claude-opus-5-5

* Rename the host exits after C exit() and fix wasi and Windows builds

- host_env::os::exit now calls the C exit() on every platform; on Windows
  std::process::exit ends in ExitProcess, so it flushes the Rust stdout
  and calls libc::exit there. The former exit, which calls _exit(), is
  now exit_immediately, used by os._exit, faulthandler and
  posixsubprocess.
- errno::strerror_string is available on wasi.
- PyGlobalState::reinit_running_main is built only where its fork caller
  is.

Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: Jeong YunWon <jeong@youknowone.org>
2026-10-18 09:22:12 +00:00

349 lines
13 KiB
Python

import signal
import sys
import time
from testutils import assert_raises
assert_raises(TypeError, lambda: signal.signal(signal.SIGINT, 2))
signals = []
def handler(signum, frame):
signals.append(signum)
signal.signal(signal.SIGILL, signal.SIG_IGN)
assert signal.getsignal(signal.SIGILL) is signal.SIG_IGN
old_signal = signal.signal(signal.SIGILL, signal.SIG_DFL)
assert old_signal is signal.SIG_IGN
assert signal.getsignal(signal.SIGILL) is signal.SIG_DFL
# Ignoring a synchronously raised signal must not invoke a callback, including
# on WASI where libc uses a function pointer rather than integer 1 for SIG_IGN.
synchronous_signals = []
def synchronous_handler(signum, frame):
synchronous_signals.append(signum)
previous = signal.signal(signal.SIGILL, synchronous_handler)
try:
signal.raise_signal(signal.SIGILL)
assert synchronous_signals == [signal.SIGILL]
assert signal.signal(signal.SIGILL, signal.SIG_IGN) is synchronous_handler
signal.raise_signal(signal.SIGILL)
assert synchronous_signals == [signal.SIGILL]
assert signal.getsignal(signal.SIGILL) is signal.SIG_IGN
finally:
signal.signal(signal.SIGILL, previous)
if sys.platform == "wasi":
# wasi-libc rejects SIGKILL (9) and SIGSTOP (19), even though they are not
# exported by RustPython's minimal WASI signal module.
for uncatchable in (9, 19):
previous = signal.getsignal(uncatchable)
assert_raises(OSError, signal.signal, uncatchable, signal.SIG_IGN)
assert signal.getsignal(uncatchable) is previous
# unix, and not WASI
if "win" not in sys.platform and sys.platform != "wasi":
signal.signal(signal.SIGALRM, handler)
assert signal.getsignal(signal.SIGALRM) is handler
signal.alarm(1)
time.sleep(2.0)
assert signals == [signal.SIGALRM]
signal.signal(signal.SIGALRM, signal.SIG_IGN)
signal.alarm(1)
time.sleep(2.0)
assert signals == [signal.SIGALRM]
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)
time.sleep(2.0)
assert signals == [signal.SIGALRM, signal.SIGALRM]
# A handler may call signal.signal(), and the usual reason is to disarm
# itself. Reading the handler table while the handler runs used to be a
# crash rather than a rearm.
rearmed = []
def rearm(signum, frame):
rearmed.append(signum)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
signal.signal(signal.SIGALRM, rearm)
signal.raise_signal(signal.SIGALRM)
assert rearmed == [signal.SIGALRM], rearmed
assert signal.getsignal(signal.SIGALRM) is signal.SIG_IGN
# The same goes for arming a different signal from inside a handler.
armed = []
def target(signum, frame):
armed.append("target")
def arm_other(signum, frame):
armed.append("arm_other")
signal.signal(signal.SIGUSR2, target)
signal.signal(signal.SIGUSR1, arm_other)
signal.raise_signal(signal.SIGUSR1)
assert armed == ["arm_other"], armed
assert signal.getsignal(signal.SIGUSR2) is target
signal.raise_signal(signal.SIGUSR2)
assert armed == ["arm_other", "target"], armed
signal.signal(signal.SIGALRM, signal.SIG_DFL)
signal.signal(signal.SIGUSR1, signal.SIG_DFL)
signal.signal(signal.SIGUSR2, signal.SIG_DFL)
def check_windows_wakeup_reporting():
if sys.platform != "win32":
return
import errno
import socket
def fill_socket(write):
# A nonblocking Windows send can briefly fail before TCP has filled
# the receiving socket. Require repeated one-byte failures to settle.
deadline = time.monotonic() + 5.0
written = 0
blocked = 0
for _ in range(4096):
assert time.monotonic() < deadline, "socket fill timed out"
assert written < 16 * 1024 * 1024, "socket fill exceeded byte bound"
try:
written += write.send(b"x" * 65536)
except BlockingIOError:
try:
written += write.send(b"x")
except BlockingIOError:
blocked += 1
if blocked == 4:
return
time.sleep(0.050)
continue
blocked = 0
raise AssertionError("socket did not fill within the attempt bound")
# Use numeric loopback addresses and bounded connection/receive calls.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
listener.settimeout(5.0)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as write:
write.settimeout(5.0)
write.connect(listener.getsockname())
read, _ = listener.accept()
with read:
read.settimeout(5.0)
read.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
write.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
write.setblocking(False)
old_handler = signal.getsignal(signal.SIGINT)
old_hook = sys.unraisablehook
old_fd = signal.set_wakeup_fd(-1)
errors = []
delivered = []
def raise_wakeup_signal():
delivered.clear()
# Reinstall for each raise: Windows CRT handlers can reset.
signal.signal(
signal.SIGINT, lambda signum, frame: delivered.append(signum)
)
signal.raise_signal(signal.SIGINT)
assert delivered == [signal.SIGINT]
try:
sys.unraisablehook = errors.append
signal.set_wakeup_fd(write.fileno())
raise_wakeup_signal()
assert read.recv(1) == bytes([signal.SIGINT])
assert not errors
for options in (
{},
{"warn_on_full_buffer": True},
{"warn_on_full_buffer": False},
{},
):
fill_socket(write)
signal.set_wakeup_fd(write.fileno(), **options)
raise_wakeup_signal()
if options.get("warn_on_full_buffer", True):
assert len(errors) == 1, errors
error = errors.pop()
assert error.exc_type is BlockingIOError
assert error.exc_value.winerror == errno.WSAEWOULDBLOCK
assert error.exc_value.errno in (
errno.EAGAIN,
errno.EWOULDBLOCK,
)
assert error.object is None
assert error.exc_traceback is error.exc_value.__traceback__
assert error.err_msg == (
"Exception ignored while trying to send "
"to the signal wakeup fd"
)
else:
assert not errors
# False suppresses a full buffer, not other send failures.
signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False)
write.close()
raise_wakeup_signal()
assert len(errors) == 1, errors
assert errors[0].exc_type is OSError
assert errors[0].exc_value.winerror == errno.WSAENOTSOCK
assert errors[0].err_msg == (
"Exception ignored while trying to send to the signal wakeup fd"
)
finally:
signal.set_wakeup_fd(old_fd)
signal.signal(signal.SIGINT, old_handler)
sys.unraisablehook = old_hook
check_windows_wakeup_reporting()
def check_native_stdin_eintr():
if sys.platform in ("win32", "wasi", "emscripten"):
return
if not sys.executable or not hasattr(sys, "_baserepl"):
return
import os
import select
import subprocess
if os.name != "posix":
return
prompt = b"__NATIVE_STDIN_PROMPT__"
handled = b"__NATIVE_STDIN_HANDLED__"
executed = b"__NATIVE_STDIN_EXECUTED__"
# This explicitly exercises the native adapter rather than an editor REPL.
# Lib/test/test_repl.py covers ordinary input, not a blocked native read
# interrupted while its pipe remains open and no complete line is supplied.
setup = (
"import signal, sys\n"
f"sys.ps1 = {prompt.decode()!r}\n"
"sys.ps2 = '__NATIVE_STDIN_CONTINUATION__'\n"
)
setup += (
"def handler(signum, frame):\n"
" print('__NATIVE_' + 'STDIN_HANDLED__', flush=True)\n"
"signal.signal(signal.SIGINT, handler)\n"
)
setup += "sys._baserepl()\n"
process = subprocess.Popen(
[sys.executable, "-i", "-S", "-u", "-c", setup],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
)
output = bytearray()
output_eof = False
deadline = time.monotonic() + 10.0
def remaining():
timeout = deadline - time.monotonic()
assert timeout > 0, ("native stdin child timed out", output)
return timeout
def read_output(timeout):
nonlocal output_eof
ready, _, _ = select.select([process.stdout], [], [], min(timeout, remaining()))
if ready:
try:
chunk = os.read(process.stdout.fileno(), 4096)
except BlockingIOError:
return
if chunk:
output.extend(chunk)
assert len(output) <= 65536, ("child output limit", output)
else:
output_eof = True
def expect(marker, start=0, interrupt=False):
observed = len(output)
retry_at = time.monotonic()
attempts = 0
while marker not in output[start:]:
assert not output_eof, ("child exited before marker", marker, output)
timeout = remaining()
if interrupt and len(output) == observed and attempts < 10:
# Drain bytes already available before deciding to retry.
read_output(0)
if len(output) != observed or output_eof:
continue
now = time.monotonic()
if now >= retry_at:
# Prompt emission precedes read(). Retry only this child
# to cover that race; never send input to wake the read.
assert process.poll() is None, ("child exited", output)
process.send_signal(signal.SIGINT)
attempts += 1
retry_at = now + 0.5
timeout = min(timeout, max(0, retry_at - time.monotonic()))
# Any response stops retries, including a partial traceback or
# marker, so another SIGINT does not interrupt its reporting.
read_output(timeout)
def write_input(data):
offset = 0
while offset < len(data):
_, ready, _ = select.select([], [process.stdin], [], remaining())
if ready:
try:
written = os.write(process.stdin.fileno(), data[offset:])
except BlockingIOError:
continue
assert written > 0
offset += written
try:
os.set_blocking(process.stdin.fileno(), False)
os.set_blocking(process.stdout.fileno(), False)
expect(prompt)
after_prompt = len(output)
source = b"print('__NATIVE_' + 'STDIN_EXECUTED__', flush=True)"
# Keep the pipe empty until the native reader dispatches the signal.
# Only then provide a complete line and EOF; this does not assert
# CPython's behavior for a partial libc fgets interrupted by a signal.
expect(handled, after_prompt, interrupt=True)
write_input(source + b"\n")
process.stdin.close()
expect(executed, after_prompt)
while not output_eof:
read_output(remaining())
returncode = process.wait(timeout=remaining())
assert returncode == 0, (returncode, output)
assert output.count(executed) == 1, output
assert b"KeyboardInterrupt" not in output, output
finally:
process.stdin.close()
process.stdout.close()
if process.poll() is None:
process.kill()
process.wait(timeout=5.0)
check_native_stdin_eintr()