diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 63f8ec29be..b89694fbe5 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -84,7 +84,9 @@ act, then check the result with the reading tools, keeping screenshots for what They say to prefer typed tools over clicks and never retry a call that returned a job, point to `get_settings`' meta and search for what a setting does, say how a gizmo opens and is driven (and that `gizmo_file` only stands in for a file picker inside one, since its name draws agents to it for any -gizmo work), that the camera turns with `set_view` rather than a drag, and which indices are 0-based. Clients that defer tools load only their names and the +gizmo work), that the camera turns with `set_view` rather than a drag, and which indices are 0-based. +They also point to `api_describe` for the operations plugins offer, which `tools/list` never shows, so +nothing else tells an agent they exist. Clients that defer tools load only their names and the instructions at first, so the instructions are how an agent without a skill learns which tool to load. @@ -2277,8 +2279,8 @@ GUI changes it. wx ignores `OnExit()`'s return value, so `GUI_Run()` returns File › Run Script… and the Speed Dial command `open_script_runner` open `ScriptRunnerDialog`, where a person opens or writes a script, reads its steps and runs it whole or one step at a time. A `.py` file is a -Python script, shown and run as one step through `McpService::start_python_run()`: its printed output, its -result or its traceback show in that step. With the Python setting off it does not parse, so Run stays +Python script, shown and run as one step through `McpService::start_python_run()`, with no time limit, since +Stop ends it: its printed output, its result or its traceback show in that step. With the Python setting off it does not parse, so Run stays off and the page says why. The editor holds UTF-8 text: a `.py` file is decoded as Python reads it and saved back in the encoding it was read in, BOM included; text that encoding can't hold is not saved. It is a `WebViewHostDialog` page (`resources/web/dialog/ScriptRunner/`), modeless and one at a time @@ -2359,61 +2361,186 @@ be satisfied. Only the call's own job counts as its job: a ## Python scripts -A Python script is a `.py` file or a code string that runs on the plugin interpreter against `orca.host`, -the plugin API, without being packaged as a plugin. A person runs one from the Run Script dialog or with -`--mcp-script file.py`; an agent sends one with `run_python {code, args, timeout_s}`; a plugin's code may -call `run_python` too. The code computes next to the data (meshes as numpy, settings, presets) and changes -the project only through the tools. +A Python script is a `.py` file or a code string that runs on the plugin interpreter as an embedded macro: the +main program of a run inside OrcaSlicer, with the whole plugin API (`orca.host`), without being packaged as a +plugin. A person runs one from the Run Script dialog or with `--mcp-script file.py`; an agent sends one with +`run_python {code, args, timeout_s, filename}`; a plugin's code may call `run_python` too. A script that runs +under `python file.py` runs the same way here, and code written for a plugin's `execute()` (windows, progress, +presets, storage) runs from a script unchanged. A script is not a plugin: it gets no permission prompt and no +grants, is never in the Plugins list, and ends when its work ends, leaving nothing loaded. -**Entry contract.** `run_python_code()` (`plugin/PythonScriptRunner.cpp`) runs the code as a module body -on the calling thread, the MCP job that runs `run_python`, in a fresh namespace with `args` bound and -`orca` importable. The code is text, compiled as Python compiles any code string, so a coding line in it -changes nothing; a file's bytes are decoded first as Python reads a source file, by its BOM or its PEP 263 -declaration, else as UTF-8 (`decode_python_source()`), and `filename` (a `.py` file's path) names it in -tracebacks. It holds an interpreter lease and the GIL for the run. The value left in `result` is -read once when the body returns; one that is not JSON (a dict with string keys, a list, a string, a -finite number, a boolean or None, nested) makes the run `raised`, and `SystemExit` with code 0 or None -finishes it. What the run's own thread prints to stdout and stderr is captured, up to 256 KiB, by a -stream installed once over `sys.stdout` and `sys.stderr` that routes writes by thread; other threads -print through. The outcome is `finished`, `raised` (with the traceback), `cancelled` or `timed_out`, -reported in a successful result, as `run_script` reports a failed step. Everything that can run the -script's Python, its body and also a result's or an exception's own methods (iteration, `__str__`) and the -finalizers of what its namespace and traceback hold, runs inside the script's audit scope and under the -watcher; the capture functions the runner calls are the ones it installed, held from then on. A -finalizer that runs on past the budget or a cancel while the namespace is cleared makes the run -`timed_out` or `cancelled`, though Python swallows the interrupt it raises there. +**Entry contract.** `run_python_code()` (`plugin/PythonScriptRunner.cpp`) runs the code on the calling thread, the +MCP job that runs `run_python`, holding an interpreter lease and the GIL. The code is text, compiled as Python +compiles any code string, so a coding line in it changes nothing; a file's bytes are decoded first as Python reads +a source file, by its BOM or its PEP 263 declaration, else as UTF-8 (`decode_python_source()`). It runs as the main +program, in a `types.ModuleType("__main__")` of its own, with `args` bound and `orca` importable. A run is a *file +run* when `filename` names an existing file (the dialog's and `--mcp-script`'s always do): `__file__` and +`sys.argv` (`[path]`) name it, its folder serves its imports, and its PEP 723 dependencies are installed first. +Any other name (the default ``, a bare traceback name) is code sent as text, which gets none of that; +`filename` still names it in tracebacks. The value left in `result` is read once when the body returns; in code +sent as text, one that is not JSON (a dict with string keys, a list, a string, a finite number, a boolean or None, +nested) makes the run `raised`, while in a file run, where a standalone script may well have a variable of that +name, it is no result, and the output ends with a line saying it was not JSON. `SystemExit` with code 0 or None +finishes the run. Output is captured up to 256 KiB by a stream installed once over `sys.stdout` and `sys.stderr` +that routes writes by the run bound to the writing thread: the run's own thread, the threads it starts, its pool +tasks and its window callbacks; other threads print through. The outcome is `finished`, `raised` (with the +traceback), `cancelled` or `timed_out`, reported in a successful result, as `run_script` reports a failed step. -**Cancellation.** A watcher thread interrupts the run with `PyThreadState_SetAsyncExc` when `cancel -{job}` stops the job (`run_python` is `cancellable`) or the time budget (default 300 s) runs out, again -every second until the code ends; code blocked inside a C call stops once the call returns. A pending -interrupt is cleared before the thread runs anything else. +**The run scope.** `PythonRunScope` (`plugin/PythonRunScope.hpp`) is the run's state that its threads, pool tasks +and window callbacks share: identity, file, tool bridge, the work it waits for, admission, and whether its UI is +closed. It is bound thread-locally (`ScopedPythonRun`, `current_python_run()`) to the run's thread, carried by the +interpreter's thread shim into the threads it starts, by a wrapper of `concurrent.futures.thread._WorkItem.run` +into its pool tasks, and captured by its window callbacks. Lock order: the GIL before the scope's mutex; nothing +holding the mutex waits for the GIL. + +**One interpreter, many runs.** Runs overlap (an agent's beside a person's), so everything a run changes is keyed +by the run bound to the calling thread (`_run_id()`), in the helper module `_orca_run_capture` the runner installs +once (under a lock taken without the GIL, since its imports release the GIL). The interpreter's own `__main__` +module and the `sys` module get a `ModuleType` subclass (module `__class__` assignment): attribute access on +`__main__` goes to the bound run's module, so `typing.get_type_hints`, `dataclasses` and pickling find a script's +globals, and `sys.argv` to the bound run's own list, so every list operation and reassignment stays in the run; +code outside runs sees the app's. C code that reads the modules' dicts directly (`PyModule_GetDict`, +`PySys_GetObject`) sees the app's too. Routing `argv` costs every Python attribute read on `sys` about 70 ns. A +script that puts a plain class back is undone at the next run's entry, and one that replaces +`sys.modules["__main__"]` gets the original back when it leaves. No run changes `sys.path`: a finder in +`sys.meta_path`, just before the path finder and so after the built-in and frozen importers as `sys.path[0]` is +under `python file.py`, serves the threads of an active file run from the script's folder through `FileFinder` +(source, extension modules, sourceless `.pyc`, namespace packages), and the submodules of the packages it served +there, never those of a package found elsewhere, even one installed below the folder. It compiles source afresh +each run, never from or to a cached `.pyc`, so an edit shows on the next run whatever the file's timestamp. What it +served for a folder is evicted when the last active run from that folder ends, each module only while +`sys.modules` still holds the module it found (by its spec), never an extension module, which can't load twice, +nor one a plugin's load recorded as its own. `sys.modules` stays one cache: a script's `import utils` gets a `utils` the app or a plugin +already imported, and two overlapping scripts in different folders with a helper of the same name share whichever +came first, so helpers want distinct names. Modules a script imports through folders it adds to `sys.path` itself +stay cached, as Python's cache keeps them. + +**Threads, pools and the end of a run.** Like `python file.py`, a run ends once its work is done: its code, the +non-daemon `threading.Thread`s it starts, its window callbacks while they run, and the pool tasks it submits. Its +code runs on a thread Python didn't start (an MCP job thread), which Python sees as a daemon dummy thread, so the +body runs with that thread's daemon flag cleared: as on `python file.py`'s main thread, a thread it starts is +non-daemon unless it says otherwise. Unlike there, `threading.main_thread()` is still the app's main thread, and +the run's own thread is named `Dummy-N`. The shim counts a thread on the run in the starting thread, before the OS +thread exists, so a thread started late, +even by another of the run's threads, is never missed; raw `_thread` threads are not waited for, as Python's exit +doesn't wait for them. A pool's workers are reused across runs, so they carry no run and are never waited for, +though the pool's initializer, which runs on a new worker before any task, runs inside the run whose thread started +the worker, as the task it was started for does (its binding and identity, one of its interrupt targets), counted +as the run's work from before the worker's thread starts until it returns, so the run waits for it even when that +task is cancelled. Once the run's admission has closed, such a worker doesn't start (a thread of the run gets the +same error as for any thread), since its initializer would run outside any run and identity. A work +item created from a thread of a run (a wrapped `_WorkItem.__init__`; `submit` creates exactly one per task it +accepts) gets a tag of that run, a C++ object that counts its task on the run and uncounts it once, and the +`_WorkItem.run` wrapper runs the whole item (the task, the future's completion and the done callbacks the pool calls +from there) inside the submitting run, whichever run started the worker, with the worker as one of its interrupt +targets; no `BaseException` gets past it, so neither a Stop nor a `SystemExit` in a callback, nor the stock `run` +refusing a future completed by hand, ends a worker other runs share. A done callback therefore runs in the run +that submitted the task, whoever added it; the callbacks of a future no pool runs (a bare `Future` another thread +completes), and those `cancel()` runs on the cancelling thread, run in that thread's own context, as in CPython. A +Stop in one done callback ends that future's later callbacks too, as any `BaseException` does in CPython's callback +loop. A future completed without its item running (cancelled, or failed by a broken pool) is uncounted by its +callback, the tag making sure only one of the two uncounts the item; the worker that later takes a cancelled item +still marks its future notified, which `wait()` and `as_completed()` need. A `submit` that raises after creating +its item (a wrapped `submit`) cancels it: the caller got no future, and the item may sit queued with no worker to +run it. The callback and that hand-off are in place before the count is taken, so no count is ever left without +them. The run waits in C++, +without the GIL, never through `Thread.join()`, whose interrupted wait marks a live thread stopped, and closes its +admission in the same locked step that sees nothing left: from then on a thread of the run can't start a thread +(it raises, as at interpreter shutdown), a submit from one raises, and a callback does nothing. Then it shuts down +the pools its own `__main__` code created (`ThreadPoolExecutor.__init__` records the creating frame: the run's +`__main__`, a module the finder served for a folder, or neither); a folder's pools are shut down when the modules +that made them are evicted, so one run never shuts down a pool another run from the folder still uses, and other +pools (`from library import POOL`) keep working. `atexit.register` called from a run's `__main__` code records on +the run, called from a folder's helper (at its import, say) records on the folder, and anything else (`logging`, +`multiprocessing`) registers with the process; `atexit.unregister` removes only from the caller's own +registrations, filed the same way. The run takes its functions once, as Python's exit does (one registered while +they run is not called), and calls them last first once it is quiet. A folder's teardown, when its last run ends, +first takes what the folder holds, evicts its modules and lists the pools they made, as host bookkeeping no +interrupt reaches, so a run that enters the folder while the rest runs imports its helpers afresh and keeps them and +their pools. A module that stays (a plugin's, an extension) has its `atexit` functions handed to the process's exit +there. Then, as Python ends a program, it runs the evicted modules' `atexit` functions, clears their globals (so +what they hold, cycles included, finalizes there, under the run's watcher, while their pools still work) and shuts +down the pools it listed. Each of these cleanup steps (the run's pools and `atexit` functions too) works through +what was taken piece by piece, removing a piece as it starts (an `atexit` function) or once it is done (a module's +globals, a pool), and the runner resumes the step after an interrupt, so an interrupt cuts only the piece it lands +in. A pool is shut down again on a resume even when its `_shutdown` flag is set, since an interrupt may have cut its +shutdown between setting the flag and waking its workers. The teardown +waits while a plugin's import is in progress (`PythonInterpreter::plugin_import_in_progress()`, since a plugin +records its modules only after its import returns), and then runs at the next entry from that folder, before that +run's code, on its thread, under its identity and watcher, with the output in its capture. A daemon thread still +running after the run sees the run's globals, and its evicted helpers', cleared, and is refused tool calls. + +**Cancellation.** A watcher thread interrupts the run with `PyThreadState_SetAsyncExc` when `cancel {job}` stops +the job (`run_python` is `cancellable`) or the time budget (`timeout_s`, default 300 s; the dialog's run has none, +since its Stop ends it) runs out, again every second until it ends. What it interrupts follows the run's phase, +which is set, and read before each interrupt, under the GIL: in *Body* (the code) and *Exit* (`atexit` functions, +the result's own code, the UI teardown, the namespace's finalizers, the folder's teardown, dropping what the script +left in its routes, its `sys.argv` or in place of `__main__`) the run's thread and its interrupt targets (its +threads, and the workers running its items or its pools' initializers); in *Threads* (the wait) the targets only; +in *Drain* (the host's bookkeeping: entering the run and its folder, taking the run's `atexit` functions, releasing +the folder and taking what its teardown evicts, detaching the run's routes, the output, closing the tools) nothing, +so no interrupt breaks the host's own bookkeeping, though a stop or time-out there is still recorded. The runner +switches to *Drain* for each piece of bookkeeping and back to *Exit* for the cleanup it hands over, so what the +script left finalizes only where a stop can still reach it. At the first stop or time-out it also cancels the +run's tool calls in flight (`PythonRunRequest::stop_calls`, the job's stop request), so a waiting tool returns at +once, marks the run stopped, so its queued pool tasks don't run, and closes its UI. Five seconds after a stop the +run stops waiting for its work and closes its admission anyway. Code blocked inside a C call, or a tool call that +can't be interrupted, holds the run until it returns. A pending interrupt is cleared before the thread runs +anything else. + +**Dependencies.** A file run's PEP 723 block (`# /// script` … `# ///`) is found, after normalizing line ends, with +the PEP's reference expression, and read with `tomllib`, so quoted commas, multi-line arrays and comments read as +TOML says; a malformed block, two `script` blocks or a `dependencies` that isn't a list of strings make the run +`raised` before its code. Its dependencies are installed before the code, without the GIL, through +`plugin_loader::install_packages()` into the shared package folder plugins use; installs are serialized, so a +script's and a plugin's never write the folder at once. An install that fails makes the run `raised` before its +code. The install isn't covered by the watcher; uv's 120 s timeout bounds it. **Identity.** A person's script runs under the audit identity `script`, an agent's under `mcp` -(`kScriptIdentityPerson`, `kScriptIdentityAgent`); `McpService::person_run()` tells them apart by the -run's lineage, since the dialog's and `--mcp-script`'s jobs are marked as a person's (`as_person()`). -Every audited access is allowed to these identities and logged under them (reads at debug level), apart -from the categorical denies every plugin has (`is_denied_path()`): nothing contains the code, and the -setting is the boundary. Threads the code starts keep the identity through the interpreter's thread -shim, but outlive the run. A run owns what its calls leave behind, as a JSON script does -(`begin_script_scope()`): auto-answer rules, a recording and a held press end with it. The identities are reserved: a plugin whose key equals one is refused before any of its code runs. A -plugin's `run_python` runs under the plugin's own identity and grants instead. +(`kScriptIdentityPerson`, `kScriptIdentityAgent`); `McpService::person_run()` tells them apart by the run's +lineage, since the dialog's and `--mcp-script`'s jobs are marked as a person's (`as_person()`). Every audited +access is allowed to these identities and logged under them (reads at debug level), apart from the categorical +denies every plugin has (`is_denied_path()`): nothing contains the code, and the setting is the boundary. The +threads, pool tasks and window callbacks of a run carry its identity. A run owns what its calls leave behind, as a +JSON script does (`begin_script_scope()`): auto-answer rules, a recording and a held press end with it. The +identities are reserved: a plugin whose key equals one is refused before any of its code runs. A plugin's +`run_python` runs under the plugin's own identity and grants instead, with the same main-program environment, but +its windows, callbacks and storage stay the plugin's. -**The setting.** One switch, `mcp_python_scripts`, off by default, lets both a person's scripts and an -agent's `run_python` run; with it off they are refused (a plugin's `run_python` needs none). It is -changed only in `PythonScriptsDialog`, opened from Preferences › AI features › Python scripts, which is -named `kHiddenFromAutomation`: the UI tools never see it and `ModalTracker` leaves it off the stack, so -no dialog tool or auto-answer rule reaches it. No tool writes the key. +**The setting.** One switch, `mcp_python_scripts`, off by default, lets both a person's scripts and an agent's +`run_python` run; with it off they are refused (a plugin's `run_python` needs none). It is changed only in +`PythonScriptsDialog`, opened from Preferences › AI features › Python scripts, which is named +`kHiddenFromAutomation`: the UI tools never see it and `ModalTracker` leaves it off the stack, so no dialog tool or +auto-answer rule reaches it. No tool writes the key. -**The host surface and the bridge.** A script reads through `orca.host` as a plugin does. The functions -that change state outside the tools (the staged preset update, bundle reload, the 3MF copy, plugin UI, -plugin storage) call `require_plugin_caller()` and refuse a script identity; the test "every orca.host -function is classified" lists every function as script-callable or plugin-only, so a new binding is -plugin-only until someone classifies it. `orca.host.tools.call(name, args)` and `run_script(script, -vars)`, whose script is a dict or its JSON text (`plugin/host/PluginHostTools.cpp`), reach the tools through the `ToolBridge` bound to the calling -thread: a run binds one whose calls are `ToolContext::call_child()` of the `run_python` job, so each has -its tool's guards, admission and undo, and the GIL is released while it waits. An error result raises -`orca.host.tools.ToolError` with its data as `details`. A thread a script starts has no bridge and is -refused, and code with no audit identity at all is refused. +**The host surface and the bridge.** A script reaches the whole `orca.host`, as a plugin does: reads, `orca.host.ui` +(message boxes, progress dialogs, HTML windows, dock panels, notifications), the staged preset update, bundle +reload and the 3MF copy; nothing is plugin-only. `orca.host.plugin.storage()` is a script's own folder, the folder +of its file; code sent as text has none. `orca.host.tools.call(name, args)` and `run_script(script, vars)`, whose +script is a dict or its JSON text (`plugin/host/PluginHostTools.cpp`), reach the tools from any thread of the run +while it lasts, through the run's bridge: its calls are `ToolContext::call_child()` of the `run_python` job, so +each has its tool's guards, admission and undo, and the GIL is released while it waits. At the end the bridge +closes, and the run waits for calls already inside it before its `ToolContext` goes. An error result raises +`orca.host.tools.ToolError` with its data as `details`. Code with no audit identity at all is refused. + +**A script's UI.** What a script's run opens (windows, dock panels, progress dialogs, message boxes, notification +links) is registered under a run-unique owner (`script/`; a plugin key never holds `/`), and closes with the +run: after its `atexit` functions and before its namespace is cleared, the run marks its UI closed and tears it +down on the UI thread, waiting for that (`PluginHostUi::close_run_windows()`), so none of its callbacks runs after +its globals go. At the first stop or time-out the watcher does the same at once (posted only while the app isn't +closing), which ends a modal loop the run waits in: a script's `ui.message` box is registered while it is shown and +ended with `EndModal`. From then on a creation from a thread of the run raises, and one already posted checks the +run on the UI thread and creates nothing, so nothing the run opens outlives it. A window callback (`on_message`, +`on_submit`, `on_close`, a notification's `on_click`) captures the run when it is made and runs inside it, +counted as active work; it runs on the UI thread, so it is refused tool calls (the tools wait for the UI thread), +and hands its work to the script's own code, through a `queue.Queue` say, which can call them. While a modal the +run opened is up, tool calls that change the project are refused by the modal guard, the run's own included, so +interactive macros use modeless windows. A script's dock panel keeps its saved layout under the script identity and +its title. A plugin's `run_python` leaves all of this to the plugin. + +**Idle.** A `run_python` job doesn't count as busy for `wait {for: "idle"}` (`JobRegistry::set_idle()`); the +calls it makes, and what they start, do. A macro waiting for the person in its window would otherwise hold every +agent's idle wait, and a `tools/mcp` driver run from the dialog against the same app would wait on its own run. **Journal and replay.** `run_python` is journaled as one step holding its code, kept when the code failed partway; its tool calls are not journaled. In a JSON script a `run_python` step's `code` is never @@ -2426,7 +2553,9 @@ A plugin's code calls the tools through `orca.host.tools` once it holds the `too (`PluginPermissions::tools`), which it declares with `request_permissions(tools=True)`. The person answers it at load in its own prompt (`request_tools_permission()`), apart from the plugin's other permissions, and a refusal leaves the plugin loading without it. With the permission a plugin can do what an agent can: -work in the GUI, answer dialogs, replace the project, write presets and files; the prompt says so. +work in the GUI, answer dialogs, replace the project, write presets and files; the prompt says so. A plugin's +`run_python` is the plugin's own code: its identity and grants, its windows and storage, though it runs as a main +program as any script does. A plugin's call waits for the UI thread, so it comes only from a thread nothing there waits for: a Script worker, a Python thread one starts (the thread shim carries the mark) or MCP's own thread running a plugin diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 786d2224cb..2d16a24a92 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -763,6 +763,8 @@ set(SLIC3R_GUI_SOURCES plugin/PythonPluginInterface.hpp plugin/PluginOperations.cpp plugin/PluginOperations.hpp + plugin/PythonRunScope.cpp + plugin/PythonRunScope.hpp plugin/PythonScriptRunner.cpp plugin/PythonScriptRunner.hpp plugin/PyPluginPackage.hpp diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index ad5eab70d1..9d23a7c352 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -199,7 +199,14 @@ bool JobRegistry::any_running_except(const std::set& excluded) cons { std::lock_guard lock(m_mutex); return std::any_of(m_jobs.begin(), m_jobs.end(), - [&](const auto& kv) { return !kv.second.finished && excluded.count(kv.first) == 0; }); + [&](const auto& kv) { return !kv.second.finished && !kv.second.idle && excluded.count(kv.first) == 0; }); +} + +void JobRegistry::set_idle(const std::string& id) +{ + std::lock_guard lock(m_mutex); + if (auto it = m_jobs.find(id); it != m_jobs.end()) + it->second.idle = true; } std::string JobRegistry::begin_operation(const std::string& id) @@ -248,6 +255,8 @@ nlohmann::json JobRegistry::list() const {"age_ms", std::chrono::duration_cast(now - job.created).count()}}; if (!job.parent.empty()) j["parent"] = job.parent; + if (job.idle && !job.finished) + j["idle"] = true; out.push_back(std::move(j)); } return out; diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index 29eda6cd8a..f8a80b67f7 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -75,8 +75,11 @@ public: void request_stop(const std::string& id); // True when a stop was asked for `id` or one of its ancestors. bool stop_requested(const std::string& id) const; - // True when a running job exists that is not in `excluded`. + // True when a running job exists that is not in `excluded` and isn't set idle. bool any_running_except(const std::set& excluded) const; + // Marks a running job as one that leaves `wait {for: "idle"}` to the calls it makes: a run_python run, which may + // wait for a person in its window for minutes. list() shows it as idle. + void set_idle(const std::string& id); // Operation admission: a job marked as an operation holds the project until it finishes. // Marks `id` unless another operation is running, whose id it then returns ("" on success). std::string begin_operation(const std::string& id); @@ -104,6 +107,7 @@ private: std::vector ancestors; bool finished = false; bool operation = false; + bool idle = false; ToolResult result; std::chrono::steady_clock::time_point created; }; diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index 6abcded53b..f782413e12 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -160,6 +160,8 @@ const char* kInstructions = "settings and calling tools through orca.host.tools, once the person has allowed Python scripts in Preferences.\n" "API lane:\n" "- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n" + "- Plugins may offer operations (plugin..) that the tool list does not show: api_describe lists and " + "searches them with their schemas, api_call runs them.\n" "- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words; " "each setting's meta has its description and where (its settings page and group).\n" "- Objects, parts and plates are 0-based indices, as list_objects and list_plates give them; filament slots and " @@ -953,7 +955,8 @@ std::shared_ptr McpService::start_python_run(std::string code, const run->set_job(ctx.job_id()); return handler(args, ctx); }; - json args{{"code", std::move(code)}}; + // No time limit: the person has the dialog's Stop. + json args{{"code", std::move(code)}, {"timeout_s", 0}}; if (!file.empty()) args["filename"] = path_to_utf8(file); diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 0c21919413..3575d53807 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -217,7 +217,8 @@ void register_app_tools(McpService& service) ToolDef wait = inspect_tool( "wait", L("Wait for a condition"), "Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, " - "no running job, nothing slicing or arranging, no gizmo working in the background), \"dialog\" / \"no_dialog\", or " + "no running job (a run_python run counts only through the calls it makes), nothing slicing or arranging, no gizmo " + "working in the background), \"dialog\" / \"no_dialog\", or " "\"job\" with a job id returned by " "an earlier call - then the reply is that job's result. Returns {satisfied:false} on timeout; call it again.", object_schema({{"for", enum_prop({"ready", "idle", "dialog", "no_dialog", "job"}, "What to wait for; default job when job " diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 105be4d799..9b41abb1f5 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -120,10 +120,12 @@ void register_python_tools(McpService& service) ToolDef run = mutate_tool( "run_python", L("Run Python code"), - "Run Python code inside OrcaSlicer against orca.host, the plugin API (python_api searches it): read objects, meshes " - "(numpy) and settings, compute, and change the project through orca.host.tools.call(name, args), which calls these " - "same tools with their guards and undo. The code is a module body: `args` holds the args you pass, set `result` to " - "a JSON value to return it; print() output comes back as output. Returns {status: finished | raised | cancelled | " + "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin " + "API (python_api searches it): read objects, meshes (numpy) and settings, compute, use orca.host.ui and the preset " + "API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args), from the code " + "and from the threads and pool tasks it starts while the run lasts. The run ends once its code and the non-daemon " + "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " + "to a JSON value to return it; print() output comes back as output. Returns {status: finished | raised | cancelled | " "timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. Python runs " "with OrcaSlicer's full access to the computer, so a person must allow Python scripts in Preferences first. Recorded " "by export_script as one step with its code, which a replay runs again against the project as it is then.", @@ -131,7 +133,9 @@ void register_python_tools(McpService& service) {"args", {{"type", "object"}, {"description", "Bound to the name `args` in the code."}}}, {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 3600}, {"description", "The run is stopped as timed_out after this many seconds (default 300)."}}}, - {"filename", prop("string", "The name tracebacks show for the code, such as its file's (default ).")}}, + {"filename", prop("string", "The name tracebacks show for the code (default ). An existing file's " + "path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports " + "from its folder and its PEP 723 dependencies; any other name only names it.")}}, {"code"}), [&service](const json& args, ToolContext& ctx) { const std::string& plugin = ctx.caller_plugin(); @@ -150,6 +154,8 @@ void register_python_tools(McpService& service) // A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON // script does: it all ends with the run. const std::string job = ctx.job_id(); + // A run may wait for a person in its window: `wait {for: "idle"}` counts only the calls it makes. + service.jobs().set_idle(job); service.begin_script_scope(job); struct ScopeEnd { @@ -165,8 +171,12 @@ void register_python_tools(McpService& service) request.args = args.value("args", json::object()); request.identity = identity; request.filename = arg_string(args, "filename", ""); + // 0, below the schema's minimum, is passed only in process, by the Run Script dialog, whose Stop ends a run: + // every external path validates the arguments. It means no time limit. request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300)); request.cancelled = [&ctx] { return ctx.cancelled(); }; + // A stop or time-out cancels the run's tool calls in flight too, so one that waits returns at once. + request.stop_calls = [&service, job] { service.request_stop(job); }; const PythonRunOutcome out = run_python_code(request); if (out.status == "unavailable") throw ToolFailure(out.message); diff --git a/src/slic3r/plugin/PluginLoader.cpp b/src/slic3r/plugin/PluginLoader.cpp index ca4f74c96d..85ec462d50 100644 --- a/src/slic3r/plugin/PluginLoader.cpp +++ b/src/slic3r/plugin/PluginLoader.cpp @@ -479,6 +479,9 @@ bool install_packages(const std::vector& pkgs, std::string& error) { if (pkgs.empty()) return true; + // A plugin's load and a script's run can install at once; both write the one shared package folder. + static std::mutex install_mutex; + std::lock_guard install_lock(install_mutex); const std::string uv_path = PythonInterpreter::bundled_uv_path(); if (uv_path.empty()) { diff --git a/src/slic3r/plugin/PluginLoader.hpp b/src/slic3r/plugin/PluginLoader.hpp index d6eba7b68b..67e2fcdc04 100644 --- a/src/slic3r/plugin/PluginLoader.hpp +++ b/src/slic3r/plugin/PluginLoader.hpp @@ -29,7 +29,7 @@ bool load(const PluginDescriptor& descriptor, void unload(Plugin& plugin); // Install Python dependencies into the shared packages directory via the bundled uv. Blocks, with -// a 120 s cap. +// a 120 s cap. Installs are serialized: plugins' loads and scripts' runs share the folder. bool install_packages(const std::vector& pkgs, std::string& error); // Read a local .py/.whl package's metadata without installing it, and report whether a package is diff --git a/src/slic3r/plugin/PythonInterpreter.cpp b/src/slic3r/plugin/PythonInterpreter.cpp index bc231c2960..5abf32c9bd 100644 --- a/src/slic3r/plugin/PythonInterpreter.cpp +++ b/src/slic3r/plugin/PythonInterpreter.cpp @@ -190,6 +190,16 @@ std::string executable_name(const char* base) #endif } +// Counts a plugin's module import from its start until its modules are recorded. +struct ScopedPluginImport +{ + std::atomic& count; + explicit ScopedPluginImport(std::atomic& count) : count(count) { ++count; } + ~ScopedPluginImport() { --count; } + ScopedPluginImport(const ScopedPluginImport&) = delete; + ScopedPluginImport& operator=(const ScopedPluginImport&) = delete; +}; + bool add_sys_path_entry(const boost::filesystem::path& path, std::string& error, bool* inserted = nullptr) { if (inserted) @@ -807,6 +817,11 @@ int PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds timeout } } +bool PythonInterpreter::plugin_uses_module(const std::string& name) const +{ + return m_plugin_module_users.count(name) != 0; +} + bool PythonInterpreter::add_plugin_sys_path(const std::string& path, std::string& error) { if (!m_initialized.load(std::memory_order_acquire)) { @@ -1130,7 +1145,8 @@ PyObject* PythonInterpreter::load_module_from_file(const std::string& file // Ensure module is re-imported fresh by removing any cached instance. remove_module_tree_locked(module_name); - // Import the module + // Import the module. Until its modules are recorded, a script's run leaves alone a module the import took. + const ScopedPluginImport importing(m_plugin_imports); PyObject* module = PyImport_ImportModule(module_name.c_str()); record_plugin_modules_locked(module_name, plugin_paths ? *plugin_paths : std::vector{}, plugin_modules); if (!module) { @@ -1179,6 +1195,7 @@ PyObject* PythonInterpreter::load_module_from_directory(const std::string& dir_p remove_module_tree_locked(pkg_name); + const ScopedPluginImport importing(m_plugin_imports); PyObject* module = PyImport_ImportModule(pkg_name.c_str()); record_plugin_modules_locked(pkg_name, plugin_paths ? *plugin_paths : std::vector{}, plugin_modules); if (!module) { diff --git a/src/slic3r/plugin/PythonInterpreter.hpp b/src/slic3r/plugin/PythonInterpreter.hpp index 3713dd9fab..effb1ba224 100644 --- a/src/slic3r/plugin/PythonInterpreter.hpp +++ b/src/slic3r/plugin/PythonInterpreter.hpp @@ -80,6 +80,12 @@ public: // removed when the final plugin using it is unloaded. bool add_plugin_sys_path(const std::string& path, std::string& error); + // Whether a loaded plugin's records hold the module `name`, so it belongs to that plugin. GIL held. + bool plugin_uses_module(const std::string& name) const; + // Whether a plugin's module import is under way. A plugin records the modules it imported only after its import + // returns, so until then nothing says that a module it took is its. Any thread. + bool plugin_import_in_progress() const { return m_plugin_imports.load() > 0; } + // Load a Python module from file path PyObject* load_module_from_file(const std::string& file_path, std::string& error, @@ -131,6 +137,7 @@ private: std::unordered_map m_plugin_path_owned; std::unordered_map m_plugin_module_users; std::unordered_map m_plugin_module_owned; + std::atomic m_plugin_imports{0}; }; class PythonRuntimeLease diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 2613582000..cd23bc9335 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -9,6 +9,7 @@ #include #include #include "slic3r/plugin/PythonPluginInterface.hpp" +#include #include #include @@ -19,6 +20,8 @@ #include #include "PythonInterpreter.hpp" +#include "PythonRunScope.hpp" +#include "PythonScriptRunner.hpp" #include "PluginJsonPy.hpp" #include "PluginOperations.hpp" #include "host/PluginHostTools.hpp" @@ -796,27 +799,74 @@ void install_python_thread_audit_shim() py::object shim = py::cpp_function( [original](py::object function, py::object args, py::object kwargs) -> py::object { + const auto start = [&](const py::object& target) { + return kwargs.is_none() ? original(target, args) : original(target, args, kwargs); + }; + // A script's run reaches the threads it starts. A pool's worker is the exception: pools are reused + // across runs, so a worker carries neither run nor identity, and each task brings its own, as the + // pool's initializer does from the run that started the worker. + std::shared_ptr run = current_python_run().run; + if (run && python_run_is_pool_worker(function)) { + const PoolInitializerBinding initializer = python_run_bind_pool_initializer(function, run); + if (initializer == PoolInitializerBinding::Refused) + throw std::runtime_error("can't start a new thread: the script's run has ended"); + try { + return start(function); + } catch (...) { + if (initializer == PoolInitializerBinding::Counted) + run->task_done(); + throw; + } + } const std::string plugin_key = PluginAuditManager::instance().current_plugin(); - if (plugin_key.empty()) { + if (plugin_key.empty() && !run) { // Not called from a plugin: preserve the stock implementation untouched. - return kwargs.is_none() ? original(function, args) : original(function, args, kwargs); + return start(function); } const std::string capability = PluginAuditManager::instance().current_capability(); // A thread a Script worker starts may call tools as the worker may. const bool tool_caller = tool_caller_thread(); + // Counted before the OS thread exists, so the run never misses a thread started late. + const bool waited = run && python_run_waits_for(function); + if (run && !run->thread_starting(waited)) + throw std::runtime_error("can't start a new thread: the script's run has ended"); py::object guarded = py::cpp_function( - [function, plugin_key, capability, tool_caller](py::args call_args, py::kwargs call_kwargs) -> py::object { - ScopedPluginAuditContext audit_scope(plugin_key, capability); + [function, plugin_key, capability, tool_caller, run, waited](py::args call_args, py::kwargs call_kwargs) -> py::object { + std::optional audit_scope; + if (!plugin_key.empty()) + audit_scope.emplace(plugin_key, capability); std::optional caller; if (tool_caller) caller.emplace(); + std::optional bound; + struct Ended + { + PythonRunScope* scope; + unsigned long ident; + ~Ended() + { + if (scope != nullptr) + scope->thread_ended(ident); + } + } ended{nullptr, PyThread_get_thread_ident()}; + if (run) { + bound.emplace(run, PythonRunThread::Started); + run->thread_started(ended.ident, waited); + ended.scope = run.get(); + } PyObject* result = PyObject_Call(function.ptr(), call_args.ptr(), call_kwargs.ptr()); if (result == nullptr) throw py::error_already_set(); return py::reinterpret_steal(result); }); - return kwargs.is_none() ? original(guarded, args) : original(guarded, args, kwargs); + try { + return start(guarded); + } catch (...) { + if (run) + run->thread_start_failed(waited); + throw; + } }, py::arg("function"), py::arg("args"), py::arg("kwargs") = py::none()); diff --git a/src/slic3r/plugin/PythonRunScope.cpp b/src/slic3r/plugin/PythonRunScope.cpp new file mode 100644 index 0000000000..eaa9a4ed2b --- /dev/null +++ b/src/slic3r/plugin/PythonRunScope.cpp @@ -0,0 +1,195 @@ +#include "PythonRunScope.hpp" + +#include "PluginAuditManager.hpp" +#include "host/PluginHostTools.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +namespace { +thread_local PythonRunBinding tl_binding; +} // namespace + +PythonRunScope::PythonRunScope(std::uint64_t id, std::string identity, boost::filesystem::path file, ToolBridge* bridge) + : m_id(id), m_identity(std::move(identity)), m_file(std::move(file)), m_bridge(bridge) +{} + +bool PythonRunScope::owns_ui() const { return is_script_identity(m_identity); } + +std::string PythonRunScope::ui_owner() const { return owns_ui() ? "script/" + std::to_string(m_id) : m_identity; } + +nlohmann::json PythonRunScope::call_tool(const std::string& tool, const nlohmann::json& args) +{ + ToolBridge* bridge = nullptr; + { + std::lock_guard lock(m_mutex); + if (m_tools_closed) + throw std::runtime_error("The script's run has ended; a thread it started calls no tools after that"); + if (m_bridge == nullptr) + throw std::runtime_error("This run has no tools to call"); + bridge = m_bridge; + ++m_calls_in_flight; + } + struct Leave + { + PythonRunScope& scope; + ~Leave() + { + { + std::lock_guard lock(scope.m_mutex); + --scope.m_calls_in_flight; + } + scope.m_calls_cv.notify_all(); + } + } leave{*this}; + return bridge->call(tool, args); +} + +bool PythonRunScope::has_tools() const +{ + std::lock_guard lock(m_mutex); + return m_bridge != nullptr && !m_tools_closed; +} + +bool PythonRunScope::tools_closed() const +{ + std::lock_guard lock(m_mutex); + return m_tools_closed; +} + +void PythonRunScope::close_tools() +{ + std::unique_lock lock(m_mutex); + m_tools_closed = true; + m_calls_cv.wait(lock, [this] { return m_calls_in_flight == 0; }); + m_bridge = nullptr; +} + +bool PythonRunScope::thread_starting(bool waited) +{ + std::lock_guard lock(m_mutex); + if (m_admission_closed) + return false; + if (waited) + ++m_waited_pending; + return true; +} + +void PythonRunScope::thread_start_failed(bool waited) +{ + std::lock_guard lock(m_mutex); + if (waited) + --m_waited_pending; +} + +void PythonRunScope::thread_started(unsigned long ident, bool waited) +{ + std::lock_guard lock(m_mutex); + if (waited) + --m_waited_pending; + m_live_threads[ident] = waited; +} + +void PythonRunScope::thread_ended(unsigned long ident) +{ + std::lock_guard lock(m_mutex); + m_live_threads.erase(ident); +} + +bool PythonRunScope::callback_entering() +{ + std::lock_guard lock(m_mutex); + if (m_admission_closed) + return false; + ++m_callbacks_active; + return true; +} + +void PythonRunScope::callback_left() +{ + std::lock_guard lock(m_mutex); + --m_callbacks_active; +} + +bool PythonRunScope::task_submitted() +{ + std::lock_guard lock(m_mutex); + if (m_admission_closed) + return false; + ++m_tasks_outstanding; + return true; +} + +void PythonRunScope::task_done() +{ + std::lock_guard lock(m_mutex); + --m_tasks_outstanding; +} + +void PythonRunScope::task_running(unsigned long ident) +{ + std::lock_guard lock(m_mutex); + m_task_targets.insert(ident); +} + +void PythonRunScope::task_finished(unsigned long ident) +{ + std::lock_guard lock(m_mutex); + if (auto it = m_task_targets.find(ident); it != m_task_targets.end()) + m_task_targets.erase(it); +} + +bool PythonRunScope::close_admission_if_quiet() +{ + std::lock_guard lock(m_mutex); + if (m_admission_closed) + return true; + if (m_waited_pending > 0 || m_callbacks_active > 0 || m_tasks_outstanding > 0) + return false; + for (const auto& [ident, waited] : m_live_threads) + if (waited) + return false; + m_admission_closed = true; + return true; +} + +void PythonRunScope::close_admission() +{ + std::lock_guard lock(m_mutex); + m_admission_closed = true; +} + +bool PythonRunScope::admission_closed() const +{ + std::lock_guard lock(m_mutex); + return m_admission_closed; +} + +void PythonRunScope::for_each_interrupt_target(const std::function& fn) const +{ + std::lock_guard lock(m_mutex); + for (const auto& [ident, waited] : m_live_threads) + fn(ident); + for (const unsigned long ident : m_task_targets) + fn(ident); +} + +const PythonRunBinding& current_python_run() { return tl_binding; } + +ScopedPythonRun::ScopedPythonRun(std::shared_ptr run, PythonRunThread kind) : m_previous(std::move(tl_binding)) +{ + tl_binding = PythonRunBinding{std::move(run), kind}; +} + +ScopedPythonRun::~ScopedPythonRun() { tl_binding = std::move(m_previous); } + +} // namespace Slic3r diff --git a/src/slic3r/plugin/PythonRunScope.hpp b/src/slic3r/plugin/PythonRunScope.hpp new file mode 100644 index 0000000000..668d723d4f --- /dev/null +++ b/src/slic3r/plugin/PythonRunScope.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +class ToolBridge; + +// What a thread is doing for the run bound to it. +enum class PythonRunThread { + Main, // the run's own thread, which runs its code + Started, // a thread the run started, or a pool worker running one of the run's tasks + Callback, // a window callback of the run, on the UI thread +}; + +// One run_python run, shared by the thread that runs its code, the threads it starts, the pool tasks it submits and +// its window callbacks: who it runs as, its file, its tool bridge, the work it waits for before it ends, and whether +// it still takes new work and opens UI. Runs can overlap, so everything a run changes is keyed by it. +// +// Lock order: the GIL before this object's mutex. Nothing that holds the mutex waits for the GIL, so the watcher may +// raise interrupts under it while a thread of the run, holding the GIL, waits to record that it ended. +class PythonRunScope +{ +public: + PythonRunScope(std::uint64_t id, std::string identity, boost::filesystem::path file, ToolBridge* bridge); + + std::uint64_t id() const { return m_id; } + // kScriptIdentityPerson or kScriptIdentityAgent for a person's or an agent's script, or a plugin's key. + const std::string& identity() const { return m_identity; } + // The file the code was read from; empty for code sent as text. + const boost::filesystem::path& file() const { return m_file; } + // A script's windows belong to its run ("script/"; '/' never occurs in a plugin key) and close when it ends; + // a plugin's run_python leaves them to the plugin, which closes them when it unloads. + bool owns_ui() const; + std::string ui_owner() const; + + // orca.host.tools from any thread of the run, called without the GIL. Throws std::runtime_error once the run + // has ended; a bridge's ToolCallError passes through. + nlohmann::json call_tool(const std::string& tool, const nlohmann::json& args); + bool has_tools() const; + bool tools_closed() const; + // Refuses new calls, then waits for the calls already inside the bridge, which holds the run's ToolContext. + void close_tools(); + + // A thread the run starts is counted from the moment the starting thread asks for it, before the OS thread + // exists, so the run never misses one started late. `waited`: the run waits for it before it ends. False once + // the run's admission has closed. + bool thread_starting(bool waited); + void thread_start_failed(bool waited); + void thread_started(unsigned long ident, bool waited); + void thread_ended(unsigned long ident); + + // A window callback of the run, while it runs. False once the run's admission has closed: it does nothing. + bool callback_entering(); + void callback_left(); + + // A task the run submitted to a pool, from submit() until its work item has run or was cancelled. False once + // the run's admission has closed. + bool task_submitted(); + void task_done(); + // The pool worker running one of the run's tasks is an interrupt target for that call. + void task_running(unsigned long ident); + void task_finished(unsigned long ident); + + // Closes admission when nothing the run waits for is left: no waited thread pending or alive, no callback + // running, no task outstanding. Returns whether admission is closed. + bool close_admission_if_quiet(); + void close_admission(); + bool admission_closed() const; + + // Calls `fn` for every interrupt target of the run (its live threads and the workers running its tasks), under + // the mutex, so a target can't end, and its ident be reused, while `fn` aims at it. + void for_each_interrupt_target(const std::function& fn) const; + + // Set at the run's first stop or time-out: its tasks that a pool has not started yet don't run. + bool stopped() const { return m_stopped.load(); } + void mark_stopped() { m_stopped.store(true); } + + // Set when the run's UI is torn down: nothing more opens, and its callbacks do nothing. + bool ui_closed() const { return m_ui_closed.load(); } + void mark_ui_closed() { m_ui_closed.store(true); } + +private: + const std::uint64_t m_id; + const std::string m_identity; + const boost::filesystem::path m_file; + + mutable std::mutex m_mutex; + std::condition_variable m_calls_cv; + ToolBridge* m_bridge = nullptr; + bool m_tools_closed = false; + int m_calls_in_flight = 0; + + bool m_admission_closed = false; + int m_waited_pending = 0; + std::map m_live_threads; // ident -> waited + int m_callbacks_active = 0; + int m_tasks_outstanding = 0; + std::multiset m_task_targets; + + std::atomic m_stopped{false}; + std::atomic m_ui_closed{false}; +}; + +// The run bound to the calling thread, and what the thread does for it; `run` is null outside a run. +struct PythonRunBinding +{ + std::shared_ptr run; + PythonRunThread kind = PythonRunThread::Main; +}; +const PythonRunBinding& current_python_run(); + +// Binds `run` to the calling thread for the scope's lifetime, restoring the previous binding after. +class ScopedPythonRun +{ +public: + ScopedPythonRun(std::shared_ptr run, PythonRunThread kind); + ~ScopedPythonRun(); + ScopedPythonRun(const ScopedPythonRun&) = delete; + ScopedPythonRun& operator=(const ScopedPythonRun&) = delete; + +private: + PythonRunBinding m_previous; +}; + +} // namespace Slic3r diff --git a/src/slic3r/plugin/PythonScriptRunner.cpp b/src/slic3r/plugin/PythonScriptRunner.cpp index 85fafec4c2..e321cf21da 100644 --- a/src/slic3r/plugin/PythonScriptRunner.cpp +++ b/src/slic3r/plugin/PythonScriptRunner.cpp @@ -2,13 +2,24 @@ #include "PluginAuditManager.hpp" #include "PluginJsonPy.hpp" +#include "PluginLoader.hpp" #include "PythonInterpreter.hpp" +#include "PythonRunScope.hpp" +#include "host/PluginHostTools.hpp" +#include "host/PluginHostUi.hpp" +#include +#include +#include +#include + +#include #include #include #include #include #include +#include #include @@ -19,12 +30,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include namespace Slic3r { @@ -33,12 +46,15 @@ using nlohmann::json; namespace { -// The module that captures a run's output and holds the exception that interrupts it. Installed once, -// over whatever sys.stdout and sys.stderr are then (the stderr tee to the Python log): writes from a -// thread that has a capture go to it, all others pass through. +// The module that gives each run its own Python world inside the one interpreter, installed once. It captures a +// run's output, over whatever sys.stdout and sys.stderr are then (the stderr tee to the Python log): writes from a +// thread bound to a run that has a capture go to it, all others pass through. It routes the interpreter's own +// __main__ module and sys.argv to the bound run's, and serves a file run's imports from the script's folder. Runs +// overlap (an agent's beside a person's), so every piece is keyed by the run bound to the calling thread, read +// through _run_id(), which the runner injects before the source runs, with _plugin_uses() and _plugin_importing(). constexpr const char* kCaptureModule = "_orca_run_capture"; constexpr const char* kCaptureSource = R"CAPTURE( -import sys, threading +import atexit, concurrent.futures.thread, importlib.machinery, os, re, sys, threading, tomllib, traceback, types, weakref class RunInterrupted(BaseException): """Raised in a script's code when its run is cancelled or out of time.""" @@ -57,7 +73,7 @@ class _RunStream: def __init__(self, original): self._original = original def write(self, s): - capture = _captures.get(threading.get_ident()) + capture = _captures.get(_run_id()) if capture is None: if self._original is not None: return self._original.write(s) @@ -83,11 +99,11 @@ class _RunStream: def __getattr__(self, name): return getattr(self._original, name) -def begin(ident): - _captures[ident] = _Capture() +def begin(run_id): + _captures[run_id] = _Capture() -def end(ident): - capture = _captures.pop(ident, None) +def end(run_id): + capture = _captures.pop(run_id, None) if capture is None: return "" text = "".join(capture.parts) @@ -97,6 +113,349 @@ def end(ident): sys.stdout = _RunStream(sys.stdout) sys.stderr = _RunStream(sys.stderr) + +# Each run's __main__ module and sys.argv. The interpreter's own __main__ and the sys module get a ModuleType +# subclass whose attribute access goes to the bound run's, so typing.get_type_hints, dataclasses and pickle find a +# script's globals, and argparse its argv, while code outside runs sees the app's. C code that reads the module's +# dict directly (PyModule_GetDict, PySys_GetObject) sees the app's. The routing methods take what they use as +# defaults, so they keep working while the interpreter finalizes and this module's globals are cleared. +_app_main = sys.modules["__main__"] +_app_argv = sys.argv +_mains = {} +_argvs = {} + +class _MainRouter(types.ModuleType): + def __getattribute__(self, name, _get=types.ModuleType.__getattribute__, _mains=_mains, _rid=_run_id): + module = _mains.get(_rid()) + return _get(self, name) if module is None else getattr(module, name) + def __setattr__(self, name, value, _set=types.ModuleType.__setattr__, _mains=_mains, _rid=_run_id): + module = _mains.get(_rid()) + if module is None: + _set(self, name, value) + else: + setattr(module, name, value) + def __delattr__(self, name, _del=types.ModuleType.__delattr__, _mains=_mains, _rid=_run_id): + module = _mains.get(_rid()) + if module is None: + _del(self, name) + else: + delattr(module, name) + +class _SysRouter(types.ModuleType): + # Only argv is routed: every other attribute read on sys costs one Python call more than before. + def __getattribute__(self, name, _get=types.ModuleType.__getattribute__, _argvs=_argvs, _rid=_run_id): + if name == "argv": + argv = _argvs.get(_rid()) + if argv is not None: + return argv + return _get(self, name) + def __setattr__(self, name, value, _set=types.ModuleType.__setattr__, _argvs=_argvs, _rid=_run_id): + if name == "argv": + run_id = _rid() + if run_id in _argvs: + _argvs[run_id] = value + return + _set(self, name, value) + +def _install_routers(): + # Again at each run's start: a script may have put a plain class back. + if type(_app_main) is not _MainRouter: + types.ModuleType.__setattr__(_app_main, "__class__", _MainRouter) + if type(sys) is not _SysRouter: + types.ModuleType.__setattr__(sys, "__class__", _SysRouter) + +# A file run's imports from its script's folder, as sys.path[0] serves them under `python file.py`, without changing +# sys.path, which plugins share. The finder serves only threads bound to an active file run, from the folder and from +# the packages it served there (namespace packages included), never a submodule of a package found elsewhere, even one +# installed below the folder. Source is compiled afresh each run, never from or to a cached .pyc, so an edit shows on +# the next run whatever the file's timestamp; a sourceless .pyc and extension modules load as Python loads them. What +# it found for a folder is evicted when the last run from that folder ends, each module only while sys.modules still +# holds the module it found (its spec), and never an extension module, which can't be loaded twice, or one a plugin's +# load recorded as its own. +class _SourceLoader(importlib.machinery.SourceFileLoader): + def get_code(self, fullname): + path = self.get_filename(fullname) + return self.source_to_code(self.get_data(path), path) + +_LOADERS = ((importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), + (_SourceLoader, importlib.machinery.SOURCE_SUFFIXES), + (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES)) + +_run_folders = {} # run id -> (folder key, folder path) +_folder_runs = {} # folder key -> active file runs from it +_folder_specs = {} # folder key -> {module name: the spec the finder found} +_pending = set() # folders whose teardown waits for a later run's entry + +def _key(path): + return os.path.normcase(os.path.abspath(path)) + +def _inside(path, key): + entry = _key(path) + return entry == key or entry.startswith(key.rstrip(os.sep) + os.sep) + +class _FolderFinder: + @staticmethod + def find_spec(name, path=None, target=None): + folder = _run_folders.get(_run_id()) + if folder is None: + return None + key, folder_path = folder + if path is None: + if "." in name: + return None + entries = [folder_path] + else: + parent = name.rpartition(".")[0] + served = _folder_specs.get(key, {}).get(parent) + if served is None or getattr(sys.modules.get(parent), "__spec__", None) is not served: + return None + entries = [entry for entry in path if isinstance(entry, str) and _inside(entry, key)] + for entry in entries: + spec = importlib.machinery.FileFinder(entry, *_LOADERS).find_spec(name, target) + if spec is not None: + _folder_specs.setdefault(key, {})[name] = spec + return spec + return None + + @staticmethod + def invalidate_caches(): + pass + +# After the built-in and frozen importers, as sys.path[0] can't shadow those either. +sys.meta_path.insert(next((i for i, finder in enumerate(sys.meta_path) if finder is importlib.machinery.PathFinder), + len(sys.meta_path)), _FolderFinder) + +# Pools and atexit belong to the code that made them. _origin() names whose own code a frame is, skipping +# concurrent.futures and this module: a run's __main__ code ("run"), a module the finder served for a folder +# ("folder"; shared by the runs from that folder, so it ends with the folder's teardown), or anything else (None: a +# library's or a plugin's, left alone). +_this_globals = globals() + +def _origin(frame): + while frame is not None and (frame.f_globals is _this_globals + or str(frame.f_globals.get("__name__", "")).startswith("concurrent.futures")): + frame = frame.f_back + if frame is None: + return None + run_id = _run_id() + module = _mains.get(run_id) + if module is not None and frame.f_globals is module.__dict__: + return ("run", run_id) + spec = frame.f_globals.get("__spec__") + if spec is not None: + for key, specs in _folder_specs.items(): + for name, found in specs.items(): + if found is spec: + return ("folder", key, name) + return None + +# A pool's work belongs to the run that submitted it: each work item created from a thread of a run (submit creates +# exactly one per task it accepts) gets a tag of that run, which counts it on the run, and the C++ wrapper of +# _WorkItem.run runs the item inside that run. A future completed without its item running (cancelled, or failed by a +# broken pool) is uncounted by its callback; the tag uncounts only what it counted, and once, whichever of the two +# comes first. A submit that raises after creating its item gave the caller no future, though the item may be queued +# with no worker to run it: it is cancelled, so it never runs and is uncounted. The callback and that hand-off are in +# place before the count, so no count is ever left without them. +_pools = weakref.WeakSet() +_original_pool_init = concurrent.futures.thread.ThreadPoolExecutor.__init__ +_original_submit = concurrent.futures.thread.ThreadPoolExecutor.submit +_original_item_init = concurrent.futures.thread._WorkItem.__init__ +_submitting = threading.local() + +def _pool_init(self, *args, **kwargs): + _original_pool_init(self, *args, **kwargs) + self._orca_origin = _origin(sys._getframe(1)) + _pools.add(self) + +def _submit(self, fn, /, *args, **kwargs): + _submitting.item = None + try: + return _original_submit(self, fn, *args, **kwargs) + except BaseException: + item = getattr(_submitting, "item", None) + if item is not None: + item.future.cancel() + raise + finally: + _submitting.item = None + +def _item_init(self, future, fn, args, kwargs): + _original_item_init(self, future, fn, args, kwargs) + tag = _item_tag() + if tag is None: + return + self._orca_run = tag + future.add_done_callback(lambda done, tag=tag: _claim(tag) and _task_done(tag)) + _submitting.item = self + if not _count(tag): + raise RuntimeError("cannot schedule new futures: the script's run has ended") + +concurrent.futures.thread.ThreadPoolExecutor.__init__ = _pool_init +concurrent.futures.thread.ThreadPoolExecutor.submit = _submit +concurrent.futures.thread._WorkItem.__init__ = _item_init + +def _shut_down(pools): + # Each pool stays listed until its shutdown returns, so an interrupt only delays the rest. A pool already shut down + # is shut down again: an interrupt may have cut its shutdown after setting _shutdown and before waking its workers, + # and another wake-up costs nothing. + while pools: + try: + pools[-1].shutdown(wait=False) + except Exception: + traceback.print_exc() + pools.pop() + +def shutdown_own_pools(run_id): + _shut_down([pool for pool in list(_pools) if getattr(pool, "_orca_origin", None) == ("run", run_id)]) + +_original_register = atexit.register +_original_unregister = atexit.unregister +_run_exits = {} # run id -> [(func, args, kwargs)] +_folder_exits = {} # folder key -> [(func, args, kwargs, name of the module that registered it)] + +def _register(func, *args, **kwargs): + origin = _origin(sys._getframe(1)) + if origin is None: + return _original_register(func, *args, **kwargs) + if origin[0] == "run": + _run_exits.setdefault(origin[1], []).append((func, args, kwargs)) + else: + _folder_exits.setdefault(origin[1], []).append((func, args, kwargs, origin[2])) + return func + +def _unregister(func): + # Within the caller's own registrations, filed as register filed them: another run's, a folder's and the process's + # stay. + origin = _origin(sys._getframe(1)) + if origin is None: + return _original_unregister(func) + exits = (_run_exits if origin[0] == "run" else _folder_exits).get(origin[1], []) + exits[:] = [entry for entry in exits if entry[0] != func] + +atexit.register = _register +atexit.unregister = _unregister + +def call_exits(exits): + """Last registered first, each on its own, as Python's exit runs them. Each is taken off the list before it runs, + so an interrupt cuts only the one it lands in and the runner resumes the rest.""" + while exits: + func, args, kwargs = exits.pop()[:3] + try: + func(*args, **kwargs) + except RunInterrupted: + pass + except BaseException: + traceback.print_exc() + +def take_exits(run_id): + """Host bookkeeping: the run's atexit functions, for call_exits(). Taken once, as Python's exit takes them, so one + registered while they run is not called.""" + return _run_exits.pop(run_id, []) + +# A folder's teardown, in two steps. _take_folder is host bookkeeping, which the runner calls where no interrupt reaches +# and which runs none of the script's code: it takes everything the folder holds, evicts its modules and lists the +# pools they made, so a run that enters the folder while the second step runs (that step's code may let it in) imports +# its helpers afresh and keeps them, and their pools. A module that stays (a plugin's, an extension, one replaced in +# sys.modules) has its atexit functions handed to the process's exit there. teardown() then ends the evicted modules as +# Python ends a program's: their atexit functions, their globals cleared (so what they hold, cycles included, +# finalizes here, under the run and its watcher, while their pools still work), and their pools. Each piece stays in +# what was taken until it is done, so the runner resumes teardown() after an interrupt and only the piece the +# interrupt lands in is cut short. +class _Taken: + __slots__ = ("exits", "modules", "pools") + +def _take_folder(key): + _pending.discard(key) + specs = _folder_specs.pop(key, {}) + exits = _folder_exits.pop(key, []) + taken = _Taken() + taken.modules = {} + for name, spec in specs.items(): + module = sys.modules.get(name) + if (module is not None and getattr(module, "__spec__", None) is spec + and not isinstance(spec.loader, importlib.machinery.ExtensionFileLoader) and not _plugin_uses(name)): + del sys.modules[name] + taken.modules[name] = module + for func, args, kwargs, name in exits: + if name not in taken.modules: + _original_register(func, *args, **kwargs) + taken.exits = [entry for entry in exits if entry[3] in taken.modules] + taken.pools = [pool for pool in list(_pools) if (getattr(pool, "_orca_origin", None) or ("",))[0] == "folder" + and pool._orca_origin[1] == key and pool._orca_origin[2] in taken.modules] + return taken + +def teardown(taken): + call_exits(taken.exits) + while taken.modules: + name = next(iter(taken.modules)) + taken.modules[name].__dict__.clear() + del taken.modules[name] + _shut_down(taken.pools) + +def enter(run_id, path): + """Host bookkeeping: the run's __main__ dict, and what a teardown an earlier run left pending took, for teardown() + before this run's code, or None. `path` is the script's file, or None for code sent as text.""" + _install_routers() + module = types.ModuleType("__main__") + taken = None + if path is None: + argv = list(_app_argv) + else: + module.__file__ = path + argv = [path] + folder_path = os.path.dirname(os.path.abspath(path)) + key = _key(folder_path) + _run_folders[run_id] = (key, folder_path) + _folder_runs[key] = _folder_runs.get(key, 0) + 1 + if _folder_runs[key] == 1 and key in _pending and not _plugin_importing(): + taken = _take_folder(key) + _mains[run_id] = module + _argvs[run_id] = argv + return module.__dict__, taken + +def release(run_id): + """Host bookkeeping: the run stops using its folder. When it was the folder's last run, what the folder's teardown + took, for teardown(); None when another run still uses the folder, or when a plugin's import in progress leaves the + teardown pending for a later run's entry.""" + folder = _run_folders.pop(run_id, None) + if folder is None: + return None + key = folder[0] + runs = _folder_runs.get(key, 1) - 1 + if runs > 0: + _folder_runs[key] = runs + return None + _folder_runs.pop(key, None) + _pending.add(key) + return None if _plugin_importing() else _take_folder(key) + +# A file run's PEP 723 dependencies, found with the PEP's reference expression and read with tomllib, so quoted commas, +# multi-line arrays and comments read as TOML says. Windows line ends would hide the block from the expression. +_PEP723 = re.compile(r"(?m)^# /// (?P[a-zA-Z0-9-]+)$\s(?P(^#(| .*)$\s)+)^# ///$") + +def script_dependencies(source): + """The `dependencies` of the script's PEP 723 block; none without one. ValueError for a malformed block.""" + source = source.lstrip("").replace("\r\n", "\n").replace("\r", "\n") + blocks = [match for match in _PEP723.finditer(source) if match.group("type") == "script"] + if not blocks: + return [] + if len(blocks) > 1: + raise ValueError("the script has more than one `# /// script` block") + content = "".join(line[2:] if line.startswith("# ") else line[1:] + for line in blocks[0].group("content").splitlines(keepends=True)) + dependencies = tomllib.loads(content).get("dependencies", []) + if not isinstance(dependencies, list) or not all(isinstance(item, str) for item in dependencies): + raise ValueError("`dependencies` is not a list of strings") + return dependencies + +def leave(run_id): + """Host bookkeeping: the run's routes go, and the app's __main__ comes back if the run replaced it. Returns what + they held (its __main__, its argv, what replaced the app's __main__, atexit functions registered while its own + ran), for the runner to drop where a finalizer of it can still be stopped.""" + held = (_mains.pop(run_id, None), _argvs.pop(run_id, None), sys.modules.get("__main__"), _run_exits.pop(run_id, None)) + if held[2] is not _app_main: + sys.modules["__main__"] = _app_main + return held )CAPTURE"; // The capture module's functions and interrupt, installed on first use and held from then on, so a script @@ -104,27 +463,194 @@ sys.stderr = _RunStream(sys.stderr) // references are kept for the process: dropping them after the interpreter finalizes would crash. GIL held. struct Capture { - PyObject* begin = nullptr; - PyObject* end = nullptr; - PyObject* interrupt = nullptr; + PyObject* begin = nullptr; + PyObject* end = nullptr; + PyObject* interrupt = nullptr; + PyObject* enter = nullptr; + PyObject* release = nullptr; + PyObject* teardown = nullptr; + PyObject* leave = nullptr; + PyObject* shutdown_own_pools = nullptr; + PyObject* take_exits = nullptr; + PyObject* call_exits = nullptr; + PyObject* dependencies = nullptr; }; +// A work item's tag (item._orca_run, a capsule that owns it): the run it belongs to and its task's accounting there, +// in plain C++, so nothing between taking the count and recording it, or between testing the claim and setting it, can +// raise or run Python code. +struct ItemTag +{ + std::shared_ptr run; + bool counted = false; + bool claimed = false; +}; + +py::capsule item_tag(std::shared_ptr run) +{ + return py::capsule(new ItemTag{std::move(run)}, [](void* tag) { delete static_cast(tag); }); +} + +ItemTag& tag_of(const py::handle& capsule) { return *static_cast(py::reinterpret_borrow(capsule).get_pointer()); } + +// Counts the item's task on its run, unless the run's admission has closed. GIL held. +bool count_item(ItemTag& tag) +{ + tag.counted = tag.run->task_submitted(); + return tag.counted; +} + +// The first of the run's _WorkItem.run wrapper and its future's callback to take a counted item uncounts it. GIL held. +bool claim_item(ItemTag& tag) +{ + if (!tag.counted || tag.claimed) + return false; + tag.claimed = true; + return true; +} + +// concurrent.futures.thread._WorkItem.run, for an item a thread of a run created: the whole item (the task's +// callable, the future's completion and so the done callbacks the pool calls from there) runs inside that run, on a +// worker that is the run's interrupt target meanwhile. Every BaseException stops here, so neither Stop nor a +// SystemExit in a callback ends the worker, which pools share across runs. +py::object run_work_item(const py::object& original, const py::handle& interrupt, const py::object& item) +{ + const py::object capsule = py::getattr(item, "_orca_run", py::none()); + if (capsule.is_none()) + return original(item); + ItemTag& tag = tag_of(capsule); + std::shared_ptr run = tag.run; + if (!claim_item(tag)) { + // Taken by its future's callback, so its future is done without it: the stock run marks a cancelled one + // notified, which wait() and as_completed() need, and raises for any other (a future completed by hand), + // which must not end the worker either. + try { + original(item); + } catch (py::error_already_set&) { + } + return py::none(); + } + { + ScopedPythonRun bound(run, PythonRunThread::Started); + ScopedPluginAuditContext audit(run->identity()); + const unsigned long ident = PyThread_get_thread_ident(); + run->task_running(ident); + try { + if (run->stopped() || run->admission_closed()) { + // A stopped or ended run's queued task doesn't run. + py::object future = item.attr("future"); + if (future.attr("set_running_or_notify_cancel")().cast()) + future.attr("set_exception")(py::module_::import("builtins").attr("RuntimeError")("The script's run has ended")); + } else + original(item); + } catch (py::error_already_set& err) { + if (!err.matches(interrupt)) { + try { + py::module_::import("traceback").attr("print_exception")(err.type(), err.value(), err.trace()); + } catch (py::error_already_set&) { + } + } + } + run->task_finished(ident); + PyThreadState_SetAsyncExc(ident, nullptr); + PyErr_Clear(); + } + run->task_done(); + return py::none(); +} + const Capture& capture_functions() { static Capture capture; + if (capture.begin != nullptr) + return capture; + // Installed once even when the first runs start together: the source's imports release the GIL, so without the + // lock a second run would install another module, with routing tables of its own. The lock is taken without the + // GIL, so the installing run can take the GIL back. + static std::mutex install_mutex; + std::unique_lock install_lock(install_mutex, std::defer_lock); + { + py::gil_scoped_release release; + install_lock.lock(); + } if (capture.begin != nullptr) return capture; py::module_ module = py::reinterpret_steal(PyModule_New(kCaptureModule)); if (!module) throw py::error_already_set(); + module.attr("_run_id") = py::cpp_function([] { + const PythonRunBinding& binding = current_python_run(); + return binding.run ? binding.run->id() : std::uint64_t(0); + }); + module.attr("_plugin_uses") = py::cpp_function([](const std::string& name) { return PythonInterpreter::instance().plugin_uses_module(name); }); + module.attr("_plugin_importing") = py::cpp_function([] { return PythonInterpreter::instance().plugin_import_in_progress(); }); + module.attr("_item_tag") = py::cpp_function([]() -> py::object { + const PythonRunBinding& binding = current_python_run(); + return binding.run ? py::object(item_tag(binding.run)) : py::object(py::none()); + }); + module.attr("_count") = py::cpp_function([](const py::handle& capsule) { return count_item(tag_of(capsule)); }); + module.attr("_claim") = py::cpp_function([](const py::handle& capsule) { return claim_item(tag_of(capsule)); }); + module.attr("_task_done") = py::cpp_function([](const py::handle& capsule) { tag_of(capsule).run->task_done(); }); py::exec(kCaptureSource, module.attr("__dict__")); py::module_::import("sys").attr("modules")[kCaptureModule] = module; - capture.begin = py::object(module.attr("begin")).release().ptr(); - capture.end = py::object(module.attr("end")).release().ptr(); - capture.interrupt = py::object(module.attr("RunInterrupted")).release().ptr(); + const auto hold = [&module](const char* name) { return py::object(module.attr(name)).release().ptr(); }; + capture.end = hold("end"); + capture.interrupt = hold("RunInterrupted"); + capture.enter = hold("enter"); + capture.release = hold("release"); + capture.teardown = hold("teardown"); + capture.leave = hold("leave"); + capture.shutdown_own_pools = hold("shutdown_own_pools"); + capture.take_exits = hold("take_exits"); + capture.call_exits = hold("call_exits"); + capture.dependencies = hold("script_dependencies"); + { + py::object item_class = py::module_::import("concurrent.futures.thread").attr("_WorkItem"); + py::object original = item_class.attr("run"); + py::handle interrupt = capture.interrupt; + item_class.attr("run") = py::cpp_function([original, interrupt](const py::object& item) { return run_work_item(original, interrupt, item); }, + py::name("run"), py::is_method(item_class)); + } + // Last: a set `begin` is what tells a later caller, under the GIL, that the rest is there. + capture.begin = hold("begin"); return capture; } +// A UTF-8 path as a native one: wide on Windows, where boost's narrow conversion uses the ANSI code page. +boost::filesystem::path utf8_path(const std::string& utf8) +{ +#ifdef _WIN32 + return boost::filesystem::path(boost::nowide::widen(utf8)); +#else + return boost::filesystem::path(utf8); +#endif +} + +// A file run names an existing file; any other name (, a bare traceback name) is code sent as text. +boost::filesystem::path run_file(const std::string& filename) +{ + if (filename.empty() || filename.front() == '<') + return {}; + boost::system::error_code ec; + boost::filesystem::path path = utf8_path(filename); + return boost::filesystem::is_regular_file(path, ec) ? path : boost::filesystem::path(); +} + +std::atomic g_next_run_id{1}; + +std::mutex g_installer_mutex; +PythonDependencyInstaller g_installer; + +bool install_dependencies(const std::vector& packages, std::string& error) +{ + PythonDependencyInstaller installer; + { + std::lock_guard lock(g_installer_mutex); + installer = g_installer; + } + return installer ? installer(packages, error) : plugin_loader::install_packages(packages, error); +} + // A run's `result` as JSON, refusing what JSON can't hold rather than stringifying it. GIL held. json strict_json(const py::handle& value, int depth = 0) { @@ -167,14 +693,19 @@ json strict_json(const py::handle& value, int depth = 0) throw std::invalid_argument("result holds a " + std::string(Py_TYPE(value.ptr())->tp_name) + ", which is not JSON"); } -// Interrupts the run's thread when it is cancelled or out of time, until stopped. +// Interrupts the run when it is cancelled or out of time, until stopped. What it interrupts depends on the run's +// phase: in Body (the code runs) and Exit (atexit functions, the namespace's finalizers, the folder's teardown) the +// run's thread and its interrupt targets; in Threads (the run's thread waits in C++ for the work it started) the +// targets only; in Drain (host bookkeeping) nothing, though it still records a stop or time-out. The phase is set, +// and read before an interrupt, under the GIL, so no interrupt lands after the phase that allowed it. class Watcher { public: enum class Reason { None, Cancelled, TimedOut }; + enum class Phase { Body, Threads, Exit, Drain }; - Watcher(const PythonRunRequest& request, unsigned long thread_ident, PyObject* interrupt) - : m_request(request), m_ident(thread_ident), m_interrupt(interrupt), m_thread([this] { run(); }) + Watcher(const PythonRunRequest& request, unsigned long thread_ident, PyObject* interrupt, std::shared_ptr scope) + : m_request(request), m_ident(thread_ident), m_interrupt(interrupt), m_scope(std::move(scope)), m_thread([this] { run(); }) {} ~Watcher() { stop(); } @@ -190,6 +721,16 @@ public: m_thread.join(); } Reason reason() const { return m_reason.load(); } + // With the GIL held. + void set_phase(Phase phase) { m_phase = phase; } + // Time since the run's first stop or time-out, or nullopt before it. + std::optional since_stop() const + { + const long long at = m_stopped_at.load(); + if (at < 0) + return std::nullopt; + return std::chrono::steady_clock::now().time_since_epoch() - std::chrono::steady_clock::duration(at); + } private: void run() @@ -201,32 +742,54 @@ private: Reason why = Reason::None; if (m_request.cancelled && m_request.cancelled()) why = Reason::Cancelled; - else if (std::chrono::steady_clock::now() - start >= m_request.budget) + else if (m_request.budget.count() > 0 && std::chrono::steady_clock::now() - start >= m_request.budget) why = Reason::TimedOut; - const auto now = std::chrono::steady_clock::now(); - if (why == Reason::None || now - last < std::chrono::seconds(1)) + if (why == Reason::None) continue; // The first reason sticks: a run cancelled after its budget ran out still timed out. Reason expected = Reason::None; - m_reason.compare_exchange_strong(expected, why); + if (m_reason.compare_exchange_strong(expected, why)) { + m_stopped_at = std::chrono::steady_clock::now().time_since_epoch().count(); + m_scope->mark_stopped(); + lock.unlock(); + if (m_request.stop_calls) + m_request.stop_calls(); + // A stopped script opens nothing more, and what it has open closes now, which ends a modal loop it + // waits in. + if (m_scope->owns_ui()) { + m_scope->mark_ui_closed(); + PluginHostUi::close_windows_for_plugin(m_scope->ui_owner()); + } + lock.lock(); + } + const auto now = std::chrono::steady_clock::now(); + if (now - last < std::chrono::seconds(1)) + continue; last = now; lock.unlock(); // The run holds an interpreter lease until this watcher is stopped, so the interpreter is up. - const PyGILState_STATE gil = PyGILState_Ensure(); - PyThreadState_SetAsyncExc(m_ident, m_interrupt); + const PyGILState_STATE gil = PyGILState_Ensure(); + const Phase phase = m_phase.load(); + if (phase == Phase::Body || phase == Phase::Exit) + PyThreadState_SetAsyncExc(m_ident, m_interrupt); + if (phase != Phase::Drain) + m_scope->for_each_interrupt_target([this](unsigned long ident) { PyThreadState_SetAsyncExc(ident, m_interrupt); }); PyGILState_Release(gil); lock.lock(); } } - const PythonRunRequest& m_request; - const unsigned long m_ident; - PyObject* m_interrupt; - std::mutex m_mutex; - std::condition_variable m_cv; - bool m_stop = false; - std::atomic m_reason{Reason::None}; - std::thread m_thread; + const PythonRunRequest& m_request; + const unsigned long m_ident; + PyObject* m_interrupt; + std::shared_ptr m_scope; + std::mutex m_mutex; + std::condition_variable m_cv; + bool m_stop = false; + std::atomic m_reason{Reason::None}; + std::atomic m_phase{Phase::Body}; // set and read under the GIL + std::atomic m_stopped_at{-1}; + std::thread m_thread; }; std::string format_traceback(py::error_already_set& err) @@ -257,6 +820,7 @@ std::string exception_line(py::error_already_set& err) PythonRunOutcome run_python_code(const PythonRunRequest& request) { PythonRunOutcome outcome; + std::string result_note; if (!PythonInterpreter::instance().is_initialized()) { outcome.status = "unavailable"; outcome.message = "Python is not available in this OrcaSlicer"; @@ -269,6 +833,11 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) return outcome; } + const boost::filesystem::path file = run_file(request.filename); + auto scope = std::make_shared(g_next_run_id++, request.identity, file, current_tool_bridge()); + ScopedPythonRun bound(scope, PythonRunThread::Main); + const std::uint64_t run_id = scope->id(); + py::gil_scoped_acquire gil; const unsigned long ident = PyThread_get_thread_ident(); const Capture* capture = nullptr; @@ -281,22 +850,102 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) } py::handle interrupt(capture->interrupt); + // A file run's PEP 723 dependencies are installed before its code, as a plugin's are; a block that can't be read + // or an install that fails stops the run there. The install runs without the GIL, bounded by uv's own limit. + if (!file.empty()) { + std::vector packages; + try { + packages = py::handle(capture->dependencies)(request.code).cast>(); + } catch (py::error_already_set& err) { + outcome.status = "raised"; + outcome.message = "Cannot read the script's PEP 723 block: " + exception_line(err); + return outcome; + } + if (!packages.empty()) { + std::string error; + bool installed = false; + { + py::gil_scoped_release release; + installed = install_dependencies(packages, error); + } + if (!installed) { + outcome.status = "raised"; + outcome.message = "Cannot install the script's dependencies: " + error; + return outcome; + } + } + } + // Everything below that can run the script's Python (its body, a result's or exception's own methods, // finalizers of what its namespace and traceback hold) runs inside the script's audit scope and under the // watcher, so none of it escapes the identity, the budget or a cancel. Watcher::Reason reason = Watcher::Reason::None; { ScopedPluginAuditContext audit(request.identity); - Watcher watcher(request, ident, interrupt.ptr()); + Watcher watcher(request, ident, interrupt.ptr(), scope); std::optional failure; py::dict ns; bool executed = false; + bool entered = false; + // The body is the run's main program, which `python file.py` runs on a non-daemon thread, so the threads it + // starts are waited for unless they say otherwise. The app runs it on a thread Python didn't start, which + // Python sees as a daemon dummy thread, so the body runs with that flag cleared. Thread.daemon refuses a + // started thread, hence _daemonic. + py::object main_thread; + bool was_daemon = false; + // Host bookkeeping that an interrupt must not cut in half (a folder's use count, what its teardown takes) runs + // in the Drain phase, with an interrupt already sent dropped. The caller sets the phase that follows. + const auto uninterrupted = [&](const auto& step) { + watcher.set_phase(Watcher::Phase::Drain); + PyThreadState_SetAsyncExc(ident, nullptr); + PyErr_Clear(); + step(); + }; + const auto quietly = [](const auto& step) { + try { + step(); + } catch (py::error_already_set&) { + // Interrupted, or the script's own cleanup failed: what is left of it is dropped. + } + }; + // A step of the script's cleanup, resumed after the run's interrupt until it ends: it takes each piece off what + // it works through as the piece starts (an atexit function) or once it is done (a pool, a module's globals), so + // a resume repeats nothing that ran and an interrupt cuts at most the piece it lands in. Any other error ends + // the step, as quietly() does. + const auto to_end = [&](const auto& step) { + for (;;) { + try { + step(); + return; + } catch (py::error_already_set& err) { + if (!err.matches(interrupt)) + return; + } + } + }; try { - py::handle(capture->begin)(ident); + py::object taken; + uninterrupted([&] { + main_thread = py::module_::import("threading").attr("current_thread")(); + was_daemon = main_thread.attr("daemon").cast(); + if (was_daemon) + main_thread.attr("_daemonic") = false; + py::handle(capture->begin)(run_id); + // The run's own __main__: a file run also gets __file__, sys.argv and imports from its folder. + const py::tuple entry = py::handle(capture->enter)(run_id, file.empty() ? py::object(py::none()) : py::str(request.filename)) + .cast(); + ns = entry[0].cast(); + taken = entry[1]; + entered = true; + }); + watcher.set_phase(Watcher::Phase::Body); + // A teardown an earlier run from this folder left pending runs before this run's code. + if (taken && !taken.is_none()) + to_end([&] { py::handle(capture->teardown)(taken); }); + taken = py::object(); py::module_ builtins = py::module_::import("builtins"); - ns["__name__"] = "__orca_script__"; ns["__builtins__"] = builtins; - ns["args"] = json_to_py(request.args); + ns["args"] = json_to_py(request.args); // Text: a BOM a file's text kept is dropped, as Python drops it from a file. const bool bom = request.code.compare(0, 3, "\xEF\xBB\xBF") == 0; py::object code = builtins.attr("compile")(py::str(bom ? request.code.substr(3) : request.code), request.filename, "exec"); @@ -309,6 +958,8 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) outcome.status = "raised"; outcome.message = e.what(); } + if (was_daemon && PyObject_SetAttrString(main_thread.ptr(), "_daemonic", Py_True) != 0) + PyErr_Clear(); try { if (failure && failure->matches(PyExc_SystemExit)) { @@ -327,8 +978,14 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) outcome.result = strict_json(ns["result"]); outcome.status = "finished"; } catch (const std::invalid_argument& e) { - outcome.status = "raised"; - outcome.message = e.what(); + if (file.empty()) { + outcome.status = "raised"; + outcome.message = e.what(); + } else { + // A standalone script may well have a variable named result: it is no result, not a failure. + outcome.status = "finished"; + result_note = std::string("\n[result is not JSON, so it was not returned: ") + e.what() + "]\n"; + } } } else if (!failure && executed) outcome.status = "finished"; @@ -343,23 +1000,81 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) if (outcome.status.empty()) outcome.status = "interrupted"; // decided below from the watcher's reason - try { - outcome.output = py::handle(capture->end)(ident).cast(); - } catch (const std::exception&) { + // Like `python file.py`, the run ends once the work it started is done: its non-daemon threads, its window + // callbacks and the pool tasks it submitted. It waits here, without the GIL, on what it counted, never through + // Thread.join(), whose interrupted wait marks a live thread stopped. A stop interrupts that work and gives it + // 5 s; then the run stops waiting and closes its admission anyway. + watcher.set_phase(Watcher::Phase::Threads); + { + py::gil_scoped_release release; + while (!scope->close_admission_if_quiet()) { + if (const auto since = watcher.since_stop(); since && *since >= std::chrono::seconds(5)) { + scope->close_admission(); + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + } + // An interrupt the body was sent as it returned would land in the next Python this thread runs. + PyThreadState_SetAsyncExc(ident, nullptr); + PyErr_Clear(); + + // What the script left behind goes here, under its identity and the watcher, with its prints captured: its + // pools, its atexit functions, its namespace, the exception with the frames its traceback holds, its folder's + // teardown when it is the folder's last run, and what it left in its argv or in place of __main__. What each + // step works through is taken as host bookkeeping, where no interrupt reaches, and the step that runs it is + // resumed after an interrupt. + watcher.set_phase(Watcher::Phase::Exit); + to_end([&] { py::handle(capture->shutdown_own_pools)(run_id); }); + py::object exits; + quietly([&] { uninterrupted([&] { exits = py::handle(capture->take_exits)(run_id); }); }); + watcher.set_phase(Watcher::Phase::Exit); + if (exits) + to_end([&] { py::handle(capture->call_exits)(exits); }); + exits = py::object(); + // A script's windows close with it, after its atexit functions and before its globals go, waiting for the UI + // thread, so none of its callbacks runs after. + if (scope->owns_ui()) { + scope->mark_ui_closed(); + PluginHostUi::close_run_windows(scope->ui_owner()); } - // What the script left behind goes here, under its identity: its namespace, and the exception with - // the frames its traceback holds. ns.clear(); failure.reset(); + if (entered) { + py::object taken; + quietly([&] { uninterrupted([&] { taken = py::handle(capture->release)(run_id); }); }); + watcher.set_phase(Watcher::Phase::Exit); + if (taken && !taken.is_none()) + to_end([&] { py::handle(capture->teardown)(taken); }); + taken = py::object(); + py::object left; + quietly([&] { uninterrupted([&] { left = py::handle(capture->leave)(run_id); }); }); + watcher.set_phase(Watcher::Phase::Exit); + // What the run's routes held finalizes here, where its finalizers can still be stopped. + left = py::object(); + } + + // Host bookkeeping, which no interrupt reaches: the output and the tools. + watcher.set_phase(Watcher::Phase::Drain); + PyThreadState_SetAsyncExc(ident, nullptr); + PyErr_Clear(); + try { + outcome.output = py::handle(capture->end)(run_id).cast(); + } catch (const std::exception&) { + } + { + py::gil_scoped_release release; + scope->close_tools(); + } { py::gil_scoped_release release; watcher.stop(); } reason = watcher.reason(); - // An interrupt raised as the run was ending would land in the next Python this thread runs. PyThreadState_SetAsyncExc(ident, nullptr); PyErr_Clear(); } + outcome.output += result_note; // A finalizer that ran on past the budget or a cancel while the namespace was cleared swallowed the // interrupt, as Python ignores what __del__ raises: the run still did not finish in time. @@ -396,6 +1111,84 @@ bool valid_utf8(const std::string& bytes) } // namespace +namespace { + +// The threading.Thread whose bootstrap `function`, given to _thread.start_new_thread, is; None for a raw thread. +py::object thread_of(const py::handle& function) +{ + py::object thread = py::getattr(function, "__self__", py::none()); + return py::isinstance(thread, py::module_::import("threading").attr("Thread")) ? thread : py::object(py::none()); +} + +bool is_pool_worker_thread(const py::object& thread) +{ + if (thread.is_none()) + return false; + const py::object pools = py::module_::import("sys").attr("modules").attr("get")("concurrent.futures.thread"); + return !pools.is_none() && py::getattr(thread, "_target", py::none()).is(pools.attr("_worker")); +} + +} // namespace + +void set_python_dependency_installer_for_testing(PythonDependencyInstaller installer) +{ + std::lock_guard lock(g_installer_mutex); + g_installer = std::move(installer); +} + +bool python_run_is_pool_worker(const py::handle& function) { return is_pool_worker_thread(thread_of(function)); } + +bool python_run_waits_for(const py::handle& function) +{ + const py::object thread = thread_of(function); + return !thread.is_none() && !thread.attr("daemon").cast() && !is_pool_worker_thread(thread); +} + +PoolInitializerBinding python_run_bind_pool_initializer(const py::handle& function, const std::shared_ptr& run) +{ + // The worker's target is _worker(executor_reference, work_queue, initializer, initargs). + const py::object thread = thread_of(function); + if (!is_pool_worker_thread(thread)) + return PoolInitializerBinding::None; + const py::object args = py::getattr(thread, "_args", py::none()); + if (!py::isinstance(args) || py::len(args) < 4) + return PoolInitializerBinding::None; + py::list worker_args(args); + const py::object initializer = worker_args[2]; + if (initializer.is_none()) + return PoolInitializerBinding::None; + if (!run->task_submitted()) + return PoolInitializerBinding::Refused; + try { + worker_args[2] = py::cpp_function([initializer, run](const py::args& call_args) -> py::object { + ScopedPythonRun bound(run, PythonRunThread::Started); + ScopedPluginAuditContext audit(run->identity()); + struct Target + { + PythonRunScope& run; + unsigned long ident; + ~Target() + { + run.task_finished(ident); + // An interrupt sent as the initializer returned would land in the worker's next task. + PyThreadState_SetAsyncExc(ident, nullptr); + run.task_done(); + } + } target{*run, PyThread_get_thread_ident()}; + run->task_running(target.ident); + PyObject* result = PyObject_Call(initializer.ptr(), call_args.ptr(), nullptr); + if (result == nullptr) + throw py::error_already_set(); + return py::reinterpret_steal(result); + }); + py::setattr(thread, "_args", py::tuple(worker_args)); + } catch (...) { + run->task_done(); + throw; + } + return PoolInitializerBinding::Counted; +} + bool decode_python_source(const std::string& bytes, std::string& text, std::string& encoding, std::string& error) { PythonRuntimeLease lease; diff --git a/src/slic3r/plugin/PythonScriptRunner.hpp b/src/slic3r/plugin/PythonScriptRunner.hpp index fade3164aa..1353b0171d 100644 --- a/src/slic3r/plugin/PythonScriptRunner.hpp +++ b/src/slic3r/plugin/PythonScriptRunner.hpp @@ -4,10 +4,18 @@ #include #include +#include #include +#include + +namespace pybind11 { +class handle; +} namespace Slic3r { +class PythonRunScope; + // A Python script a person or an agent starts (run_python, a .py in the Run Script dialog or // --mcp-script), or a plugin's run_python: code run on the plugin interpreter without being packaged // as a plugin. @@ -22,12 +30,16 @@ struct PythonRunRequest // person's or an agent's script, which every audited access is allowed to apart from the categorical // denies, or a plugin's key, whose grants then apply. std::string identity; - // Shown in tracebacks. + // Shown in tracebacks. An existing file's path makes it a file run, which runs as `python file.py` would run + // it: `__file__` and `sys.argv` name it, and its folder serves its imports. Any other name, such as the default + // , is code sent as text. std::string filename = ""; // The run is interrupted as timed_out once it has run this long. std::chrono::milliseconds budget{std::chrono::minutes(5)}; // Polled while the code runs, from another thread; true interrupts it as cancelled. std::function cancelled; + // Called once, from another thread, at the run's first stop or time-out, to cancel its tool calls in flight. + std::function stop_calls; }; struct PythonRunOutcome @@ -37,8 +49,8 @@ struct PythonRunOutcome // The value the code left in `result`, read once when the module body returned; null when it set // none or the run did not finish. nlohmann::json result; - // What the run's own thread printed to stdout and stderr, in order. Threads the code starts print - // to the app's streams instead. + // What the run printed to stdout and stderr, in order: its own thread, the threads it starts and its window + // callbacks. std::string output; // The formatted traceback of a raised run. std::string traceback; @@ -46,15 +58,34 @@ struct PythonRunOutcome std::string message; }; -// Runs `request.code` as a module body on the calling thread and returns how it ended. Holds an -// interpreter lease and the GIL for the run, under `request.identity`'s audit scope, in a fresh -// namespace where `args` is bound and `orca` is importable. Cancellation and the budget raise an +// Runs `request.code` as the main program on the calling thread and returns how it ended. Holds an +// interpreter lease and the GIL for the run, under `request.identity`'s audit scope, in a fresh `__main__` +// module of its own where `args` is bound and `orca` is importable. Cancellation and the budget raise an // exception in the running code at its next bytecode, again every second until it ends, so code // blocked inside a C call stops once the call returns. A `result` that is not JSON (a dict with str // keys, a list, a str, a finite number, a bool or None, nested) makes the run raised; SystemExit with // code 0 or None finishes it. PythonRunOutcome run_python_code(const PythonRunRequest& request); +// Installs a file run's PEP 723 dependencies; false with `error` when that fails. plugin_loader::install_packages +// unless a test sets another; nullptr restores it. +using PythonDependencyInstaller = std::function& packages, std::string& error)>; +void set_python_dependency_installer_for_testing(PythonDependencyInstaller installer); + +// For the thread shim, with the GIL held. Whether `function`, the callable _thread.start_new_thread was given, +// starts a concurrent.futures pool's worker; and whether a run waits for the thread it starts before it ends: a +// non-daemon threading.Thread that isn't a pool worker. Python's own exit doesn't wait for a raw _thread thread. +bool python_run_is_pool_worker(const pybind11::handle& function); +bool python_run_waits_for(const pybind11::handle& function); +// For a pool worker a thread of `run` starts: the worker stays unbound, as pools are shared across runs, but the +// pool's initializer, which runs on it before any task, runs inside `run` as the task it was started for does (its +// binding, its identity, one of its interrupt targets), counted as the run's work from now until it returns, so the +// run waits for it even when that task is cancelled. Counted: the caller uncounts it with PythonRunScope::task_done() +// if the thread then fails to start. Refused: the run's admission has closed, so the worker must not start, since its +// initializer would run outside any run and identity. +enum class PoolInitializerBinding { None, Counted, Refused }; +PoolInitializerBinding python_run_bind_pool_initializer(const pybind11::handle& function, const std::shared_ptr& run); + // A .py file's bytes as UTF-8 text, decoded as Python reads a source file: by its BOM, else its PEP 263 // encoding declaration, else as UTF-8. Sets `encoding` to the codec used, which encode_python_source() takes // to save the text back. False with `error` when the bytes are not text in that encoding. diff --git a/src/slic3r/plugin/host/PluginHost.cpp b/src/slic3r/plugin/host/PluginHost.cpp index 23af8253dc..4b5d405d0e 100644 --- a/src/slic3r/plugin/host/PluginHost.cpp +++ b/src/slic3r/plugin/host/PluginHost.cpp @@ -4,6 +4,10 @@ #include #include #include +#include + +#include +#include #include #include @@ -12,13 +16,20 @@ namespace Slic3r { namespace host_bindings { -void require_plugin_caller(const char* function) +namespace { + +// A native path as UTF-8: narrowed from wide on Windows, where boost's narrow form uses the ANSI code page. +std::string path_utf8(const boost::filesystem::path& path) { - if (is_script_identity(PluginAuditManager::instance().current_plugin())) - throw std::runtime_error(std::string("orca.host.") + function + - " is for plugins; a script changes the project through orca.host.tools"); +#ifdef _WIN32 + return boost::nowide::narrow(path.wstring()); +#else + return path.string(); +#endif } +} // namespace + void register_plugin(pybind11::module_& host) { auto plugin_host = host.def_submodule("plugin", "Plugin host API"); @@ -26,14 +37,20 @@ void register_plugin(pybind11::module_& host) plugin_host.def( "storage", []() -> std::string { - require_plugin_caller("plugin.storage"); const std::string plugin_key = PluginAuditManager::instance().current_plugin(); + // A script's own folder is its storage, as a plugin's installed folder is the plugin's. + if (is_script_identity(plugin_key)) { + const PythonRunBinding& binding = current_python_run(); + if (!binding.run || binding.run->file().empty()) + throw std::runtime_error("orca.host.plugin.storage() is the folder of a script's file; code sent as text has no folder"); + return path_utf8(binding.run->file().parent_path()); + } if (plugin_key.empty()) throw std::runtime_error("plugin.storage() must be called from a plugin callback"); return PluginManager::instance().get_storage_dir(plugin_key); }, - "Return the installed folder of the current plugin."); + "Return the installed folder of the current plugin; for a script, the folder of its file."); } } // namespace host_bindings diff --git a/src/slic3r/plugin/host/PluginHostApp.cpp b/src/slic3r/plugin/host/PluginHostApp.cpp index b9695fb731..b7fb1cdad6 100644 --- a/src/slic3r/plugin/host/PluginHostApp.cpp +++ b/src/slic3r/plugin/host/PluginHostApp.cpp @@ -78,7 +78,6 @@ void require_main_thread(const char* function_name) void export_3mf_copy(GUI::Plater& plater, const std::string& path) { - host_bindings::require_plugin_caller("app.export_3mf_copy"); require_main_thread("export_3mf_copy"); if (!boost::iends_with(path, ".3mf")) throw py::value_error("export_3mf_copy() needs a path ending in .3mf"); diff --git a/src/slic3r/plugin/host/PluginHostBindings.hpp b/src/slic3r/plugin/host/PluginHostBindings.hpp index ab69c66414..f253dc451e 100644 --- a/src/slic3r/plugin/host/PluginHostBindings.hpp +++ b/src/slic3r/plugin/host/PluginHostBindings.hpp @@ -15,10 +15,4 @@ void register_slicing(pybind11::module_& host); // PluginHostSlicing.cpp void register_plugin(pybind11::module_& host); // PluginHost.cpp void register_tools(pybind11::module_& host); // PluginHostTools.cpp -// Refuses a person's or an agent's script (a script audit identity) with a RuntimeError naming -// orca.host.. The functions that change state outside the MCP tools (the staged preset update, -// bundle reload, the 3MF copy, plugin UI, plugin storage) call it first: a script reads through orca.host -// and changes the project only through orca.host.tools, with each tool's guards and undo. The -// "orca.host functions are classified" test lists which functions are which. -void require_plugin_caller(const char* function); } // namespace Slic3r::host_bindings diff --git a/src/slic3r/plugin/host/PluginHostPresets.cpp b/src/slic3r/plugin/host/PluginHostPresets.cpp index 00cde90466..d79f7b428e 100644 --- a/src/slic3r/plugin/host/PluginHostPresets.cpp +++ b/src/slic3r/plugin/host/PluginHostPresets.cpp @@ -217,7 +217,6 @@ std::string resolved_slot_preset(PresetBundle& bundle, int slot_number) void PresetTransaction::set(const std::string& key, const std::string& value) { - host_bindings::require_plugin_caller("preset.PresetTransaction.set"); if (committed) throw std::runtime_error("This preset transaction has already been committed; start a new begin_update()"); if (key.empty()) @@ -231,7 +230,6 @@ void PresetTransaction::set(const std::string& key, const std::string& value) PresetUpdateResult PresetTransaction::commit() { - host_bindings::require_plugin_caller("preset.PresetTransaction.commit"); if (committed) throw std::runtime_error("This preset transaction has already been committed; start a new begin_update()"); if (type == Preset::TYPE_INVALID) @@ -348,7 +346,6 @@ void bind_preset_target(Preset::Type type, const std::string& preset_name, Prese // Blocking form used by begin_update() and update(). PresetTransaction begin_preset_update(Preset::Type type, const std::string& preset_name) { - host_bindings::require_plugin_caller("preset.begin_update"); PresetTransaction transaction; PluginHostUi::run_on_ui_thread([&] { bind_preset_target(type, preset_name, transaction); }); return transaction; @@ -507,7 +504,6 @@ void bind_filament_target(int slot_number, const std::string& preset_name, Prese // Blocking form used by begin_update() and update(). PresetTransaction begin_filament_update(int slot_number, const std::string& preset_name) { - host_bindings::require_plugin_caller("preset.filament.begin_update"); PresetTransaction transaction; PluginHostUi::run_on_ui_thread([&] { bind_filament_target(slot_number, preset_name, transaction); }); return transaction; @@ -517,7 +513,6 @@ PresetTransaction begin_filament_update(int slot_number, const std::string& pres // begin_update()/set()/commit() path, so targeting, selection, validation and commit are shared. void update_edited_preset(Preset::Type type, const std::string& key, const std::string& value) { - host_bindings::require_plugin_caller("preset.update"); PresetTransaction transaction = begin_preset_update(type, std::string()); transaction.set(key, value); transaction.commit(); @@ -525,7 +520,6 @@ void update_edited_preset(Preset::Type type, const std::string& key, const std:: void update_filament_slot(int slot_number, const std::string& key, const std::string& value) { - host_bindings::require_plugin_caller("preset.filament.update"); PresetTransaction transaction = begin_filament_update(slot_number, std::string()); transaction.set(key, value); transaction.commit(); @@ -533,7 +527,6 @@ void update_filament_slot(int slot_number, const std::string& key, const std::st void reload_local_bundle(const std::string& bundle_id) { - host_bindings::require_plugin_caller("preset.bundles.reload_local"); bool reloaded = false; std::string error; PluginHostUi::run_on_ui_thread([&] { diff --git a/src/slic3r/plugin/host/PluginHostTools.cpp b/src/slic3r/plugin/host/PluginHostTools.cpp index 0f20f27b8d..36aa806792 100644 --- a/src/slic3r/plugin/host/PluginHostTools.cpp +++ b/src/slic3r/plugin/host/PluginHostTools.cpp @@ -4,12 +4,17 @@ #include #include +#include #include #include #include #include +#include +#include + +#include #include #include #include @@ -48,15 +53,27 @@ json call_tool(py::module_& tools, const std::string& name, const py::object& ar const json arguments = args.is_none() ? json::object() : py_to_json(args); if (!arguments.is_object()) throw py::type_error("orca.host.tools.call takes its arguments as a dict"); - ToolBridge* bridge = current_tool_bridge(); - const std::string identity = PluginAuditManager::instance().current_plugin(); + ToolBridge* bridge = current_tool_bridge(); + const std::string identity = PluginAuditManager::instance().current_plugin(); + const PythonRunBinding& binding = current_python_run(); try { + // A tool call waits for the UI thread, so a window callback, which runs there, can't make one. wx reports + // every thread as its main one until it has started, hence the app check. + if (binding.run && (binding.kind == PythonRunThread::Callback || (wxTheApp != nullptr && wxIsMainThread()))) + throw std::runtime_error("A script's window callbacks run on the UI thread and call no tools; hand the message to the " + "script's own code, which can"); + // Any thread of a run calls through the run, while the run lasts. + if (binding.run && (binding.run->has_tools() || binding.run->tools_closed())) { + std::shared_ptr run = binding.run; + py::gil_scoped_release release; + return run->call_tool(name, arguments); + } if (bridge != nullptr) { py::gil_scoped_release release; return bridge->call(name, arguments); } if (is_script_identity(identity)) - throw std::runtime_error("Only the run's own worker calls tools: a thread a script starts can read but not call tools"); + throw std::runtime_error("A script calls tools only while its run lasts"); if (identity.empty()) throw std::runtime_error("orca.host.tools needs a plugin or a script: call it from a Script capability or a script's own code"); // A plugin's call waits for the UI thread, so it comes only from a thread nothing there waits for. @@ -110,8 +127,9 @@ void register_tools(py::module_& host) "Call the MCP tool `name` with `args` (a dict) and return its result as a dict. A call that outlives its " "reply budget returns {status: \"running\" | \"blocked_by_dialog\", job}, as it does for an agent; follow it " "with call(\"wait\", {\"for\": \"job\", \"job\": ...}). An error result raises ToolError, whose details " - "hold the result's data. A person's or an agent's script calls tools from its own code, not from threads it " - "starts; a plugin needs the tools permission and calls from a Script worker, never the UI thread."); + "hold the result's data. A person's or an agent's script calls tools from its own code and from the threads and " + "pool tasks it starts, while its run lasts, but not from its window callbacks; a plugin needs the tools " + "permission and calls from a Script worker, never the UI thread."); tools.def( "run_script", [tools](const py::object& script, const py::object& vars) mutable { diff --git a/src/slic3r/plugin/host/PluginHostUi.cpp b/src/slic3r/plugin/host/PluginHostUi.cpp index 014414f5eb..7415e635dd 100644 --- a/src/slic3r/plugin/host/PluginHostUi.cpp +++ b/src/slic3r/plugin/host/PluginHostUi.cpp @@ -7,6 +7,7 @@ #include "slic3r/plugin/PluginAuditManager.hpp" #include "slic3r/plugin/PythonInterpreter.hpp" // PythonGILState #include "slic3r/plugin/PluginJsonPy.hpp" +#include "slic3r/plugin/PythonRunScope.hpp" #include #include @@ -88,61 +89,113 @@ CallablePtr make_holder(py::object obj) return std::make_shared(std::move(obj)); } +// The script run the calling code's UI belongs to: the run bound to the thread when it owns its UI (a person's or an +// agent's script). None for a plugin's code, a plugin's run_python included, whose UI belongs to the plugin as always. +std::shared_ptr owning_run() +{ + const PythonRunBinding& binding = current_python_run(); + return binding.run && binding.run->owns_ui() ? binding.run : nullptr; +} + +// Who owns what the calling code opens: the run bound to the thread (refusing once its UI has closed, so nothing it +// opens outlives it), else the plugin whose code this is. +std::string new_ui_owner() +{ + const PythonRunBinding& binding = current_python_run(); + if (!binding.run) + return PluginAuditManager::instance().current_plugin(); + if (binding.run->owns_ui() && binding.run->ui_closed()) + throw std::runtime_error("The script's run has ended; it opens no more windows"); + return binding.run->ui_owner(); +} + +// On the UI thread, before creating what a run asked for: a run whose UI closed while the request waited gets nothing. +void ensure_ui_open(const std::shared_ptr& run) +{ + if (run && run->ui_closed()) + throw std::runtime_error("The script's run has ended; it opens no more windows"); +} + +// Calls `call` under the GIL. A script run's callback runs inside that run (its identity, its UI owner, its thread +// attribution), counted as one of its active callbacks so the run waits for it, and does nothing once the run's UI has +// closed. A callback runs on the UI thread, so it calls no tools (call_tool refuses a Callback binding). +template +void call_in_run(const std::shared_ptr& run, Call&& call) +{ + if (run && (run->ui_closed() || !run->callback_entering())) + return; + struct Left + { + PythonRunScope* run; + ~Left() + { + if (run != nullptr) + run->callback_left(); + } + } left{run.get()}; + PythonGILState gil; + if (!gil) + return; + std::optional bound; + std::optional audit; + if (run) { + bound.emplace(run, PythonRunThread::Callback); + audit.emplace(run->identity()); + } + call(); +} + // Adapt a Python callable to a GUI message handler that acquires the GIL and // swallows/logs exceptions (a raising handler must not escape into wx events). -GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message) +GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message, const char* what = "on_message") { CallablePtr holder = make_holder(std::move(on_message)); if (!holder) return nullptr; - return [holder](const json& data) { - PythonGILState gil; - if (!gil) - return; - try { - holder->fn(json_to_py(data)); - } catch (py::error_already_set& e) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui on_message handler raised: " << e.what(); - PyErr_Clear(); - } + return [holder, run = owning_run(), what](const json& data) { + call_in_run(run, [&] { + try { + holder->fn(json_to_py(data)); + } catch (py::error_already_set& e) { + BOOST_LOG_TRIVIAL(error) << "orca.host.ui " << what << " handler raised: " << e.what(); + PyErr_Clear(); + } + }); }; } -GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit) +// A callable that takes no arguments (on_close, a notification's link): true unless it returned a false value. +std::function make_event_adapter(const CallablePtr& holder, std::shared_ptr run, const char* what) { - CallablePtr holder = make_holder(std::move(on_submit)); if (!holder) return nullptr; - return [holder](const json& data) { - PythonGILState gil; - if (!gil) - return; - try { - holder->fn(json_to_py(data)); - } catch (py::error_already_set& e) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui on_submit handler raised: " << e.what(); - PyErr_Clear(); - } + return [holder, run = std::move(run), what]() { + bool handled = false; + call_in_run(run, [&] { + if (!holder->active.load(std::memory_order_acquire)) + return; + try { + py::object result = holder->fn(); + handled = result.is_none() || result.cast(); + } catch (py::error_already_set& e) { + BOOST_LOG_TRIVIAL(error) << "orca.host.ui " << what << " handler raised: " << e.what(); + PyErr_Clear(); + } catch (const std::exception& e) { + BOOST_LOG_TRIVIAL(error) << "orca.host.ui " << what << " handler raised: " << e.what(); + } + }); + return handled; }; } // The plugin's on_close: fired only on a user/JS-initiated close (not forced teardown), while the -// window is alive. Empty if the plugin passed None. -std::function make_close_adapter(const CallablePtr& holder) +// window is alive. Empty if the plugin passed None. `run` is the script run that opened the window, if any. +std::function make_close_adapter(const CallablePtr& holder, std::shared_ptr run) { - if (!holder) + std::function event = make_event_adapter(holder, std::move(run), "on_close"); + if (!event) return nullptr; - return [holder]() { - PythonGILState gil; - if (!gil) - return; - try { - holder->fn(); - } catch (py::error_already_set& e) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui on_close handler raised: " << e.what(); - PyErr_Clear(); - } - }; + return [event]() { (void) event(); }; } // -------------------------------------------------------------------------- @@ -347,10 +400,27 @@ std::string button_to_string(int rc) std::string ui_message(const std::string& text, const std::string& title, const std::string& buttons, const std::string& icon) { - host_bindings::require_plugin_caller("ui.message"); + const std::string owner = new_ui_owner(); + const std::shared_ptr run = owning_run(); const long style = message_style(buttons, icon); return run_on_ui_blocking([&]() -> std::string { + ensure_ui_open(run); GUI::MessageDialog dlg(nullptr, wxString::FromUTF8(text), wxString::FromUTF8(title), style); + // A script's message box closes with its run, so a stop ends the modal loop the run waits in. A plugin's + // stays unregistered: its unload doesn't close it. + struct Registered + { + int id = 0; + ~Registered() + { + if (id != 0) + UiRegistry::instance().remove(id); + } + } registered; + if (run) { + registered.id = UiRegistry::instance().reserve_id(); + UiRegistry::instance().bind(registered.id, &dlg, owner); + } return button_to_string(dlg.ShowModal()); }); } @@ -375,11 +445,11 @@ struct UiProgressHandle py::object ui_create_window(const std::string& html, const std::string& title, int width, int height, py::object on_message, py::object on_close, long style, py::object on_submit) { - host_bindings::require_plugin_caller("ui.create_window"); + const std::string plugin_key = new_ui_owner(); + auto run = owning_run(); auto msg_adapter = make_message_adapter(std::move(on_message)); - auto submit_adapter = make_submit_adapter(std::move(on_submit)); + auto submit_adapter = make_message_adapter(std::move(on_submit), "on_submit"); CallablePtr close_holder = make_holder(std::move(on_close)); - const std::string plugin_key = PluginAuditManager::instance().current_plugin(); const int w = width > 0 ? width : 820; const int h = height > 0 ? height : 600; @@ -410,15 +480,15 @@ py::object ui_create_window(const std::string& html, const std::string& title, i const int new_id = UiRegistry::instance().reserve_id(); UiRegistry::instance().bind(new_id, nullptr, plugin_key); - GUI::wxGetApp().CallAfter([new_id, plugin_key, html, title, w, h, + GUI::wxGetApp().CallAfter([new_id, plugin_key, html, title, w, h, run, msg_adapter = std::move(msg_adapter), submit_adapter = std::move(submit_adapter), close_holder = std::move(close_holder), modal]() mutable { - // Torn down (plugin unload / app shutdown) before the window materialized. + // Torn down (plugin unload, a script run's end, app shutdown) before the window materialized. if (!UiRegistry::instance().is_open(new_id)) return; - GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder); + GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder, run); // Registry cleanup: GIL-free, runs from the dialog destructor on every path. auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); }; @@ -492,13 +562,15 @@ void run_when_plater_shown(std::function fn) py::object ui_create_dock_panel(const std::string& html, const std::string& title, int width, int height, py::object on_message, py::object on_close, const std::string& dock) { - host_bindings::require_plugin_caller("ui.create_dock_panel"); if (std::find(std::begin(DOCK_POSITIONS), std::end(DOCK_POSITIONS), dock) == std::end(DOCK_POSITIONS)) throw std::invalid_argument("orca.host.ui.create_dock_panel dock must be \"left\", \"right\", \"bottom\" or \"float\""); + const std::string plugin_key = new_ui_owner(); + auto run = owning_run(); + // A script's panels keep one saved layout per title across its runs, which each own their panels. + const std::string pane_key = run ? run->identity() : plugin_key; auto msg_adapter = make_message_adapter(std::move(on_message)); CallablePtr close_holder = make_holder(std::move(on_close)); - const std::string plugin_key = PluginAuditManager::instance().current_plugin(); const int w = width > 0 ? width : 320; const int h = height > 0 ? height : 480; @@ -509,7 +581,7 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl const int new_id = UiRegistry::instance().reserve_id(); UiRegistry::instance().bind(new_id, nullptr, plugin_key); - run_when_plater_shown([new_id, plugin_key, html, title, dock, w, h, + run_when_plater_shown([new_id, plugin_key, pane_key, html, title, dock, w, h, run, msg_adapter = std::move(msg_adapter), close_holder = std::move(close_holder)](GUI::Plater* plater) mutable { if (!UiRegistry::instance().is_open(new_id)) @@ -521,10 +593,10 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl } auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); }; - auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), make_close_adapter(close_holder), + auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), make_close_adapter(close_holder, run), std::move(on_destroyed)); UiRegistry::instance().bind(new_id, panel, plugin_key); - plater->add_dock_pane(panel, GUI::plugin_pane_name(plugin_key, title), wxString::FromUTF8(title), dock, + plater->add_dock_pane(panel, GUI::plugin_pane_name(pane_key, title), wxString::FromUTF8(title), dock, wxSize(w, h), [panel]() { panel->fire_close(); }); }); @@ -533,7 +605,6 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl void handle_post(int id, py::object data) { - host_bindings::require_plugin_caller("ui.UiWindow.post"); if (wxTheApp == nullptr) return; json j = py_to_json(data); // GIL held (binding body) @@ -548,7 +619,6 @@ void handle_post(int id, py::object data) void handle_close(int id) { - host_bindings::require_plugin_caller("ui.UiWindow.close"); if (wxTheApp == nullptr) return; GUI::wxGetApp().CallAfter([id]() { @@ -562,7 +632,6 @@ void handle_close(int id) void handle_show(int id, bool show) { - host_bindings::require_plugin_caller("ui.UiDockPanel.show"); if (wxTheApp == nullptr) return; GUI::wxGetApp().CallAfter([id, show]() { @@ -575,11 +644,12 @@ void handle_show(int id, bool show) UiProgressHandle ui_create_progress_dialog(const std::string& title, const std::string& message, int maximum, int style) { - host_bindings::require_plugin_caller("ui.create_progress_dialog"); - const std::string plugin_key = PluginAuditManager::instance().current_plugin(); + const std::string plugin_key = new_ui_owner(); + const auto run = owning_run(); const int max_value = maximum > 0 ? maximum : 100; return run_on_ui_blocking([&]() -> UiProgressHandle { + ensure_ui_open(run); const int new_id = UiRegistry::instance().reserve_id(); // Registry cleanup: GIL-free, runs from the dialog destructor on every path. @@ -595,7 +665,6 @@ UiProgressHandle ui_create_progress_dialog(const std::string& title, const std:: UiProgressHandle* new_progress_dialog(const std::string& title, const std::string& message, int maximum, int style) { - host_bindings::require_plugin_caller("ui.ProgressDialog"); return new UiProgressHandle(ui_create_progress_dialog(title, message, maximum, style)); } @@ -606,7 +675,6 @@ bool progress_is_open(int id) bool progress_pulse(int id, const std::string& message) { - host_bindings::require_plugin_caller("ui.ProgressDialog.pulse"); return run_on_ui_blocking([&]() { auto* d = UiRegistry::instance().get_as(id); return GUI::PluginProgressDialog::pulse(d, wxString::FromUTF8(message)); @@ -615,7 +683,6 @@ bool progress_pulse(int id, const std::string& message) bool progress_update(int id, int value, const std::string& message) { - host_bindings::require_plugin_caller("ui.ProgressDialog.update"); return run_on_ui_blocking([&]() { auto* d = UiRegistry::instance().get_as(id); return GUI::PluginProgressDialog::update(d, value, wxString::FromUTF8(message)); @@ -624,7 +691,6 @@ bool progress_update(int id, int value, const std::string& message) void progress_start_pulse(int id, int interval_ms, const std::string& message) { - host_bindings::require_plugin_caller("ui.ProgressDialog.start_pulse"); run_on_ui_blocking([&]() { auto* d = UiRegistry::instance().get_as(id); GUI::PluginProgressDialog::start_pulse(d, interval_ms, wxString::FromUTF8(message)); @@ -633,7 +699,6 @@ void progress_start_pulse(int id, int interval_ms, const std::string& message) void progress_stop_pulse(int id) { - host_bindings::require_plugin_caller("ui.ProgressDialog.stop_pulse"); run_on_ui_blocking([&]() { auto* d = UiRegistry::instance().get_as(id); GUI::PluginProgressDialog::stop_pulse(d); @@ -642,7 +707,6 @@ void progress_stop_pulse(int id) void progress_close(int id) { - host_bindings::require_plugin_caller("ui.ProgressDialog.close"); run_on_ui_blocking([&]() { auto* d = UiRegistry::instance().get_as(id); GUI::PluginProgressDialog::request_close(d); @@ -652,39 +716,18 @@ void progress_close(int id) void plater_notification(GUI::NotificationManager::NotificationLevel notification_level, const std::string& text, const std::string& hypertext, py::object on_click) { - host_bindings::require_plugin_caller("ui.push_notification"); - const std::string plugin_key = PluginAuditManager::instance().current_plugin(); + const std::string plugin_key = new_ui_owner(); + const auto run = owning_run(); CallablePtr holder = make_holder(std::move(on_click)); if (holder) UiRegistry::instance().bind_callback(holder, plugin_key); std::function callback; - if (holder) { - callback = [holder](wxEvtHandler*) -> bool { - if (!holder->active.load(std::memory_order_acquire)) - return false; + if (std::function event = make_event_adapter(holder, run, "notification")) + callback = [event](wxEvtHandler*) -> bool { return event(); }; - PythonGILState gil; - if (!gil) - return false; - try { - py::object result = holder->fn(); - return result.is_none() || result.cast(); - } catch (py::error_already_set& e) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui notification callback raised: " << e.what(); - PyErr_Clear(); - return false; - } catch (const std::exception& e) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui notification callback raised: " << e.what(); - return false; - } catch (...) { - BOOST_LOG_TRIVIAL(error) << "orca.host.ui notification callback raised an unknown exception"; - return false; - } - }; - } - - run_on_ui_blocking([notification_level, text, hypertext, callback = std::move(callback)]() mutable { + run_on_ui_blocking([notification_level, text, hypertext, &run, callback = std::move(callback)]() mutable { + ensure_ui_open(run); GUI::wxGetApp().plater()->get_notification_manager()->push_notification(GUI::NotificationType::CustomNotification, notification_level, text, hypertext, std::move(callback)); }); @@ -692,6 +735,16 @@ void plater_notification(GUI::NotificationManager::NotificationLevel notificatio } // namespace +std::function PluginHostUi::message_callback(pybind11::object fn) +{ + return make_message_adapter(std::move(fn)); +} + +std::function PluginHostUi::event_callback(pybind11::object fn) +{ + return make_event_adapter(make_holder(std::move(fn)), owning_run(), "on_close"); +} + void PluginHostUi::run_on_ui_thread(std::function fn) { run_on_ui_blocking(std::move(fn)); @@ -838,6 +891,8 @@ void PluginHostUi::close_windows_for_plugin(const std::string& plugin_key) GUI::WebDialog::destroy_silently(dialog); else if (auto* panel = dynamic_cast(window)) panel->destroy_silently(); + else if (auto* message = dynamic_cast(window)) + message->EndModal(wxID_CANCEL); // a script's message box lives on the stack of its modal call else if (window != nullptr) window->Destroy(); } @@ -845,8 +900,20 @@ void PluginHostUi::close_windows_for_plugin(const std::string& plugin_key) if (wxIsMainThread()) teardown(); - else + else if (!app_closing()) GUI::wxGetApp().CallAfter(teardown); } +void PluginHostUi::close_run_windows(const std::string& owner) +{ + if (wxTheApp == nullptr) + return; + try { + run_on_ui_blocking([&owner]() { close_windows_for_plugin(owner); }); + } catch (const std::exception& e) { + // The app is closing: its own teardown takes the windows. + BOOST_LOG_TRIVIAL(info) << "Script windows left to the app's teardown: " << e.what(); + } +} + } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostUi.hpp b/src/slic3r/plugin/host/PluginHostUi.hpp index cb47416b71..bcf4e6e90e 100644 --- a/src/slic3r/plugin/host/PluginHostUi.hpp +++ b/src/slic3r/plugin/host/PluginHostUi.hpp @@ -1,6 +1,8 @@ #pragma once +#include #include +#include #include #include @@ -25,6 +27,18 @@ public: // Lifecycle hook: close and tear down every UI window owned by a plugin. PluginManager invokes // this after plugin teardown and also for bulk unload during application shutdown. static void close_windows_for_plugin(const std::string& plugin_key); + + // From a script run's thread, with the GIL held: tears down what the run owns (`owner`, its ui_owner()) on the UI + // thread and returns once that is done, so none of its callbacks runs after. Does nothing while the app closes. + static void close_run_windows(const std::string& owner); + + // The handler create_window() and create_dock_panel() give a page for its on_message and on_submit: calls `fn` + // with the page's data under the GIL. Made in a script's run, it runs inside that run, which waits for it, and does + // nothing once the run's UI has closed. + static std::function message_callback(pybind11::object fn); + // The same for a callable that takes no arguments (on_close, a notification's link): true unless it returned a + // false value. + static std::function event_callback(pybind11::object fn); }; } // namespace Slic3r diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 9526482ac8..1500de6cdd 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -827,6 +827,22 @@ TEST_CASE("idle ignores the caller and its ancestors", "[Mcp]") CHECK(jobs.running_operations() == std::vector{step}); } +TEST_CASE("idle skips a job set idle, but not the calls it makes", "[Mcp]") +{ + JobRegistry jobs; + const std::string run = jobs.create("run_python", ""); + jobs.set_idle(run); + const std::string child = jobs.create("slice", run); + CHECK(jobs.any_running_except({})); + bool listed_idle = false; + for (const nlohmann::json& job : jobs.list()) + if (job["id"] == run) + listed_idle = job.value("idle", false); + CHECK(listed_idle); + jobs.finish(child, ToolResult::ok()); + CHECK_FALSE(jobs.any_running_except({})); +} + TEST_CASE("the job registry caps running jobs and forgets old finished ones", "[Mcp]") { JobRegistry jobs; diff --git a/tests/slic3rutils/test_plugin_host_api.cpp b/tests/slic3rutils/test_plugin_host_api.cpp index bc7c25392e..14b1d69aca 100644 --- a/tests/slic3rutils/test_plugin_host_api.cpp +++ b/tests/slic3rutils/test_plugin_host_api.cpp @@ -632,290 +632,3 @@ TEST_CASE("Plugin host API exposes TriangleMesh geometry to Python", "[PluginHos REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(0, 3)).cast(), WithinAbs(5.0, 1e-6)); REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(1, 3)).cast(), WithinAbs(6.0, 1e-6)); } - -namespace { - -// Every function and public method reachable under orca.host, as "." or -// ".." ("" for orca.host itself), sorted. -std::vector host_callables(const py::module_& host) -{ - py::dict scope; - scope["host"] = host; - py::exec(R"PY( -import inspect, types -names = [] -def walk(module, prefix, seen): - if id(module) in seen: - return - seen.add(id(module)) - for name, value in vars(module).items(): - if name.startswith("_"): - continue - if isinstance(value, types.ModuleType): - if value.__name__.startswith(host.__name__): - walk(value, prefix + name + ".", seen) - elif inspect.isclass(value): - if getattr(value, "__module__", "").startswith(host.__name__) or value.__module__ == "orca": - for member, attr in vars(value).items(): - if not member.startswith("_") and callable(attr) and not isinstance(attr, property): - names.append(prefix + name + "." + member) - elif callable(value): - names.append(prefix + name) -walk(host, "", set()) -names = sorted(set(names)) -)PY", scope); - return scope["names"].cast>(); -} - -} // namespace - -TEST_CASE("every orca.host function is classified as callable by scripts or by plugins only", "[PluginHost][Python]") -{ - py::module_ orca = import_orca_module(); - // Functions that change state outside the MCP tools, which call require_plugin_caller() first. - const std::set plugin_only{ - "Plater.export_3mf_copy", - "plugin.storage", - "preset.PresetEditor.begin_update", - "preset.PresetEditor.update", - "preset.bundles.reload_local", - "ui.create_dock_panel", - "ui.create_progress_dialog", - "ui.create_window", - "ui.message", - "ui.push_notification", - // Reached only through a function above (a transaction from begin_update, a handle from a window or - // progress dialog), or only inside a slicing hook, which a script never runs in. - "Layer.make_slices", - "SurfaceCollection.append", - "SurfaceCollection.clear", - "SurfaceCollection.set", - "SurfaceCollection.set_type", - "preset.PresetTransaction.commit", - "preset.PresetTransaction.set", - "ui.ProgressDialog.close", - "ui.ProgressDialog.pulse", - "ui.ProgressDialog.start_pulse", - "ui.ProgressDialog.stop_pulse", - "ui.ProgressDialog.update", - "ui.UiDockPanel.close", - "ui.UiDockPanel.hide", - "ui.UiDockPanel.post", - "ui.UiDockPanel.show", - "ui.UiWindow.close", - "ui.UiWindow.post", - }; - // Functions a person's or an agent's script may call: reads, and orca.host.tools. - const std::set script_callable{ - "ui.ProgressDialog.is_open", - "ui.UiDockPanel.is_open", - "ui.UiWindow.is_open", - "ExPolygon.area", - "ExPolygon.contains", - "ExPolygon.diff_ex", - "ExPolygon.douglas_peucker", - "ExPolygon.intersection_ex", - "ExPolygon.is_valid", - "ExPolygon.num_contours", - "ExPolygon.offset", - "ExPolygon.rotate", - "ExPolygon.scale", - "ExPolygon.set_holes", - "ExPolygon.simplify", - "ExPolygon.translate", - "ExPolygon.union_ex", - "ExtrusionEntityCollection.flatten_paths", - "ExtrusionEntityCollection.size", - "ExtrusionPath.points", - "Layer.lslices", - "Layer.regions", - "LayerRegion.config_value", - "LayerRegion.layer", - "LayerRegion.region", - "Model.bounding_box", - "Model.bounding_box_approx", - "Model.current_plate_index", - "Model.design_id", - "Model.designer", - "Model.id", - "Model.is_fdm_support_painted", - "Model.is_fuzzy_skin_painted", - "Model.is_mm_painted", - "Model.is_seam_painted", - "Model.material_count", - "Model.max_z", - "Model.object", - "Model.object_count", - "Model.objects", - "ModelInstance.assemble_matrix", - "ModelInstance.assemble_offset", - "ModelInstance.assemble_rotation", - "ModelInstance.bounding_box", - "ModelInstance.id", - "ModelInstance.is_assemble_initialized", - "ModelInstance.is_left_handed", - "ModelInstance.is_printable", - "ModelInstance.matrix", - "ModelInstance.mirror", - "ModelInstance.offset", - "ModelInstance.offset_to_assembly", - "ModelInstance.rotation", - "ModelInstance.scaling_factor", - "ModelObject.bounding_box", - "ModelObject.config_keys", - "ModelObject.config_value", - "ModelObject.facets_count", - "ModelObject.has_custom_layering", - "ModelObject.id", - "ModelObject.instance", - "ModelObject.instance_count", - "ModelObject.instances", - "ModelObject.is_cut", - "ModelObject.is_fdm_support_painted", - "ModelObject.is_fuzzy_skin_painted", - "ModelObject.is_mm_painted", - "ModelObject.is_multiparts", - "ModelObject.is_seam_painted", - "ModelObject.materials_count", - "ModelObject.max_z", - "ModelObject.mesh_errors_count", - "ModelObject.min_z", - "ModelObject.parts_count", - "ModelObject.raw_mesh_bounding_box", - "ModelObject.volume", - "ModelObject.volume_count", - "ModelObject.volumes", - "ModelVolume.bounding_box", - "ModelVolume.config_keys", - "ModelVolume.config_value", - "ModelVolume.extruder_id", - "ModelVolume.facets_count", - "ModelVolume.id", - "ModelVolume.is_fdm_support_painted", - "ModelVolume.is_fuzzy_skin_painted", - "ModelVolume.is_manifold", - "ModelVolume.is_mm_painted", - "ModelVolume.is_model_part", - "ModelVolume.is_modifier", - "ModelVolume.is_negative_volume", - "ModelVolume.is_precise_seam", - "ModelVolume.is_precise_seam_strong", - "ModelVolume.is_precise_seam_weak", - "ModelVolume.is_seam_painted", - "ModelVolume.is_support_blocker", - "ModelVolume.is_support_enforcer", - "ModelVolume.is_support_modifier", - "ModelVolume.matrix", - "ModelVolume.mesh", - "ModelVolume.mesh_errors_count", - "ModelVolume.mirror", - "ModelVolume.offset", - "ModelVolume.rotation", - "ModelVolume.scaling_factor", - "ModelVolume.type", - "ModelVolume.volume", - "Plater.inside_snapshot_capture", - "Plater.is_presets_dirty", - "Plater.is_project_dirty", - "Plater.model", - "Plater.project_path", - "Polygon.append", - "Polygon.area", - "Polygon.as_array", - "Polygon.centroid", - "Polygon.contains", - "Polygon.douglas_peucker", - "Polygon.is_clockwise", - "Polygon.is_counter_clockwise", - "Polygon.is_valid", - "Polygon.make_clockwise", - "Polygon.make_counter_clockwise", - "Polygon.offset", - "Polygon.rotate", - "Polygon.set_points", - "Polygon.simplify", - "Polygon.size", - "Polygon.translate", - "Preset.config_keys", - "Preset.config_value", - "Preset.is_from_bundle", - "Preset.is_user", - "Preset.label", - "PresetBundle.current_filament_preset_names", - "PresetBundle.current_filament_presets", - "PresetBundle.current_print_preset", - "PresetBundle.current_printer_preset", - "PresetBundle.current_process_preset", - "PresetBundle.full_config_keys", - "PresetBundle.full_config_value", - "PresetCollection.edited_preset", - "PresetCollection.find_preset", - "PresetCollection.get_edited_preset", - "PresetCollection.get_selected_preset", - "PresetCollection.get_selected_preset_name", - "PresetCollection.preset", - "PresetCollection.preset_names", - "PresetCollection.selected_preset", - "PresetCollection.selected_preset_name", - "PresetCollection.size", - "Print.canceled", - "Print.config_keys", - "Print.config_value", - "Print.model", - "Print.objects", - "PrintObject.bounding_box", - "PrintObject.config_keys", - "PrintObject.config_value", - "PrintObject.id", - "PrintObject.layers", - "PrintObject.model_object", - "PrintObject.support_layers", - "PrintObject.trafo", - "PrintRegion.config_keys", - "PrintRegion.config_value", - "Surface.area", - "Surface.is_bottom", - "Surface.is_bridge", - "Surface.is_external", - "Surface.is_internal", - "Surface.is_solid", - "Surface.is_top", - "SurfaceCollection.empty", - "SurfaceCollection.filter_by_type", - "SurfaceCollection.has", - "SurfaceCollection.size", - "TriangleMesh.bounding_box", - "TriangleMesh.face_normals", - "TriangleMesh.facets_count", - "TriangleMesh.is_empty", - "TriangleMesh.is_manifold", - "TriangleMesh.triangle", - "TriangleMesh.triangle_count", - "TriangleMesh.triangles", - "TriangleMesh.vertex", - "TriangleMesh.vertex_count", - "TriangleMesh.vertices", - "TriangleMesh.volume", - "app_info", - "gl_info", - "model", - "plater", - "preset.bundles.list_ids", - "preset_bundle", - "selected_printer", - "tools.call", - "tools.run_script", - }; - - std::vector unclassified; - for (const std::string& name : host_callables(orca.attr("host").cast())) - if (plugin_only.count(name) == 0 && script_callable.count(name) == 0) - unclassified.push_back(name); - // A new binding is plugin-only until listed here: reads go in script_callable, anything that changes - // state outside the tools calls require_plugin_caller() and goes in plugin_only. - std::string listed; - for (const std::string& name : unclassified) - listed += " \"" + name + "\",\n"; - INFO("Unclassified orca.host functions:\n" << listed); - CHECK(unclassified.empty()); -} diff --git a/tests/slic3rutils/test_python_script_runner.cpp b/tests/slic3rutils/test_python_script_runner.cpp index d6fe8020c4..493c8a0b8b 100644 --- a/tests/slic3rutils/test_python_script_runner.cpp +++ b/tests/slic3rutils/test_python_script_runner.cpp @@ -1,13 +1,16 @@ #include #include +#include #include #include #include #include #include +#include #include #include +#include #include #include @@ -19,12 +22,22 @@ #include #include +#include +#include #include #include +#include #include +#include +#include #include +#include +#include +#include +#include #include +#include #include #include @@ -69,6 +82,122 @@ PythonRunOutcome run(const std::string& code, json args = json::object(), std::c return run_python_code(request); } +// UTF-8 text to a native path and back: wide on Windows, where boost's narrow conversion uses the ANSI code page. +boost::filesystem::path utf8_path(const std::string& utf8) +{ +#ifdef _WIN32 + return boost::filesystem::path(boost::nowide::widen(utf8)); +#else + return boost::filesystem::path(utf8); +#endif +} + +std::string path_utf8(const boost::filesystem::path& path) +{ +#ifdef _WIN32 + return boost::nowide::narrow(path.wstring()); +#else + return path.string(); +#endif +} + +// A folder of script files whose name holds a non-ASCII character, removed at the end. +struct MacroDir +{ + boost::filesystem::path dir; + + MacroDir() : dir(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca-macro-%%%%-%%%%")) + { + dir += utf8_path("-\xC3\xBC"); + boost::filesystem::create_directories(dir); + } + ~MacroDir() + { + boost::system::error_code ec; + boost::filesystem::remove_all(dir, ec); + } + MacroDir(const MacroDir&) = delete; + MacroDir& operator=(const MacroDir&) = delete; + + // Writes `text` as `name` ('/'-separated) and returns the file's path as UTF-8. + std::string write(const std::string& name, const std::string& text) const + { + const boost::filesystem::path path = dir / utf8_path(name); + boost::filesystem::create_directories(path.parent_path()); + boost::nowide::ofstream out(path_utf8(path).c_str(), std::ios::binary); + out << text; + return path_utf8(path); + } + std::string folder() const { return path_utf8(dir); } +}; + +// Runs `code` as the person's script read from the file `path`, which holds the same text. +PythonRunOutcome run_file(const std::string& path, const std::string& code, std::chrono::milliseconds budget = std::chrono::minutes(1), + std::function cancelled = {}) +{ + PythonRunRequest request; + request.code = code; + request.identity = kScriptIdentityPerson; + request.filename = path; + request.budget = budget; + request.cancelled = std::move(cancelled); + return run_python_code(request); +} + +// Evaluates `expr` outside any run and returns its value as JSON. +json py_json(const std::string& expr) +{ + PythonGILState gil; + py::dict scope; + py::exec("import json, sys", scope); + return json::parse(py::eval("json.dumps(" + expr + ")", scope).cast()); +} + +// A module the test shares with its scripts, holding threading.Events and the values they leave; removed at the end. +struct SharedModule +{ + std::string name; + SharedModule(std::string module_name, std::initializer_list events); + ~SharedModule(); + SharedModule(const SharedModule&) = delete; + SharedModule& operator=(const SharedModule&) = delete; + void set(const char* event) const; + bool wait(const char* event, double seconds) const; + // A value a script left at `path` below the module ("pool._shutdown"), as JSON; null when there is none. + json get(const std::string& path) const; +}; + +// Runs `code` outside any run, for the state a test sets up or clears. +void py_run(const std::string& code) +{ + PythonGILState gil; + py::dict scope; + py::exec(code, scope); +} + +SharedModule::SharedModule(std::string module_name, std::initializer_list events) : name(std::move(module_name)) +{ + std::string code = "import sys, types, threading\nm = types.ModuleType('" + name + "')\n"; + for (const char* event : events) + code += std::string("m.") + event + " = threading.Event()\n"; + py_run(code + "sys.modules['" + name + "'] = m\n"); +} + +SharedModule::~SharedModule() { py_run("import sys\nsys.modules.pop('" + name + "', None)\n"); } + +void SharedModule::set(const char* event) const { py_run("import " + name + "\n" + name + "." + event + ".set()\n"); } + +bool SharedModule::wait(const char* event, double seconds) const +{ + return py_json("__import__('" + name + "')." + event + ".wait(" + std::to_string(seconds) + ")").get(); +} + +json SharedModule::get(const std::string& path) const +{ + return py_json("(lambda m: eval('m.' + '" + path + "', {'m': m}) if hasattr(m, '" + path.substr(0, path.find('.')) + + "') else None)(__import__('" + name + "'))"); +} + } // namespace TEST_CASE("a script returns the result it sets, computed from its args", "[PythonScript][Python]") @@ -88,6 +217,363 @@ TEST_CASE("a script returns the result it sets, computed from its args", "[Pytho CHECK(none.result.is_null()); } +TEST_CASE("code run from a file sees the file's path as __file__, and code under a sees none", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + const std::string code = "result = {'file': globals().get('__file__'), 'name': __name__}"; + const std::string path = macro.write("report.py", code); + const PythonRunOutcome from_file = run_file(path, code); + REQUIRE(from_file.status == "finished"); + CHECK(from_file.result == json{{"file", path}, {"name", "__main__"}}); + + const PythonRunOutcome from_name = run_file("", code); + REQUIRE(from_name.status == "finished"); + CHECK(from_name.result["file"].is_null()); +} + +TEST_CASE("a script file runs as the main program, with its folder importable", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + macro.write("helper.py", "VALUE = 1\n"); + const std::string code = "import sys, helper\n" + "result = {'name': __name__, 'argv': list(sys.argv), 'file': __file__, 'value': helper.VALUE,\n" + " 'main': sys.modules['__main__'].__dict__ is globals()}\n"; + const std::string path = macro.write("main.py", code); + const PythonRunOutcome out = run_file(path, code); + REQUIRE(out.status == "finished"); + CHECK(out.result["name"] == "__main__"); + CHECK(out.result["argv"] == json::array({path})); + CHECK(out.result["file"] == path); + CHECK(out.result["value"] == 1); + CHECK(out.result["main"] == true); +} + +TEST_CASE("a file run's sys.argv is a list of its own", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const json app_argv = py_json("list(sys.argv)"); + MacroDir macro; + const std::string code = "import sys\n" + "sys.argv[0] += '!'\n" + "sys.argv.append('x')\n" + "ne = sys.argv != [__file__]\n" + "sys.argv = sys.argv + ['y']\n" + "result = [list(sys.argv), ne]\n"; + const std::string path = macro.write("argv.py", code); + const PythonRunOutcome out = run_file(path, code); + REQUIRE(out.status == "finished"); + CHECK(out.result == json::array({json::array({path + "!", "x", "y"}), true})); + CHECK(py_json("list(sys.argv)") == app_argv); +} + +TEST_CASE("a run leaves sys.path, sys.argv and the app's __main__ as it found them", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const std::string state = "[list(sys.path), list(sys.argv), id(sys.modules['__main__'].__dict__)]"; + const json before = py_json(state); + MacroDir macro; + macro.write("helper.py", "VALUE = 1\n"); + const std::string code = "import helper\nresult = helper.VALUE\n"; + REQUIRE(run_file(macro.write("main.py", code), code).status == "finished"); + CHECK(py_json(state) == before); +} + +TEST_CASE("a helper module edited between runs is imported afresh", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + const std::string helper = macro.write("helper.py", "VALUE = 1\n"); + const std::time_t written = boost::filesystem::last_write_time(utf8_path(helper)); + const std::string code = "import helper\nresult = helper.VALUE\n"; + const std::string path = macro.write("main.py", code); + REQUIRE(run_file(path, code).result == 1); + + // Same size and the first write's time, so only reading the source again shows the edit. + macro.write("helper.py", "VALUE = 2\n"); + boost::filesystem::last_write_time(utf8_path(helper), written); + CHECK(run_file(path, code).result == 2); + CHECK(py_json("'helper' in sys.modules") == false); +} + +TEST_CASE("a namespace package beside the script imports as Python would", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + macro.write("nspkg/mod.py", "X = 3\n"); + const std::string code = "import nspkg.mod\nresult = nspkg.mod.X\n"; + const PythonRunOutcome out = run_file(macro.write("main.py", code), code); + REQUIRE(out.status == "finished"); + CHECK(out.result == 3); + CHECK(py_json("'nspkg.mod' in sys.modules") == false); +} + +TEST_CASE("a module the script reaches through another path entry stays imported", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + macro.write("lib/libmod_kept.py", "Y = 4\n"); + const std::string code = "import os, sys\n" + "sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))\n" + "import libmod_kept\nresult = libmod_kept.Y\n"; + REQUIRE(run_file(macro.write("main.py", code), code).result == 4); + CHECK(py_json("'libmod_kept' in sys.modules") == true); + py_run("import sys\nsys.modules.pop('libmod_kept', None)\n" + "sys.path[:] = [p for p in sys.path if not p.endswith('lib') or 'orca-macro-' not in p]\n"); +} + +TEST_CASE("a package the script reaches through another path entry keeps its submodules", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The package lies below the script's folder, as one installed anywhere under a broad folder does. + MacroDir macro; + macro.write("lib/libpkg_kept/__init__.py", ""); + macro.write("lib/libpkg_kept/part.py", "Z = 5\n"); + const std::string code = "import os, sys\n" + "sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))\n" + "import libpkg_kept.part\nresult = libpkg_kept.part.Z\n"; + REQUIRE(run_file(macro.write("main.py", code), code).result == 5); + CHECK(py_json("'libpkg_kept.part' in sys.modules") == true); + py_run("import sys\nfor name in ('libpkg_kept.part', 'libpkg_kept'):\n sys.modules.pop(name, None)\n" + "sys.path[:] = [p for p in sys.path if 'orca-macro-' not in p]\n"); +} + +TEST_CASE("a script's folder shadows a standard module not imported yet, but not a built-in one", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + REQUIRE(py_json("'colorsys' in sys.modules") == false); + const json builtin = py_json("next((n for n in sorted(sys.builtin_module_names) if n not in sys.modules and n.isidentifier() " + "and not n.startswith('_')), None)"); + if (builtin.is_null()) + SKIP("Every built-in module is imported already"); + MacroDir macro; + macro.write("colorsys.py", "SHADOW = True\n"); + macro.write(builtin.get() + ".py", "SHADOW = True\n"); + const std::string code = "import importlib\nresult = [getattr(importlib.import_module(name), 'SHADOW', False) " + "for name in ('colorsys', '" + builtin.get() + "')]\n"; + const PythonRunOutcome out = run_file(macro.write("main.py", code), code); + REQUIRE(out.status == "finished"); + CHECK(out.result == json::array({true, false})); + CHECK(py_json("'colorsys' in sys.modules") == false); +} + +TEST_CASE("a helper a plugin also loaded stays imported after the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + py_run("import sys, types, threading\nm = types.ModuleType('_overlap')\nm.started = threading.Event()\nm.go = threading.Event()\n" + "sys.modules['_overlap'] = m\n"); + MacroDir macro; + macro.write("helper_shared.py", "VALUE = 5\n"); + const std::string plugmod = macro.write("plugmod_shared.py", "import helper_shared\n"); + const std::string code = "import _overlap, helper_shared\n_overlap.started.set()\n_overlap.go.wait(10)\nresult = helper_shared.VALUE\n"; + const std::string path = macro.write("main.py", code); + PythonRunOutcome out; + std::thread a([&] { out = run_file(path, code); }); + py_run("import _overlap\n_overlap.started.wait(10)\n"); + + std::string error; + std::vector paths, modules; + PyObject* module = PythonInterpreter::instance().load_module_from_file(plugmod, error, &paths, &modules); + py_run("import _overlap\n_overlap.go.set()\n"); + a.join(); + CHECK(out.status == "finished"); + CHECK(module != nullptr); + CHECK(py_json("'helper_shared' in sys.modules") == true); + PythonInterpreter::instance().unload_module(module, "plugmod_shared", paths, modules); + py_run("import sys\nsys.modules.pop('_overlap', None)\n"); +} + +TEST_CASE("a run that replaces the routers or __main__ leaves the next run its own", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const json app_main = py_json("id(sys.modules['__main__'])"); + MacroDir macro; + const std::string first = "import sys, types\nsys.__class__ = types.ModuleType\nsys.modules['__main__'] = types.ModuleType('x')\n"; + REQUIRE(run_file(macro.write("first.py", first), first).status == "finished"); + CHECK(py_json("id(sys.modules['__main__'])") == app_main); + + const std::string second = "import sys\nresult = [list(sys.argv), sys.modules['__main__'].__dict__ is globals()]\n"; + const std::string path = macro.write("second.py", second); + const PythonRunOutcome out = run_file(path, second); + REQUIRE(out.status == "finished"); + CHECK(out.result == json::array({json::array({path}), true})); +} + +TEST_CASE("overlapping runs each see their own __main__ and argv while both run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + py_run("import sys, types, threading\nm = types.ModuleType('_overlap')\nm.b_started = threading.Event()\n" + "m.a_read = threading.Event()\nsys.modules['_overlap'] = m\n"); + MacroDir macro; + const std::string a_code = "import sys, _overlap\n_overlap.b_started.wait(10)\nsys.argv.append('a')\n" + "result = [list(sys.argv), sys.modules['__main__'].__dict__ is globals()]\n_overlap.a_read.set()\n"; + const std::string b_code = "import sys, _overlap\n_overlap.b_started.set()\n_overlap.a_read.wait(10)\n" + "result = [list(sys.argv), sys.modules['__main__'].__dict__ is globals()]\n"; + const std::string a_path = macro.write("a.py", a_code); + const std::string b_path = macro.write("b.py", b_code); + PythonRunOutcome a_out; + std::thread a([&] { a_out = run_file(a_path, a_code); }); + const PythonRunOutcome b_out = run_file(b_path, b_code); + a.join(); + CHECK(a_out.result == json::array({json::array({a_path, "a"}), true})); + CHECK(b_out.result == json::array({json::array({b_path}), true})); + py_run("import sys\nsys.modules.pop('_overlap', None)\n"); +} + +TEST_CASE("runs from one folder evict its helpers only when the last of them ends", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool a_ends_first = GENERATE(true, false); + py_run("import sys, types, threading\nm = types.ModuleType('_overlap')\n" + "m.a_started, m.b_started, m.go_a, m.go_b = (threading.Event() for _ in range(4))\nsys.modules['_overlap'] = m\n"); + MacroDir macro; + macro.write("helper_two.py", "VALUE = 6\n"); + const std::string a_code = "import _overlap, helper_two\n_overlap.a_started.set()\n_overlap.go_a.wait(10)\n"; + const std::string b_code = "import _overlap\n_overlap.b_started.set()\n_overlap.go_b.wait(10)\n"; + const std::string a_path = macro.write("a.py", a_code); + const std::string b_path = macro.write("b.py", b_code); + std::thread a([&] { run_file(a_path, a_code); }); + std::thread b([&] { run_file(b_path, b_code); }); + py_run("import _overlap\n_overlap.a_started.wait(10)\n_overlap.b_started.wait(10)\n"); + CHECK(py_json("'helper_two' in sys.modules") == true); + + py_run(std::string("import _overlap\n_overlap.") + (a_ends_first ? "go_a" : "go_b") + ".set()\n"); + (a_ends_first ? a : b).join(); + CHECK(py_json("'helper_two' in sys.modules") == true); + py_run(std::string("import _overlap\n_overlap.") + (a_ends_first ? "go_b" : "go_a") + ".set()\n"); + (a_ends_first ? b : a).join(); + CHECK(py_json("'helper_two' in sys.modules") == false); + py_run("import sys\nsys.modules.pop('_overlap', None)\n"); +} + +TEST_CASE("a run entering a folder while its last run's teardown runs keeps the helpers it imports", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // A's teardown waits in the helper's atexit function, without the GIL, while B enters the folder and imports. + SharedModule shared("_td", {"in_exit", "go_exit", "b_imported", "go_b"}); + MacroDir macro; + macro.write("helper_td.py", "import atexit, _td\nfrom concurrent.futures import ThreadPoolExecutor\nVALUE = _td.version\n" + "POOL = ThreadPoolExecutor(1)\ndef _bye():\n _td.in_exit.set()\n _td.go_exit.wait(10)\n" + "atexit.register(_bye)\n"); + const std::string a_code = "import _td\n_td.version = 1\nimport helper_td\n"; + const std::string b_code = "import _td\n_td.version = 2\nimport helper_td\n_td.b_value = helper_td.VALUE\n_td.b_imported.set()\n" + "_td.go_b.wait(10)\nresult = helper_td.POOL.submit(int, '9').result(5)\n"; + const std::string a_path = macro.write("a.py", a_code); + const std::string b_path = macro.write("b.py", b_code); + PythonRunOutcome b_out; + std::thread a([&] { run_file(a_path, a_code); }); + REQUIRE(shared.wait("in_exit", 10)); + std::thread b([&] { b_out = run_file(b_path, b_code); }); + REQUIRE(shared.wait("b_imported", 10)); + shared.set("go_exit"); + a.join(); + CHECK(shared.get("b_value") == 2); + CHECK(py_json("getattr(sys.modules.get('helper_td'), 'VALUE', None)") == 2); + shared.set("go_b"); + b.join(); + CHECK(b_out.status == "finished"); + CHECK(b_out.result == 9); + CHECK(py_json("'helper_td' in sys.modules") == false); +} + +TEST_CASE("a helper's finalizers run when its folder's last run ends, inside that run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The helper's functions hold its globals, which hold KEEP: only clearing them frees it before a later collection. + MacroDir macro; + macro.write("helper_cycle.py", "class Bye:\n def __del__(self):\n print('helper finalized')\nKEEP = Bye()\n"); + const std::string code = "import helper_cycle\n"; + const PythonRunOutcome out = run_file(macro.write("main.py", code), code); + CHECK(out.status == "finished"); + CHECK_THAT(out.output, ContainsSubstring("helper finalized")); +} + +TEST_CASE("a filename that is not an existing file runs as code sent as text", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const json app_argv = py_json("list(sys.argv)"); + const std::string code = "import sys\nresult = {'name': __name__, 'file': globals().get('__file__'), 'argv': list(sys.argv)}\n"; + const PythonRunOutcome out = run_file("report", code); + REQUIRE(out.status == "finished"); + CHECK(out.result["name"] == "__main__"); + CHECK(out.result["file"].is_null()); + CHECK(out.result["argv"] == app_argv); +} + +TEST_CASE("a thread a script starts prints into the run's output", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const PythonRunOutcome out = run("import threading\nt = threading.Thread(target=lambda: print('from thread'))\nt.start()\nt.join()\n"); + REQUIRE(out.status == "finished"); + CHECK_THAT(out.output, ContainsSubstring("from thread")); +} + +TEST_CASE("a non-JSON result in a file run comes back as no result, with a note", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + const std::string code = "result = object()\n"; + const PythonRunOutcome out = run_file(macro.write("main.py", code), code); + CHECK(out.status == "finished"); + CHECK(out.result.is_null()); + CHECK_THAT(out.output, ContainsSubstring("not JSON")); +} + TEST_CASE("a script's printed output comes back with its result", "[PythonScript][Python]") { RunnerHarness harness; @@ -190,10 +676,30 @@ struct FakeBridge : ToolBridge { std::vector calls; json last_args; + // Answers a call in place of the canned results when it returns a value; `after` sees each call once answered. + std::function(const std::string&, const json&)> hook; + std::function after; + std::mutex mutex; json call(const std::string& tool, const json& args) override { - calls.push_back(tool); - last_args = args; + { + std::lock_guard lock(mutex); + calls.push_back(tool); + last_args = args; + } + struct After + { + FakeBridge& bridge; + const std::string& tool; + ~After() + { + if (bridge.after) + bridge.after(tool); + } + } after_call{*this, tool}; + if (hook) + if (std::optional answer = hook(tool, args)) + return *answer; if (tool == "get_state") return json{{"ready", true}, {"args", args}}; if (tool == "run_script") @@ -248,7 +754,7 @@ result = orca.host.tools.run_script(text, {"part": "lid"}) CHECK(bridge.last_args == json{{"script", R"({"orca_script": 1, "steps": []} // replayed)"}, {"vars", {{"part", "lid"}}}}); } -TEST_CASE("a thread a script starts reads but can't call tools", "[PythonScript][Python]") +TEST_CASE("a run waits for the non-daemon threads it starts, which call tools through it", "[PythonScript][Python]") { RunnerHarness harness; if (!harness.initialized) @@ -256,49 +762,1130 @@ TEST_CASE("a thread a script starts reads but can't call tools", "[PythonScript] FakeBridge bridge; ScopedToolBridge bound(bridge); - const PythonRunOutcome out = run(R"PY( -import orca, threading -seen = {} -def work(): - try: - orca.host.tools.call("get_state") - seen["called"] = True - except RuntimeError as e: - seen["error"] = str(e) -worker = threading.Thread(target=work) -worker.start() -worker.join() -result = seen -)PY"); - REQUIRE(out.status == "finished"); - CHECK_THAT(out.result.value("error", ""), ContainsSubstring("run's own worker")); - CHECK(bridge.calls.empty()); + const PythonRunOutcome out = run("import orca, threading, time\n" + "def work():\n time.sleep(0.2)\n orca.host.tools.call('get_state')\n" + "threading.Thread(target=work).start()\n"); + CHECK(out.status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); } -TEST_CASE("a script is refused the orca.host functions only plugins may call", "[PythonScript][Python]") +TEST_CASE("a run on a thread Python didn't start waits for the threads it starts", "[PythonScript][Python]") { RunnerHarness harness; if (!harness.initialized) SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + // The app runs a script on an MCP job thread, which Python sees as a daemon dummy thread. + FakeBridge bridge; + PythonRunOutcome out; + std::thread job([&] { + ScopedToolBridge bound(bridge); + out = run("import orca, threading, time\n" + "def work(orca=orca, time=time):\n time.sleep(0.2)\n orca.host.tools.call('get_state')\n" + "threading.Thread(target=work).start()\n"); + }); + job.join(); + CHECK(out.status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a thread started just before the code returns is waited for", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + FakeBridge bridge; + ScopedToolBridge bound(bridge); + CHECK(run("import orca, threading\nthreading.Thread(target=lambda: orca.host.tools.call('get_state')).start()\n").status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a thread started by another of the run's threads after the code returned is waited for", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + FakeBridge bridge; + ScopedToolBridge bound(bridge); + CHECK(run("import orca, threading, time\n" + "def second():\n time.sleep(0.3)\n orca.host.tools.call('get_state')\n" + "def first():\n time.sleep(0.3)\n threading.Thread(target=second).start()\n" + "threading.Thread(target=first).start()\n") + .status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a callback already running when the code returns is waited for, and the thread it starts too", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The script's code hands its run to the test through the bridge, the way a window callback captures it. + SharedModule shared("_cb", {"entered"}); + std::shared_ptr run_scope; + FakeBridge bridge; + bridge.hook = [&](const std::string& tool, const json&) -> std::optional { + if (tool != "capture_run") + return std::nullopt; + run_scope = current_python_run().run; + return json::object(); + }; + ScopedToolBridge bound(bridge); + std::thread callback; + bridge.after = [&](const std::string& tool) { + if (tool != "capture_run") + return; + callback = std::thread([&] { + ScopedPythonRun in_run(run_scope, PythonRunThread::Callback); + if (!run_scope->callback_entering()) + return; + py_run("import orca, threading, time, _cb\n_cb.entered.set()\ntime.sleep(0.3)\n" + "threading.Thread(target=lambda: orca.host.tools.call('get_state')).start()\n"); + run_scope->callback_left(); + }); + }; + const PythonRunOutcome out = run("import orca, _cb\norca.host.tools.call('capture_run')\n_cb.entered.wait(10)\n"); + callback.join(); + CHECK(out.status == "finished"); + CHECK(bridge.calls == std::vector{"capture_run", "get_state"}); +} + +TEST_CASE("a raw thread can't start a thread after its run has ended", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_late", {"done"}); + FakeBridge bridge; + ScopedToolBridge bound(bridge); + REQUIRE(run("import _thread, threading, time, _late\n" + "def raw(time=time, threading=threading, late=_late):\n time.sleep(0.3)\n try:\n" + " threading.Thread(target=print).start()\n except RuntimeError as e:\n late.error = str(e)\n" + " late.done.set()\n" + "_thread.start_new_thread(raw, ())\n") + .status == "finished"); + REQUIRE(shared.wait("done", 5)); + CHECK_THAT(shared.get("error").get(), ContainsSubstring("run has ended")); +} + +TEST_CASE("a script that exits with sys.exit(0) still waits for its threads", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + FakeBridge bridge; + ScopedToolBridge bound(bridge); + CHECK(run("import orca, sys, threading, time\n" + "def work():\n time.sleep(0.2)\n orca.host.tools.call('get_state')\n" + "threading.Thread(target=work).start()\nsys.exit(0)\n") + .status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a daemon thread still running after its run is refused tool calls", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_late", {"go", "done"}); + FakeBridge bridge; + ScopedToolBridge bound(bridge); + REQUIRE(run("import orca, threading, _late\n" + "def work(orca=orca, late=_late):\n late.go.wait(10)\n try:\n orca.host.tools.call('get_state')\n" + " except RuntimeError as e:\n late.error = str(e)\n late.done.set()\n" + "threading.Thread(target=work, daemon=True).start()\n") + .status == "finished"); + shared.set("go"); + REQUIRE(shared.wait("done", 5)); + CHECK_THAT(shared.get("error").get(), ContainsSubstring("run has ended")); + CHECK(bridge.calls.empty()); +} + +TEST_CASE("a tool call in flight when the run ends finishes before the run does", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_late", {"in_call"}); + FakeBridge bridge; + bridge.hook = [&](const std::string&, const json&) -> std::optional { + shared.set("in_call"); + std::this_thread::sleep_for(std::chrono::seconds(1)); + return json{{"ready", true}}; + }; + ScopedToolBridge bound(bridge); + const auto start = std::chrono::steady_clock::now(); + REQUIRE(run("import orca, threading, _late\n" + "def work(orca=orca, late=_late):\n late.result = orca.host.tools.call('get_state')\n" + "threading.Thread(target=work, daemon=True).start()\n_late.in_call.wait(10)\n") + .status == "finished"); + CHECK(std::chrono::steady_clock::now() - start >= std::chrono::seconds(1)); + CHECK(shared.get("result") == json{{"ready", true}}); +} + +TEST_CASE("a stop during the in-flight wait still ends the run as cancelled", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool by_budget = GENERATE(false, true); + SharedModule shared("_late", {"in_call"}); + std::atomic stop{false}; + FakeBridge bridge; + bridge.hook = [&](const std::string&, const json&) -> std::optional { + shared.set("in_call"); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + stop = true; + std::this_thread::sleep_for(std::chrono::seconds(2)); // ignores the cancel + return json::object(); + }; + ScopedToolBridge bound(bridge); + int stops = 0; + PythonRunRequest request; + request.code = "import orca, threading, _late\n" + "threading.Thread(target=lambda: orca.host.tools.call('get_state'), daemon=True).start()\n" + "_late.in_call.wait(10)\n"; + request.identity = kScriptIdentityAgent; + request.budget = by_budget ? std::chrono::milliseconds(1000) : std::chrono::minutes(1); + request.cancelled = [&] { return !by_budget && stop.load(); }; + request.stop_calls = [&] { ++stops; }; + const PythonRunOutcome out = run_python_code(request); + CHECK(out.status == (by_budget ? "timed_out" : "cancelled")); + CHECK(stops == 1); +} + +TEST_CASE("a task the run submits is waited for and runs inside the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const std::string where = GENERATE("module", "list", "function", "helper", "library"); + SharedModule shared("_kept", {}); + MacroDir macro; + const std::string pool_source = "from concurrent.futures import ThreadPoolExecutor\nPOOL = ThreadPoolExecutor(1)\n"; + macro.write("helper_pool.py", pool_source); + macro.write("lib/libpool_task.py", pool_source); + std::string make; + if (where == "module") + make = "from concurrent.futures import ThreadPoolExecutor\npool = ThreadPoolExecutor(1)\n"; + else if (where == "list") + make = "from concurrent.futures import ThreadPoolExecutor\npools = [ThreadPoolExecutor(1)]\npool = pools[0]\n"; + else if (where == "function") + make = "from concurrent.futures import ThreadPoolExecutor\ndef make():\n _kept.pool = ThreadPoolExecutor(1)\n" + " return _kept.pool\npool = make()\n"; + else if (where == "helper") + make = "import helper_pool\npool = helper_pool.POOL\n"; + else + make = "import os, sys\nsys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))\nimport libpool_task\n" + "pool = libpool_task.POOL\n"; + const std::string code = "import orca, time, _kept\n" + make + + "_kept.pool = pool\n" + "def task():\n time.sleep(0.3)\n orca.host.tools.call('get_state')\n" + "pool.submit(task)\n"; + FakeBridge bridge; + ScopedToolBridge bound(bridge); + const PythonRunOutcome out = run_file(macro.write("main.py", code), code, std::chrono::seconds(20)); + CHECK(out.status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); + CHECK(shared.get("pool._shutdown") == (where != "library")); + if (where == "library") { + CHECK(py_json("__import__('_kept').pool.submit(int, '3').result()") == 3); + py_run("import sys, _kept\n_kept.pool.shutdown()\nsys.modules.pop('libpool_task', None)\n" + "sys.path[:] = [p for p in sys.path if 'orca-macro-' not in p]\n"); + } +} + +TEST_CASE("a pool worker another run started runs this run's task inside this run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_kept", {}); + py_run("import _kept\nfrom concurrent.futures import ThreadPoolExecutor\n_kept.pool = ThreadPoolExecutor(1)\n"); + FakeBridge bridge_a, bridge_b; + { + ScopedToolBridge bound(bridge_a); + REQUIRE(run("import _kept\n_kept.pool.submit(int).result()\n").status == "finished"); + } + { + ScopedToolBridge bound(bridge_b); + REQUIRE(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('get_state')).result()\n").status == + "finished"); + } + CHECK(bridge_a.calls.empty()); + CHECK(bridge_b.calls == std::vector{"get_state"}); + py_run("import _kept\n_kept.pool.shutdown()\n"); +} + +TEST_CASE("a submit to a shut-down pool does not hang the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool caught = GENERATE(true, false); + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run(std::string("from concurrent.futures import ThreadPoolExecutor\npool = ThreadPoolExecutor(1)\n" + "pool.shutdown()\n") + + (caught ? "try:\n pool.submit(int)\nexcept RuntimeError:\n pass\n" : "pool.submit(int)\n")); + CHECK(out.status == (caught ? "finished" : "raised")); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); +} + +TEST_CASE("Stop interrupts a task the run submitted", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stop", {"returned", "ended"}); + py_run("import _stop\nfrom concurrent.futures import ThreadPoolExecutor\n_stop.pool = ThreadPoolExecutor(1)\n"); + std::atomic stop{false}; + std::thread stopper([&] { + shared.wait("returned", 10); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const PythonRunOutcome out = run("import _stop\n" + "def task():\n try:\n while True:\n pass\n finally:\n _stop.ended.set()\n" + "_stop.pool.submit(task)\n_stop.returned.set()\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK(shared.wait("ended", 5)); + CHECK(py_json("__import__('_stop').pool.submit(int, '5').result()") == 5); + py_run("import _stop\n_stop.pool.shutdown()\n"); +} + +TEST_CASE("a task queued when the run is stopped never runs", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stop", {"ran"}); + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const PythonRunOutcome out = run("import time, _stop\nfrom concurrent.futures import ThreadPoolExecutor\n" + "pool = ThreadPoolExecutor(1)\n" + "def spin():\n while True:\n time.sleep(0.01)\n" + "pool.submit(spin)\n_stop.second = pool.submit(_stop.ran.set)\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + std::this_thread::sleep_for(std::chrono::seconds(1)); + CHECK(py_json("__import__('_stop').ran.is_set()") == false); + CHECK_THAT(py_json("str(__import__('_stop').second.exception(5))").get(), ContainsSubstring("run has ended")); +} + +TEST_CASE("a task's done callbacks run inside the run that submitted it, and it waits for them", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool warmed = GENERATE(false, true); + SharedModule shared("_cb", {"release"}); + py_run("import _cb\nfrom concurrent.futures import ThreadPoolExecutor\n_cb.pool = ThreadPoolExecutor(1)\n"); + if (warmed) { + FakeBridge other; + ScopedToolBridge bound(other); + REQUIRE(run("import _cb\n_cb.pool.submit(int).result()\n").status == "finished"); + } + FakeBridge bridge; + ScopedToolBridge bound(bridge); + std::thread releaser([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + shared.set("release"); + }); + const PythonRunOutcome out = run("import orca, time, _cb\n" + "def cb(future):\n time.sleep(0.3)\n print('callback ran')\n orca.host.tools.call('get_state')\n" + "_cb.pool.submit(_cb.release.wait, 10).add_done_callback(cb)\n"); + releaser.join(); + CHECK(out.status == "finished"); + CHECK(bridge.calls == std::vector{"get_state"}); + CHECK_THAT(out.output, ContainsSubstring("callback ran")); + py_run("import _cb\n_cb.pool.shutdown()\n"); +} + +TEST_CASE("Stop reaches a task's done callback and the pool keeps working", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_cb", {"release", "first"}); + py_run("import _cb\nfrom concurrent.futures import ThreadPoolExecutor\n_cb.pool = ThreadPoolExecutor(1)\n"); + std::atomic stop{false}; + std::thread driver([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + shared.set("release"); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + stop = true; + }); + const PythonRunOutcome out = run("import _cb\n" + "def first(future):\n try:\n while True:\n pass\n finally:\n _cb.first.set()\n" + "f = _cb.pool.submit(_cb.release.wait, 10)\nf.add_done_callback(first)\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + driver.join(); + CHECK(out.status == "cancelled"); + CHECK(shared.wait("first", 5)); + CHECK(py_json("__import__('_cb').pool.submit(int, '6').result(5)") == 6); + py_run("import _cb\n_cb.pool.shutdown()\n"); +} + +TEST_CASE("a SystemExit in a task's done callback leaves a shared pool working", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // One worker: had the SystemExit ended it, the pool would never run another task. + SharedModule shared("_cb", {}); + py_run("import _cb\nfrom concurrent.futures import ThreadPoolExecutor\n_cb.pool = ThreadPoolExecutor(1)\n"); + const PythonRunOutcome out = run("import threading, _cb\nrelease = threading.Event()\n" + "def bye(future):\n raise SystemExit(3)\n" + "f = _cb.pool.submit(release.wait, 10)\nf.add_done_callback(bye)\nrelease.set()\n"); + CHECK(out.status == "finished"); + CHECK_THAT(out.output, ContainsSubstring("SystemExit")); + CHECK(py_json("__import__('_cb').pool.submit(int, '6').result(5)") == 6); + py_run("import _cb\n_cb.pool.shutdown()\n"); +} + +TEST_CASE("a task's future completed by hand while queued leaves a shared pool working", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_cb", {}); + py_run("import _cb\nfrom concurrent.futures import ThreadPoolExecutor\n_cb.pool = ThreadPoolExecutor(1)\n"); + const PythonRunOutcome out = run("import threading, _cb\nhold = threading.Event()\n_cb.pool.submit(hold.wait, 10)\n" + "f = _cb.pool.submit(int)\nf.set_result(7)\nhold.set()\nresult = f.result()\n"); + CHECK(out.status == "finished"); + CHECK(out.result == 7); + CHECK(py_json("__import__('_cb').pool.submit(int, '6').result(5)") == 6); + py_run("import _cb\n_cb.pool.shutdown()\n"); +} + +TEST_CASE("a submit whose accounting callback can't be added does not hang the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run("import concurrent.futures\npool = concurrent.futures.ThreadPoolExecutor(1)\n" + "original = concurrent.futures.Future.add_done_callback\n" + "def refuse(self, fn):\n raise MemoryError('no room')\n" + "concurrent.futures.Future.add_done_callback = refuse\n" + "try:\n pool.submit(int)\nexcept MemoryError as e:\n result = str(e)\n" + "finally:\n concurrent.futures.Future.add_done_callback = original\n", + json::object(), std::chrono::seconds(20)); + CHECK(out.status == "finished"); + CHECK(out.result == "no room"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(10)); +} + +TEST_CASE("a pool's initializer runs inside the run that started its worker", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + FakeBridge bridge; + ScopedToolBridge bound(bridge); + const PythonRunOutcome out = run("import orca\nfrom concurrent.futures import ThreadPoolExecutor\n" + "def init():\n print('init ran')\n orca.host.tools.call('get_state')\n" + "pool = ThreadPoolExecutor(1, initializer=init)\nresult = pool.submit(int, '5').result(10)\n"); + CHECK(out.status == "finished"); + CHECK(out.result == 5); + CHECK_THAT(out.output, ContainsSubstring("init ran")); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a pool's initializer in a plugin's run runs under the plugin's identity", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The plugin may start its pool's thread: the test grants what it asks for. + PluginAuditManager::set_permission_prompt_for_testing([](const std::string&, const std::vector&) { return true; }); + PythonRunRequest request; + request.code = "import orca\nfrom concurrent.futures import ThreadPoolExecutor\n" + "def init():\n try:\n orca.host.plugin.storage()\n except RuntimeError as e:\n print('storage:', e)\n" + "pool = ThreadPoolExecutor(1, initializer=init)\npool.submit(int).result(10)\n"; + request.identity = "test_plugin_init"; + const PythonRunOutcome out = run_python_code(request); + INFO(out.message << "\n" << out.traceback); + CHECK(out.status == "finished"); + CHECK_THAT(out.output, ContainsSubstring("not registered")); +} + +TEST_CASE("a run waits for a pool's initializer whose task it cancelled", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_ini", {"entered", "go"}); + FakeBridge bridge; + ScopedToolBridge bound(bridge); + std::thread releaser([&] { + shared.wait("entered", 10); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + shared.set("go"); + }); + const PythonRunOutcome out = run("import orca, _ini\nfrom concurrent.futures import ThreadPoolExecutor\n" + "def init():\n _ini.entered.set()\n _ini.go.wait(10)\n print('init done')\n" + " orca.host.tools.call('get_state')\n" + "pool = ThreadPoolExecutor(1, initializer=init)\nf = pool.submit(int)\n_ini.entered.wait(10)\n" + "cancelled = f.cancel()\n"); + releaser.join(); + CHECK(out.status == "finished"); + CHECK_THAT(out.output, ContainsSubstring("init done")); + CHECK(bridge.calls == std::vector{"get_state"}); +} + +TEST_CASE("a thread of an ended run can't start a pool worker whose initializer would run outside it", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The daemon thread starts a second worker after the run ended, as a submit whose task the first worker already + // ran does when it then spins up another worker. + SharedModule shared("_k", {"go", "done"}); + py_run("import _k\n_k.inits = []\ndef init(k=_k):\n k.inits.append(1)\n" + "from concurrent.futures import ThreadPoolExecutor\n_k.pool = ThreadPoolExecutor(2, initializer=init)\n"); + REQUIRE(run("import threading, _k\n_k.pool.submit(int).result(5)\n" + "def late(pool=_k.pool, k=_k):\n k.go.wait(10)\n" + " while pool._idle_semaphore.acquire(timeout=0):\n pass\n" + " try:\n pool._adjust_thread_count()\n except RuntimeError as e:\n k.error = str(e)\n" + " k.done.set()\n" + "threading.Thread(target=late, daemon=True).start()\n") + .status == "finished"); + shared.set("go"); + REQUIRE(shared.wait("done", 10)); + CHECK_THAT(shared.get("error").get(), ContainsSubstring("run has ended")); + CHECK(shared.get("inits") == json::array({1})); + py_run("import _k\n_k.pool.shutdown()\n"); +} + +TEST_CASE("a pool shutdown an interrupt cut short is done again", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The first shutdown is cut as an interrupt would cut CPython's: after _shutdown is set, before the workers' wake-up. + SharedModule shared("_k", {}); + const PythonRunOutcome out = run("import sys, _k\nfrom concurrent.futures import ThreadPoolExecutor\n" + "Interrupted = sys.modules['_orca_run_capture'].RunInterrupted\n" + "class Pool(ThreadPoolExecutor):\n cut = True\n" + " def shutdown(self, wait=True, *, cancel_futures=False):\n" + " if Pool.cut:\n Pool.cut = False\n self._shutdown = True\n" + " raise Interrupted()\n" + " super().shutdown(wait=wait, cancel_futures=cancel_futures)\n" + "_k.pool = Pool(1)\n_k.pool.submit(int).result(5)\n"); + CHECK(out.status == "finished"); + CHECK(py_json("(lambda p: [t.join(5) for t in p._threads] and [t.is_alive() for t in p._threads])(__import__('_k').pool)") == + json::array({false})); +} + +TEST_CASE("Stop reaches a pool's initializer", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stop", {"ended"}); + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const PythonRunOutcome out = run("import time, _stop\nfrom concurrent.futures import ThreadPoolExecutor\n" + "def init():\n try:\n while True:\n time.sleep(0.05)\n" + " finally:\n _stop.ended.set()\n" + "pool = ThreadPoolExecutor(1, initializer=init)\npool.submit(int).result()\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK(shared.wait("ended", 5)); +} + +TEST_CASE("a task cancelled while queued is done to wait()", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const PythonRunOutcome out = run("import threading\nfrom concurrent.futures import ThreadPoolExecutor, wait\n" + "pool = ThreadPoolExecutor(1)\nrelease = threading.Event()\n" + "pool.submit(release.wait, 10)\nsecond = pool.submit(int)\nsecond.cancel()\nrelease.set()\n" + "done, _ = wait([second], timeout=5)\nresult = second in done\n", + json::object(), std::chrono::seconds(30)); + CHECK(out.status == "finished"); + CHECK(out.result == true); +} + +TEST_CASE("a task a broken pool fails does not hang the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run("from concurrent.futures import ThreadPoolExecutor\n" + "def boom():\n raise ValueError('no start')\n" + "pool = ThreadPoolExecutor(1, initializer=boom)\nf = pool.submit(int)\n" + "result = type(f.exception(5)).__name__\n", + json::object(), std::chrono::seconds(20)); + CHECK(out.status == "finished"); + CHECK(out.result == "BrokenThreadPool"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(10)); +} + +TEST_CASE("a submit that raises after queueing its task does not hang the run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The task is queued, but the pool can't start the worker that would run it. + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run("from concurrent.futures import ThreadPoolExecutor\npool = ThreadPoolExecutor(1)\n" + "def no_thread():\n raise RuntimeError('no thread')\npool._adjust_thread_count = no_thread\n" + "try:\n pool.submit(int)\nexcept RuntimeError as e:\n result = str(e)\n", + json::object(), std::chrono::seconds(20)); + CHECK(out.status == "finished"); + CHECK(out.result == "no thread"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(10)); +} + +TEST_CASE("a cancelled task is uncounted once", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool by_shutdown = GENERATE(false, true); + SharedModule shared("_cb", {"release"}); + std::thread releaser([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + shared.set("release"); + }); + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run(std::string("import _cb\nfrom concurrent.futures import ThreadPoolExecutor\n" + "pool = ThreadPoolExecutor(1)\npool.submit(_cb.release.wait, 10)\n" + "second = pool.submit(int)\n") + + (by_shutdown ? "pool.shutdown(wait=False, cancel_futures=True)\n" : "second.cancel()\n")); + releaser.join(); + CHECK(out.status == "finished"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); +} + +TEST_CASE("an untagged pool is still a pool to a run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_kept", {}); + py_run("import _kept\nfrom concurrent.futures import ThreadPoolExecutor\n_kept.pool = ThreadPoolExecutor(1)\n" + "_kept.pool.__dict__.pop('_orca_origin', None)\n"); + FakeBridge bridge; + ScopedToolBridge bound(bridge); + const auto start = std::chrono::steady_clock::now(); + CHECK(run("import orca, _kept\n_kept.pool.submit(lambda: orca.host.tools.call('get_state'))\n").status == "finished"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); + CHECK(bridge.calls == std::vector{"get_state"}); + py_run("import _kept\n_kept.pool.shutdown()\n"); +} + +TEST_CASE("a submit from a thread of an ended run is refused", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_late", {"go", "done"}); + py_run("import _late\nfrom concurrent.futures import ThreadPoolExecutor\n_late.pool = ThreadPoolExecutor(1)\n"); + REQUIRE(run("import threading, _late\n" + "def work(late=_late):\n late.go.wait(10)\n try:\n late.pool.submit(int)\n" + " except RuntimeError as e:\n late.error = str(e)\n late.done.set()\n" + "threading.Thread(target=work, daemon=True).start()\n") + .status == "finished"); + shared.set("go"); + REQUIRE(shared.wait("done", 5)); + CHECK_THAT(shared.get("error").get(), ContainsSubstring("run has ended")); + py_run("import _late\n_late.pool.shutdown()\n"); +} + +TEST_CASE("runs from one folder share a helper's pool and atexit until the last of them ends", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_overlap", {"a_started", "b_started", "go_a", "go_b"}); + MacroDir macro; + macro.write("helper_atexit.py", "import atexit\nfrom concurrent.futures import ThreadPoolExecutor\nPOOL = ThreadPoolExecutor(1)\n" + "atexit.register(print, 'helper done')\n"); + const std::string a_code = "import _overlap, helper_atexit\n_overlap.pool = helper_atexit.POOL\n_overlap.a_started.set()\n" + "_overlap.go_a.wait(10)\n"; + const std::string b_code = "import _overlap, helper_atexit\n_overlap.b_started.set()\n_overlap.go_b.wait(10)\n" + "result = helper_atexit.POOL.submit(int, '4').result(5)\n"; + const std::string a_path = macro.write("a.py", a_code); + const std::string b_path = macro.write("b.py", b_code); + PythonRunOutcome a_out, b_out; + std::thread a([&] { a_out = run_file(a_path, a_code); }); + REQUIRE(shared.wait("a_started", 10)); + std::thread b([&] { b_out = run_file(b_path, b_code); }); + REQUIRE(shared.wait("b_started", 10)); + shared.set("go_a"); + a.join(); + shared.set("go_b"); + b.join(); + CHECK_THAT(a_out.output, !ContainsSubstring("helper done")); + CHECK(b_out.result == 4); + CHECK_THAT(b_out.output, ContainsSubstring("helper done")); + CHECK(shared.get("pool._shutdown") == true); +} + +TEST_CASE("a folder's teardown waits for a plugin import in progress, at the end and at the next entry", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_overlap", {"a_imported", "go_a", "imported", "release"}); + MacroDir macro; + macro.write("helper_import.py", "from concurrent.futures import ThreadPoolExecutor\nPOOL = ThreadPoolExecutor(1)\n"); + const std::string plugmod = macro.write("plugmod_import.py", "import _overlap, helper_import\n_overlap.imported.set()\n" + "_overlap.release.wait(10)\n" + "_overlap.value = helper_import.POOL.submit(int, '7').result(5)\n"); + const std::string a_code = "import _overlap, helper_import\n_overlap.a_imported.set()\n_overlap.go_a.wait(10)\n"; + const std::string a_path = macro.write("a.py", a_code); + const std::string b_code = "x = 1\n"; + const std::string b_path = macro.write("b.py", b_code); + + // Run A imports the helper; a plugin's import takes it and pauses; A ends, then B enters and ends. + PythonRunOutcome a_out; + std::thread a([&] { a_out = run_file(a_path, a_code); }); + REQUIRE(shared.wait("a_imported", 10)); + std::string error; + std::vector paths, modules; + PyObject* module = nullptr; + std::thread plugin([&] { module = PythonInterpreter::instance().load_module_from_file(plugmod, error, &paths, &modules); }); + REQUIRE(shared.wait("imported", 10)); + shared.set("go_a"); + a.join(); + const PythonRunOutcome b_out = run_file(b_path, b_code); + shared.set("release"); + plugin.join(); + CHECK(a_out.status == "finished"); + CHECK(b_out.status == "finished"); + REQUIRE(module != nullptr); + CHECK(shared.get("value") == 7); + CHECK(py_json("'helper_import' in sys.modules") == true); + CHECK(std::find(modules.begin(), modules.end(), "helper_import") != modules.end()); + + // A later run tears the folder down: the plugin's helper and its pool stay. + REQUIRE(run_file(b_path, b_code).status == "finished"); + CHECK(py_json("'helper_import' in sys.modules") == true); + CHECK(py_json("__import__('helper_import').POOL.submit(int, '8').result(5)") == 8); + PythonInterpreter::instance().unload_module(module, "plugmod_import", paths, modules); +} + +TEST_CASE("atexit functions a script registers run when its run ends, last first", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // A first run installs the run helper, whose imports register the standard library's own atexit hooks. + REQUIRE(run("x = 1").status == "finished"); + const json before = py_json("__import__('atexit')._ncallbacks()"); + const PythonRunOutcome out = run("import atexit, functools\natexit.register(print, 'one')\n" + "atexit.register(functools.partial(print, 'two'))\nprint('body')\n"); + REQUIRE(out.status == "finished"); + CHECK(out.output == "body\ntwo\none\n"); + CHECK(py_json("__import__('atexit')._ncallbacks()") == before); +} + +TEST_CASE("a library's atexit registration made during a run stays for the process", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + REQUIRE(run("x = 1").status == "finished"); + const json before = py_json("__import__('atexit')._ncallbacks()"); + MacroDir macro; + macro.write("lib/libexit.py", "import atexit\nCALLED = []\ndef _bye():\n CALLED.append(1)\natexit.register(_bye)\n"); + const std::string code = "import os, sys\nsys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))\nimport libexit\n"; + REQUIRE(run_file(macro.write("main.py", code), code).status == "finished"); + CHECK(py_json("__import__('libexit').CALLED") == json::array()); + CHECK(py_json("__import__('atexit')._ncallbacks()") == before.get() + 1); + py_run("import atexit, sys, libexit\natexit.unregister(libexit._bye)\nsys.modules.pop('libexit', None)\n" + "sys.path[:] = [p for p in sys.path if 'orca-macro-' not in p]\n"); +} + +TEST_CASE("atexit.unregister in one run leaves another run's registration", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_ae", {"a_registered", "go_a"}); + py_run("import _ae\n_ae.calls = []\ndef mark(tag, calls=_ae.calls):\n calls.append(tag)\n_ae.mark = mark\n"); + PythonRunOutcome a_out; + std::thread a([&] { a_out = run("import atexit, _ae\natexit.register(_ae.mark, 'a')\n_ae.a_registered.set()\n_ae.go_a.wait(10)\n"); }); + REQUIRE(shared.wait("a_registered", 10)); + const PythonRunOutcome b_out = run("import atexit, _ae\natexit.register(_ae.mark, 'b')\natexit.unregister(_ae.mark)\n"); + shared.set("go_a"); + a.join(); + CHECK(b_out.status == "finished"); + CHECK(a_out.status == "finished"); + CHECK(shared.get("calls") == json::array({"a"})); +} + +TEST_CASE("a helper a plugin also loaded keeps its atexit functions for the process", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + REQUIRE(run("x = 1").status == "finished"); + const json before = py_json("__import__('atexit')._ncallbacks()"); + SharedModule shared("_overlap", {"started", "go"}); + MacroDir macro; + macro.write("helper_ae.py", "import atexit\nCLOSED = []\ndef _close():\n CLOSED.append(1)\n print('helper closed')\n" + "atexit.register(_close)\n"); + const std::string plugmod = macro.write("plugmod_ae.py", "import helper_ae\n"); + const std::string code = "import _overlap, helper_ae\n_overlap.started.set()\n_overlap.go.wait(10)\n"; + const std::string path = macro.write("main.py", code); + PythonRunOutcome out; + std::thread a([&] { out = run_file(path, code); }); + REQUIRE(shared.wait("started", 10)); + std::string error; + std::vector paths, modules; + PyObject* module = PythonInterpreter::instance().load_module_from_file(plugmod, error, &paths, &modules); + shared.set("go"); + a.join(); + CHECK(out.status == "finished"); + REQUIRE(module != nullptr); + CHECK(py_json("__import__('helper_ae').CLOSED") == json::array()); + CHECK_THAT(out.output, !ContainsSubstring("helper closed")); + CHECK(py_json("__import__('atexit')._ncallbacks()") == before.get() + 1); + py_run("import atexit, helper_ae\natexit.unregister(helper_ae._close)\n"); + PythonInterpreter::instance().unload_module(module, "plugmod_ae", paths, modules); +} + +TEST_CASE("Stop interrupts the threads a run started", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stop", {"ended"}); + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const PythonRunOutcome out = run("import threading, time, _stop\n" + "def spin():\n try:\n while True:\n time.sleep(0.05)\n" + " finally:\n _stop.ended.set()\n" + "threading.Thread(target=spin).start()\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK(shared.wait("ended", 5)); +} + +TEST_CASE("Stop does not hang on a thread that ignores it", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run("import threading, time\nthreading.Thread(target=time.sleep, args=(30,)).start()\n", + json::object(), std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(15)); +} + +TEST_CASE("a stopped run's atexit functions still run and the app's state is restored", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const json state = py_json("[list(sys.argv), id(sys.modules['__main__'].__dict__)]"); + MacroDir macro; + macro.write("helper_stop.py", "VALUE = 1\n"); + const std::string code = "import atexit, helper_stop\natexit.register(print, 'goodbye')\nwhile True:\n pass\n"; + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + const PythonRunOutcome out = run_file(macro.write("main.py", code), code, std::chrono::minutes(1), [&] { return stop.load(); }); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK_THAT(out.output, ContainsSubstring("goodbye")); + CHECK(py_json("[list(sys.argv), id(sys.modules['__main__'].__dict__)]") == state); + const std::string next = "x = 1\n"; + REQUIRE(run_file(macro.write("next.py", next), next).status == "finished"); + CHECK(py_json("'helper_stop' in sys.modules") == false); +} + +TEST_CASE("a finalizer of what a script left in sys.argv is still stopped by the run's time limit", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const auto start = std::chrono::steady_clock::now(); + const PythonRunOutcome out = run("import sys\nclass Loop:\n def __del__(self):\n while True:\n pass\n" + "sys.argv.append(Loop())\n", + json::object(), std::chrono::seconds(1)); + CHECK(out.status == "timed_out"); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(10)); +} + +TEST_CASE("a run with no time limit runs past what a limit would allow", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const std::string code = "import time\ntime.sleep(1.5)\nresult = 1\n"; + CHECK(run(code, json::object(), std::chrono::milliseconds(0)).status == "finished"); + CHECK(run(code, json::object(), std::chrono::milliseconds(1000)).status == "timed_out"); +} + +TEST_CASE("a window callback of a run is refused tool calls", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + FakeBridge bridge; + auto scope = std::make_shared(0, kScriptIdentityPerson, boost::filesystem::path(), &bridge); + ScopedPythonRun in_run(scope, PythonRunThread::Callback); + PythonGILState gil; + py::dict ns; + py::exec("import orca\ntry:\n orca.host.tools.call('get_state')\n error = None\nexcept RuntimeError as e:\n error = str(e)\n", ns); + CHECK_THAT(ns["error"].cast(), ContainsSubstring("window callbacks")); + CHECK(bridge.calls.empty()); +} + +TEST_CASE("a script passes every plugin gate it can reach without an app", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // Without an app every one of these fails further on; none may fail at a plugins-only gate. A gate left anywhere + // would not compile: require_plugin_caller() is gone. const PythonRunOutcome out = run(R"PY( import orca -refusals = [] +messages = [] for attempt in (lambda: orca.host.preset.process.begin_update(), lambda: orca.host.preset.process.update("layer_height", "0.2"), + lambda: orca.host.preset.filament.begin_update(1), + lambda: orca.host.preset.filament.update(1, "filament_flow_ratio", "0.98"), + lambda: orca.host.preset.bundles.reload_local("x"), + lambda: orca.host.plater().export_3mf_copy("x.3mf"), lambda: orca.host.ui.message("hello"), - lambda: orca.host.plugin.storage()): + lambda: orca.host.ui.create_window("

x

"), + lambda: orca.host.ui.create_dock_panel("

x

"), + lambda: orca.host.ui.create_progress_dialog("t", "m"), + lambda: orca.host.ui.push_notification("n")): try: attempt() - refusals.append("allowed") - except RuntimeError as e: - refusals.append(str(e)) -result = refusals + messages.append("allowed") + except Exception as e: + messages.append(str(e)) +result = messages )PY"); REQUIRE(out.status == "finished"); - REQUIRE(out.result.size() == 4); - for (const json& refusal : out.result) - CHECK_THAT(refusal.get(), ContainsSubstring("is for plugins")); + REQUIRE(out.result.size() == 11); + for (const json& message : out.result) + CHECK_THAT(message.get(), !ContainsSubstring("is for plugins")); +} + +TEST_CASE("storage() is the folder of a script's file", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + const std::string code = "import orca\nresult = orca.host.plugin.storage()\n"; + const PythonRunOutcome out = run_file(macro.write("main.py", code), code); + REQUIRE(out.status == "finished"); + CHECK(utf8_path(out.result.get()) == macro.dir); + + const PythonRunOutcome text = run("import orca\ntry:\n orca.host.plugin.storage()\nexcept RuntimeError as e:\n result = str(e)\n"); + REQUIRE(text.status == "finished"); + CHECK_THAT(text.result.get(), ContainsSubstring("no folder")); +} + +TEST_CASE("a window callback runs inside the script's run", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The script hands its callback to the host through the bridge, as create_window does; the test then delivers a + // page message to it from another thread while the run lasts. + SharedModule shared("_cb", {"done"}); + std::function handler; + FakeBridge bridge; + bridge.hook = [&](const std::string& tool, const json&) -> std::optional { + if (tool != "take_callback") + return std::nullopt; + PythonGILState gil; + handler = PluginHostUi::message_callback(py::module_::import("_cb").attr("on_message")); + return json::object(); + }; + std::thread delivery; + bridge.after = [&](const std::string& tool) { + if (tool == "take_callback") + delivery = std::thread([&] { handler(json{{"x", 1}}); }); + }; + ScopedToolBridge bound(bridge); + MacroDir macro; + const std::string code = R"PY( +import orca, threading, _cb +def on_message(data): + _cb.storage = orca.host.plugin.storage() + try: + orca.host.tools.call("get_state") + except RuntimeError as e: + _cb.refused = str(e) + worker = threading.Thread(target=lambda: orca.host.tools.call("get_state")) + worker.start() + worker.join() + _cb.done.set() +_cb.on_message = on_message +orca.host.tools.call("take_callback") +_cb.done.wait(10) +)PY"; + REQUIRE(run_file(macro.write("main.py", code), code).status == "finished"); + delivery.join(); + CHECK(utf8_path(shared.get("storage").get()) == macro.dir); + CHECK_THAT(shared.get("refused").get(), ContainsSubstring("window callbacks")); + CHECK(bridge.calls == std::vector{"take_callback", "get_state"}); +} + +TEST_CASE("a run's callbacks do nothing and its threads open no UI once its UI is closed", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_cb", {"called"}); + auto scope = std::make_shared(1, kScriptIdentityPerson, boost::filesystem::path(), nullptr); + std::function handler; + { + ScopedPythonRun in_run(scope, PythonRunThread::Main); + PythonGILState gil; + handler = PluginHostUi::message_callback(py::eval("lambda data: __import__('_cb').called.set()")); + } + scope->mark_ui_closed(); + handler(json::object()); + CHECK(shared.wait("called", 0.2) == false); + + ScopedPythonRun in_run(scope, PythonRunThread::Started); + PythonGILState gil; + py::dict ns; + py::exec("import orca\ntry:\n orca.host.ui.message('x')\n error = None\nexcept RuntimeError as e:\n error = str(e)\n", ns); + CHECK_THAT(ns["error"].cast(), ContainsSubstring("run has ended")); +} + +TEST_CASE("a plugin's run leaves its window callbacks and its storage to the plugin", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_cb", {"entered", "go"}); + MacroDir macro; + const std::string path = macro.write("main.py", "x = 1\n"); + auto scope = std::make_shared(2, "test_plugin_ui", utf8_path(path), nullptr); + std::function handler; + { + ScopedPythonRun in_run(scope, PythonRunThread::Main); + PythonGILState gil; + handler = PluginHostUi::message_callback(py::eval("lambda data: (__import__('_cb').entered.set(), __import__('_cb').go.wait(10))")); + } + // A script's run counts a running callback and drops one that comes after it ended; a plugin's does neither. + std::thread delivery([&] { handler(json::object()); }); + REQUIRE(shared.wait("entered", 10)); + CHECK(scope->close_admission_if_quiet()); + shared.set("go"); + delivery.join(); + py_run("import _cb\n_cb.entered.clear()\n"); + std::thread later([&] { handler(json::object()); }); + CHECK(shared.wait("entered", 10)); + later.join(); + + ScopedPythonRun in_run(scope, PythonRunThread::Main); + ScopedPluginAuditContext audit("test_plugin_ui"); + PythonGILState gil; + py::dict ns; + py::exec("import orca\ntry:\n orca.host.plugin.storage()\n error = None\nexcept RuntimeError as e:\n error = str(e)\n", ns); + CHECK_THAT(ns["error"].cast(), ContainsSubstring("not registered")); +} + +TEST_CASE("a stopped run opens no more UI", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + std::atomic stop{false}; + std::thread stopper([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + stop = true; + }); + PythonRunRequest request; + request.code = "import atexit, orca\n" + "def later():\n try:\n orca.host.ui.message('x')\n except RuntimeError as e:\n print(e)\n" + "atexit.register(later)\nwhile True:\n pass\n"; + request.identity = kScriptIdentityPerson; + request.cancelled = [&] { return stop.load(); }; + const PythonRunOutcome out = run_python_code(request); + stopper.join(); + CHECK(out.status == "cancelled"); + CHECK_THAT(out.output, ContainsSubstring("run has ended")); } TEST_CASE("orca.host.tools refuses code that is neither a plugin nor a script", "[PythonScript][Python]") @@ -466,6 +2053,118 @@ def handler(args): CHECK_FALSE(harness.prompts.empty()); } +namespace { + +// Records what a run asks to install, in place of uv, for the test's lifetime. +struct InstallerHook +{ + std::vector> installs; + bool succeed = true; + std::string error = "no network"; + InstallerHook() + { + set_python_dependency_installer_for_testing([this](const std::vector& packages, std::string& message) { + installs.push_back(packages); + if (!succeed) + message = error; + return succeed; + }); + } + ~InstallerHook() { set_python_dependency_installer_for_testing(nullptr); } + InstallerHook(const InstallerHook&) = delete; + InstallerHook& operator=(const InstallerHook&) = delete; +}; + +// `text` with its line ends made CRLF. +std::string crlf(const std::string& text) +{ + std::string out; + for (const char c : text) { + if (c == '\n') + out += '\r'; + out += c; + } + return out; +} + +} // namespace + +TEST_CASE("a script file's dependencies are installed before its code runs", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool windows_lines = GENERATE(false, true); + InstallerHook hook; + MacroDir macro; + std::string code = "# /// script\n" + "# dependencies = [\n" + "# \"requests>=2,<3\", # pinned\n" + "# \"rich\",\n" + "# ]\n" + "# ///\n" + "result = 1\n"; + if (windows_lines) + code = crlf(code); + const std::string path = macro.write("deps.py", code); + // The text as the dialog hands it over: read back and decoded as Python reads a source file. + std::string text, encoding, error; + REQUIRE(decode_python_source(code, text, encoding, error)); + const PythonRunOutcome out = run_file(path, text); + CHECK(out.status == "finished"); + REQUIRE(hook.installs.size() == 1); + CHECK(hook.installs[0] == std::vector{"requests>=2,<3", "rich"}); +} + +TEST_CASE("a failed install stops the run before its code", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + InstallerHook hook; + hook.succeed = false; + MacroDir macro; + const std::string code = "# /// script\n# dependencies = [\"rich\"]\n# ///\n" + "import os\nopen(os.path.join(os.path.dirname(__file__), 'ran.txt'), 'w').close()\n"; + const PythonRunOutcome out = run_file(macro.write("deps.py", code), code); + CHECK(out.status == "raised"); + CHECK_THAT(out.message, ContainsSubstring("no network")); + CHECK_FALSE(boost::filesystem::exists(macro.dir / "ran.txt")); +} + +TEST_CASE("a malformed PEP 723 block stops the run before its code", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const std::string block = GENERATE(std::string("# /// script\n# dependencies = [\"x\",\n# ///\n"), + std::string("# /// script\n# dependencies = []\n# ///\n# /// script\n# dependencies = []\n# ///\n"), + std::string("# /// script\n# dependencies = \"x\"\n# ///\n")); + InstallerHook hook; + MacroDir macro; + const std::string code = block + "import os\nopen(os.path.join(os.path.dirname(__file__), 'ran.txt'), 'w').close()\n"; + const PythonRunOutcome out = run_file(macro.write("deps.py", code), code); + CHECK(out.status == "raised"); + CHECK_THAT(out.message, ContainsSubstring("PEP 723")); + CHECK(hook.installs.empty()); + CHECK_FALSE(boost::filesystem::exists(macro.dir / "ran.txt")); +} + +TEST_CASE("code sent as text installs nothing", "[PythonScript][Python]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + InstallerHook hook; + const PythonRunOutcome out = run("# /// script\n# dependencies = [\"rich\"]\n# ///\nresult = 2\n"); + CHECK(out.status == "finished"); + CHECK(hook.installs.empty()); +} + TEST_CASE("an agent's code is compiled as the text it sent, whatever coding line it holds", "[PythonScript][Python]") { RunnerHarness harness; diff --git a/tools/mcp/README.md b/tools/mcp/README.md index 06828a04fc..e071fa2ad5 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -103,6 +103,41 @@ finishes and 1 when it raises, is cancelled or runs out of time; its traceback g scripts run only once the setting allows them: set `"mcp_python_scripts": "true"` in the `app` section of the datadir's `OrcaSlicer.conf` before the launch, since no tool can turn it on. +A `.py` file runs as Python runs it (`python file.py`), with the whole plugin API: `__name__` is +`"__main__"`, `__file__` and `sys.argv` name it, the modules beside it import (afresh each run, so an edit +shows), and the packages its PEP 723 block lists are installed first. It may open windows and progress +dialogs, which close when the run ends, and its threads and pool tasks call the tools too. The run ends once +its code and the non-daemon threads and pool tasks it started are done: + +```python +# /// script +# dependencies = ["numpy"] +# /// +import queue, threading +import orca +import helper # helper.py beside this file + +def main(): + progress = orca.host.ui.create_progress_dialog("Measuring", "Starting", 3) + for step in range(3): + progress.update(step + 1, helper.describe(step)) + # A window's callbacks run on the UI thread and call no tools; they hand the work to the script. + pages = queue.Queue() + window = orca.host.ui.create_window("", + on_message=pages.put) + pages.get() # the person pressed Go + worker = threading.Thread(target=lambda: print(orca.host.tools.call("get_state")["ready"])) + worker.start() # waited for before the run ends + +if __name__ == "__main__": + main() +``` + +A window that stays open is closed with the run, so a script that wants the person to work in it waits, as +the `pages.get()` above does. While a modal it opened is up, tool calls that change the project are refused, +so interactive scripts use modeless windows. `docs/HLSD/mcp-server.md` ("Python scripts") has the rules for +overlapping runs, imports, pools, `atexit` and Stop. + `tests/gizmos.json` drives every gizmo through the GUI tools, the way a person does: each one's icon, its panel's fields, combos, toggles and links, and clicks or strokes at points of the model, then checks what it left on the model (`list_objects`), with an undo and redo and a canvas screenshot per