Repository navigation
Implement plugins - #275
Closed
joergbrech wants to merge 46 commits into
Closed
joergbrech wants to merge 46 commits into
joergbrech wants to merge 46 commits into
Conversation
A standalone example (own pixi environment, own CMake build) demonstrating grunk alongside geoml/OpenCASCADE for CAD modeling, and ADOL-C for automatic differentiation through a dynamic recipe: - register_geoml wraps a handful of geoml/OCCT types and functions (gp_Pnt, bezier_curve, interpolate_curve_network) as grunk dynamic types, building a Gordon surface fuselage cross-section from a recipe. - register_adolc loads ADOL-C's tapeless adouble type via a compiled SWIG-Lua module (adtl.so, built separately per the README) through grunk::state's load_compiled_plugin/register_external_type, and runs a small autodiff recipe through it end to end (write, read back, evaluate). ADOL-C and the SWIG-Lua wrapper are built manually outside of pixi/CMake's own dependency fetching (see README.md for the build steps); everything else (grunk, geoml, opencascade, sol2/lua/yaml-cpp/libparametric) is fetched or resolved automatically via pixi/CMake FetchContent. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TS5yFa1xBMh7dhCLj5yNi3
register_external_type now auto-discovers member functions by probing an instance the first time each is looked up (merged in #262), so the explicit setADValue/getADValue/getValue listing is no longer needed to bridge adtl.adouble.
Move the gp_Pnt/bezier_curve/interpolate_curve_network registration out of register_geoml (called directly from cad_autodiff) into its own shared library (plugins/geoml/geoml_plugin.cpp, built as the geoml_plugin CMake target), and dlopen it at runtime via a new load_geoml_plugin, the same way adtl.so is already loaded. This is #235's "C++ plugin" kind, alongside the existing "compiled Lua module" mockup. Since this plugin shares sol2 usertype machinery for OCCT types with the host executable (unlike adtl.so, where ADOL-C's adouble crosses the boundary only as an opaque grunk::object), it needs RTLD_GLOBAL plus ENABLE_EXPORTS on cad_autodiff so both sides resolve to the same template instantiations - otherwise Handles built by the plugin fail to convert back on the host side. geoml_plugin is a shared library linking the static grunk/geoml libraries, so those need CMAKE_POSITION_INDEPENDENT_CODE too. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011PZm8wzearBkvqPRtyoyZs
Rename write_recipe_ad/read_recipe_ad -> write_autodiff_only_recipe/ read_autodiff_only_recipe (stage 1: AD, no CAD) and write_recipe/ read_recipe -> write_cad_only_recipe/read_cad_only_recipe (stage 2: CAD, no AD), and wire both into main() with printed stage headers - stage 2 was previously dead code. Strip the leftover broken/commented surface-interpolation and debug scaffolding that didn't serve either stage. Document the 3-stage story (stage 3 - CAD *with* AD, via a future geoml+ADOL-C plugin - not yet implemented) in a file-level comment and in README.md, explaining why the example is named "cad_autodiff". Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011PZm8wzearBkvqPRtyoyZs
Adds plugins/geoml_adolc/, the AD-enabled counterpart to geoml_plugin.so: a standalone CMake project (kept separate from the main one since it needs a different, AD-enabled geoml under the same CMake target name stock geoml already claims) plus geoml_adolc_plugin.cpp, which shares register_geoml with geoml_plugin.cpp unmodified via the new plugins/geoml_registration.hpp. Not yet buildable - it needs an adOCCT install and geoml's feature/autodiff branch built against it, with an OCCT version mismatch (geoml pins 7.6.2, adOCCT forks V7_9_0) reconciled first. README.md's new "Stage 3" section documents this, and every remaining action is tagged TODO(stage3) for `grep -rn 'TODO(stage3)'`. main.cpp gained write_cad_recipe(bool with_ad)/read_cad_recipe (renamed from write/read_cad_only_recipe) and read_recipe_ad: the same recipe script, with with_ad only choosing which plugin loads - the point of the whole example. The CAD recipe itself is simplified to a single bezier curve (a dev artifact for exercising the plugin swap, not a shape worth modeling), renamed gordon.grr.yml -> bezier_curve.grr.yml. occt_sol_traits.hpp moves from include/ into plugins/, and geoml_plugin gains an export_brep function so main.cpp no longer needs to include any OCCT header at all - even verifying a curve got built now happens via a registered function called from within the recipe. That also means geoml_plugin.so no longer needs RTLD_GLOBAL/ENABLE_EXPORTS to load correctly (reverting part of the previous commit): with no OCCT-typed value crossing into main.cpp's own translation unit, there's nothing left for the dynamic linker to unify. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011PZm8wzearBkvqPRtyoyZs
Every plugin kind (compiled Lua, and soon C++/pure-Lua) needs to record its identity the same way - append to plugins() and mirror into the Lua-global grunk.plugins table for Recipe's uses:-block validation. Pull that bookkeeping out of load_compiled_plugin into a private helper so the upcoming plugin-loading paths can share it instead of duplicating it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Implements the "plain C++" plugin kind PluginInfo's doc comment already described as a future state::begin_plugin(info): a plugin's entry point gets a namespace table to register_type/register_function against directly, instead of the ad hoc flat registration examples/cpp/ cad_autodiff's geoml_plugin.cpp currently does with no PluginInfo/ namespacing at all. Shares the note_plugin bookkeeping (plugins(), grunk.plugins) with load_compiled_plugin, so uses:-block validation works the same regardless of which plugin kind registered a name. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Completes #235's three plugin kinds in grunk::dynamic: compiled Lua (load_compiled_plugin), plain C++ (begin_plugin), and now pure Lua script - no compilation, just a name+version and some Lua source. Thin wrappers over the existing run_module_script/run_module_file, mirrored the same way those two mirror each other, plus the shared note_plugin bookkeeping so uses:-block validation and plugins() behave identically across all three kinds. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
New CMake target/layer (GRUNK_WITH_PLUGIN, default ON, needs GRUNK_WITH_DYNAMIC) providing grunk::plugin::load_native: a generic dlopen-based loader for the fixed grunk_plugin_info/grunk_plugin_register ABI, generalizing the per-plugin dlopen/dlsym dance examples/cpp/ cad_autodiff's src/main.cpp currently hand-rolls (bespoke symbol names, no shared identity/bookkeeping). The loader never needs to know whether a given .so is a plain C++ plugin or a compiled-Lua/SWIG shim - that disambiguation happens once, inside each plugin's own grunk_plugin_register, via state::begin_plugin or state::load_compiled_plugin respectively. Also adds grunk::plugin::load_script, a thin convenience wrapper over state::load_lua_plugin_file, so all three plugin kinds have an entry point in one place. No test coverage yet for load_native itself - that needs a real .so fixture, added next. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Every other plugin test stands in for its kind in-process (e.g. dynamic_plugin.cpp's luaopen_testplugin for a compiled Lua module) - but that can't exercise the loader's own dlopen/dlsym machinery, only the state-side primitives it eventually calls. Adds plugin_native_fixture, a tiny shared library built by tests/cpp/CMakeLists.txt exporting the grunk_plugin_info/grunk_plugin_register ABI, and plugin_loader.cpp, which dlopen's it via grunk::plugin::load_native for real and confirms its begin_plugin-registered type/function decorate correctly. Also covers a missing-library error and grunk::plugin::load_script. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Found while extending recipe_plugin.cpp's uses:-block coverage to a
begin_plugin-registered type: a type/function registered into a
namespace table (via register_type("Length", ns) or
register_function("twice", ..., ns)) serialized its constructor/call as
bare "Length.new"/"twice", not "cppplugin.Length.new"/"cppplugin.twice"
- unresolvable once read back, since it's actually only reachable
through the plugin's namespace. register_type/register_function/
modify_type had no way to know the dotted path to the table they were
given, unlike register_external_type/decorate_module_functions, which
already take an explicit qualifier for exactly this reason.
Adds the same explicit, opt-in `qualifier` parameter (default "",
so every existing flat call site is unaffected) to register_type,
modify_type and register_function, and threads info.name through it
wherever this pass's own plugin code registers into a namespace table.
This is a general, pre-existing gap in nested registration (not
specific to plugins - dynamic_module.cpp's
nested_type_keeps_dependency_tracking has the same shape and would hit
the same bug if it tried to serialize), just never exercised by an
existing test.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
RecipePlugin so far only exercised load_compiled_plugin. Since note_plugin backs plugins()/grunk.plugins identically for every kind (see the note_plugin/begin_plugin/load_lua_plugin_script commits), a recipe's uses: block should list a compiled-Lua plugin, a begin_plugin C++ plugin and a load_lua_plugin_script plugin the same way - and a begin_plugin-registered type should round-trip through YAML exactly like the existing compiled-plugin test already covers. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The library table still called it grunk::plugins (plural, wrong dependency: grunk::recipe instead of the actual grunk::dynamic), and the sneak-peek section was the only one with no code sample - it predated this implementation entirely. Fix the table row and add a minimal end-to-end example (a native C++ plugin's entry point plus grunk::plugin::load_native loading it), with a pointer to the other two kinds (load_compiled_plugin, load_lua_plugin_script/_file). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Found while migrating examples/cpp/cad_autodiff onto the new layer: #include <grunk/grunk.hpp> alone (the umbrella header's whole point, per core.hpp/dynamic.hpp/recipe.hpp) did not expose grunk::plugin at all - grunk.hpp had no GRUNK_WITH_PLUGIN branch, and nothing defined that macro for consumers in the first place. Mirrors the existing GRUNK_WITH_RECIPE mechanism: grunk_plugin now PUBLICly compile-defines GRUNK_WITH_PLUGIN (propagating to anything linking grunk::plugin, directly or via the grunk umbrella target), and grunk.hpp includes plugin.hpp when it's set. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
register_geoml now takes the namespace table + PluginInfo begin_plugin hands back, and registers everything (gp_Pnt, Geom_BezierCurve, bezier_curve, export_brep, and AD-only Standard_Real) under it with the qualifier that keeps serialization resolvable - both geoml_plugin.cpp (stage 2) and geoml_adolc_plugin.cpp (stage 3) now export the fixed grunk_plugin_info/grunk_plugin_register ABI instead of a bespoke per-plugin entry-point symbol, and main.cpp loads both via grunk::plugin::load_native instead of hand-rolled dlopen/dlsym. Recipe scripts updated for the resulting namespacing: gp_Pnt -> geoml.gp_Pnt, bezier_curve -> geoml.bezier_curve, export_brep -> geoml.export_brep, and the "ad" module's Standard_Real -> geoml.Standard_Real. Colon-call sites (curve:Value(...), point_at_half:X()/:Y()) are unaffected - native colon-call dispatch resolves via a C++-type-keyed registry, not Lua-side naming, so namespacing geoml's tables doesn't touch it. Verified end-to-end against a local grunk checkout (not yet on grunk-dev/grunk's main, which this example's CMakeLists.txt FetchContents from): all three stages produce identical output to before the migration, and the written recipe's uses: block now correctly lists "geoml". Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Moves the SWIG-bridging work (register_external_type + the __tostring metatable patch) out of main.cpp and into a proper plugin shim, plugins/adtl/adtl_plugin.cpp, which links directly against the prebuilt adtl.so and exports the same fixed grunk_plugin_info/grunk_plugin_register ABI geoml_plugin.so does - main.cpp now loads it via grunk::plugin::load_native uniformly, with zero SWIG-specific code left in application code. An application loading this plugin only ever sees PluginInfo + grunk::state, same as any other kind. This also let ADOL-C drop out of the main project entirely: main.cpp no longer includes adolc/adtl.h or links libadolc directly (both were vestigial - nothing in this file ever used adtl:: types in C++), and the ADOLC_BASE_DIR/ADOLC_INCLUDE_DIR/ADOLC_LIB_DIR find_library/find_file block is gone from CMakeLists.txt along with its pixi.toml configure flag - ADOL-C is now confined entirely behind adtl.so and, from there, behind adtl_plugin.so, the same way OCCT/geoml is confined behind the geoml plugins. adtl_plugin.so doesn't need it either: adtl.so already carries its own libadolc dependency, resolved transitively at load time. Verified end-to-end: all three stages produce identical output to before, including stage 1's serialized adtl.adouble round-trip. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Replaces the "dlopen'd... a stand-in for grunk's still-unwritten runtime plugin loader" framing (no longer true) with a description of the real grunk::plugin::load_native mechanism both plugins now use, adds adtl_plugin.so to the Project Structure section, fixes the ADOL-C prerequisites section's now-dead pixi.toml/ADOLC_BASE_DIR cross-reference, and updates the Stage 3 walkthrough's Lua snippets (gp_Pnt.*, Standard_Real.*, export_brep) to their namespaced geoml.* form. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
load_native was pure POSIX (<dlfcn.h>: dlopen/dlsym/dlerror) - it would not even compile on Windows. Splits the native-library-loading and symbol-lookup primitives into a POSIX branch (unchanged) and a Windows branch (LoadLibraryW/GetProcAddress/GetLastError+FormatMessage), behind a single native_handle/open_library/last_error_message/ find_symbol_checked seam so load_native's own logic stays identical on every platform. Also adds GRUNK_PLUGIN_EXPORT (grunk/plugin/loader.hpp): a plain extern "C" alone exports a symbol from a shared library by default on Linux/macOS, but not from a Windows DLL - GetProcAddress would find nothing without __declspec(dllexport) on the definition (or CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON on the *plugin's own* CMake project, which a third-party plugin build doesn't inherit from grunk's). Every existing native-plugin entry point (the cad_autodiff example's three plugins, tests/cpp's fixture) now uses this macro instead of a bare extern "C", so plugin source is portable across all three platforms without per-plugin CMake changes. Verified on Linux: full grunk test suite (168 tests) and cad_autodiff's three stages still pass/produce identical output. The Windows branch is unverified by compilation - no Windows toolchain available here - so treat it as reviewed-by-reading, not build-tested. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Keep the sneak-peek example consistent with the actual portable ABI (previous commit) instead of demonstrating the Linux/macOS-only extern "C" spelling. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Fills in the three plugin-related Sphinx sections that were previously "TODO"/"To Do" placeholders (or, worse, entirely commented-out prose describing a defunct PluginRegistry/IPlugin/conan-based design that no longer exists): - "Grunk plugins" / "Using grunk plugins": the three plugin kinds, PluginInfo/namespace-per-plugin contract, and how to load each kind (grunk::plugin::load_native for native/compiled, state::load_lua_plugin_file for pure Lua), plus a note that Python bindings don't expose plugin loading yet. - "Writing Plugins": a complete, accurate worked example of each of the three kinds (plain C++, compiled-Lua/SWIG shim, pure Lua), including GRUNK_PLUGIN_EXPORT and why it's needed for Windows portability, with a pointer to examples/cpp/cad_autodiff for the compiled-Lua case's full SWIG-bridging detail. - "Sharing Plugins": honestly marked not yet implemented, pointing at the working example instead of overclaiming. Also un-comments docs/code.rst's grunk::plugin Doxygen group (now pointing readers to state.hpp's plugin-authoring methods, documented under grunk::dynamic where they're actually declared) and adds grunk/plugin/ to docs/CMakeLists.txt's Doxygen input dirs - it was missing entirely, so `@ingroup plugin` tags were never being extracted. Fixes an unrelated pre-existing dangling anchor (_usage-dynamic-mode) noticed in the process. Verified: `pixi run -e docs build` succeeds; grunk::plugin::load_native/ load_script/GRUNK_PLUGIN_EXPORT and the new "Grunk plugins" tutorial both render correctly in the generated HTML, with no new Sphinx warnings (all remaining warnings are pre-existing and unrelated). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…enable PIC CI's Ubuntu Debug build failed: libplugin_native_fixture.so wouldn't dlopen, undefined symbol grunk::Recipe::Recipe(grunk::Recipe const&). Root cause: grunk::state's constructor (grunk/dynamic/state.hpp's init()) unconditionally registers RecipeCaller/Recipe::SubRecipe whenever GRUNK_WITH_RECIPE is on (the default) - so anything that instantiates grunk::state needs grunk::recipe's compiled Recipe.cpp linked in, not just grunk::dynamic's headers. At -O0 (Debug), GCC kept this code path (and its dependency on Recipe's out-of-line copy constructor) in the fixture's object file instead of optimizing it away, so the previously-Release-only-tested plugin_native_fixture (linked PRIVATE grunk::dynamic) surfaced it; the same gap exists in docs/usage.rst's documented `target_link_libraries(my_plugin PRIVATE grunk::plugin)` guidance for anyone building a plugin in Debug mode. grunk::dynamic can't link grunk::recipe itself (grunk::recipe already links grunk::dynamic - circular), so grunk::plugin, sitting above both, now links grunk::recipe when GRUNK_WITH_RECIPE is on (grunk::dynamic otherwise) - closing the gap for anyone following the documented "just link grunk::plugin" advice. Updated the test fixture to match. This then surfaced a second, mechanically unrelated issue: linking grunk::recipe's (and grunk's) static libraries into a shared plugin requires them to be position-independent, which grunk's own build only turned on for Python/scikit-build. Extended that condition to GRUNK_WITH_PLUGIN, so any shared plugin built as part of grunk's own tree (today: this test fixture) works without every downstream project needing its own `set(CMAKE_POSITION_INDEPENDENT_CODE ON)` - which examples/cpp/cad_autodiff's CMakeLists.txt already does for the same reason, independently. Verified: full test suite (168 tests) passes in both Debug and Release locally, and examples/cpp/cad_autodiff still builds and runs correctly (all three stages, unaffected). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Correctness fixes: - begin_plugin/load_compiled_plugin/load_lua_plugin_script now refuse to (re)start a plugin whose name is already loaded on the same state, instead of silently discarding or augmenting the existing namespace table. clear_module() is the sanctioned reload path (it now also forgets the plugin's identity via the new state::forget_plugin()). - grunk::plugin::load_native rolls a plugin's identity back out of state::plugins() if its own grunk_plugin_register throws partway through, and wraps the error with the plugin name/library path for context. - load_native no longer leaks the shared library handle when symbol lookup fails after a successful open. - CMakeLists.txt now fails configure with a clear message if GRUNK_WITH_PLUGIN=ON is combined with GRUNK_WITH_DYNAMIC=OFF, instead of an opaque "target not found" deep inside grunk/plugin/CMakeLists.txt. - Windows' last_error_message() no longer risks constructing a std::string from a null buffer if FormatMessageA itself fails. Design/usability fixes: - register_type/register_function/modify_type auto-infer their `qualifier` argument from a create_module-created table (begin_plugin's/ run_module_script's namespace tables) when left empty, so forgetting to pass info.name no longer silently produces an unresolvable serialized name. - Corrected docs/usage.rst's claim that a recipe's uses: block enforces plugin version, not just name - it only checks name, intentionally, since examples/cpp/cad_autodiff's geoml/geoml_adolc plugins rely on that leniency to swap variants under one recipe. Added a plugin-kind -> entry-point decision table to address discoverability of the four loading calls. README.md and docs/usage.rst updated to match; new/updated tests cover every behavior change above.
Second round of fixes from #275's review: - load_native no longer erases an already-loaded plugin's bookkeeping when a retry/double-load fails on a name collision. - forget_plugin now clears the namespace table it created (not just plugins() bookkeeping), so a rolled-back plugin's partial registration is actually gone. - clear_module also clears package.loaded, so load_compiled_plugin genuinely reloads instead of returning a stale cached module. - Starting a plugin under a name already used by a plain module now throws instead of silently clobbering that module. - modify_type refuses to overwrite the type registry with an invalid/missing usertype table instead of corrupting native colon-call dispatch. - load_compiled_plugin's namespace table now supports qualifier auto-inference; register_external_type rejects a name missing its namespace prefix instead of silently serializing an unresolvable one. - Guard the cad_autodiff example's CMP0169 policy set for CMake <3.30, and scope PIC to grunk's own targets instead of the whole build. - Fix a library-handle leak in load_native, an unchecked int->unsigned narrowing cast into an AD derivative buffer, and a SWIG __index override that masked lookup errors as nil. - Add GRUNK_PLUGIN_REGISTER: a plugin's exceptions are now caught on its own side of the dlopen boundary and reported as a plain error string, since unwinding a C++ exception across that boundary is unsafe unless the plugin and host share the exact same compiler/stdlib/library versions. All bundled plugins are migrated onto it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
forget_plugin() is now the fully general rollback primitive its doc comment already claimed to be: it clears the Lua package.loaded cache entry (previously only clear_module did) and removes any C++ types registered under the plugin's namespace from the type registry. load_lua_plugin_script now rolls back cleanly on a failed script instead of leaving a stale module that blocks retries. load_native closes the native library handle on every registration-failure path, not just symbol-lookup failures. Also trims the embedded CRLF from Windows error messages, deduplicates the qualifier computation shared by register_type/modify_type/register_function, and fixes the CMAKE_SOURCE_DIR vs PROJECT_SOURCE_DIR bug that forced downstream projects to manually copy grunkConfig.cmake.in. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Adds PluginInfo, state.plugins()/forget_plugin(), state.load_lua_plugin_script/ load_lua_plugin_file (pure-Lua plugins), and a grunk.plugin submodule mirroring grunk::plugin's C++ namespace with load_native/load_script, so Python code can load and use a prebuilt native (C++/SWIG) or Lua plugin, not just author dynamic scripts against one. begin_plugin/load_compiled_plugin are deliberately not bound - they require a C++ template type or a lua_CFunction entry point, neither expressible from Python; both plugin kinds are still reachable via grunk.plugin.load_native once built as a native shared library. Documents the Python-side API in docs/usage.rst alongside the existing C++ examples, and marks the new load_native test's dependency on a prebuilt C++ test fixture .so with a TODO to replace it once grunk has a real plugin distribution path (see "Sharing Plugins" in the docs - not yet implemented). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
begin_plugin/load_compiled_plugin now return a grunk::plugin_namespace proxy
instead of a bare sol::table: it remembers its own namespace table and
qualifier, so register_type/register_function calls against it no longer
repeat "ns, info.name" at every call site. register_external_type gets a real
behavior change, not just less typing - it auto-prefixes a short name
("MyClass" -> "my_plugin.MyClass") instead of requiring the caller to
concatenate the qualifier by hand, the way the raw state::register_external_type
still requires (it only validates a caller-supplied fully-qualified name).
plugin_namespace is implicitly convertible to sol::table (and exposes
.table()/[]) as an escape hatch for code that still needs the raw
state::register_type/register_function API, e.g. to override the namespace's
own qualifier.
Updates every begin_plugin/load_compiled_plugin call site to the new style:
examples/cpp/cad_autodiff's geoml/adtl plugins, the plugin test fixtures, and
the docs/README examples. Adds a regression test for the escape hatch
(PluginBegin.namespace_table_interoperates_with_raw_state_api) and updates the
compiled-plugin external-type test to exercise the new auto-prefixing.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
… crash Fixes several correctness issues found in review: begin_plugin/load_compiled_plugin had no rollback for a caller's own registration calls made after they returned (plugin_namespace is now RAII and rolls back on an in-flight exception); register_external_type's qualifier validation was skipped for untagged tables and could silently double-qualify a name; run_module_script could mutate a live plugin's namespace; the cross-plugin type registry had no ownership tracking; forget_plugin unconditionally cleared LUA_LOADED_TABLE entries it never populated; and load_lua_plugin_file narrowed paths in a way that mishandles non-ASCII paths on Windows. Also fixes the Windows CI crash in PluginLoader's rollback tests (SEH 0xc0000005): load_native was unloading a failed plugin's shared library immediately after forget_plugin, before Lua's GC had a chance to sweep any usertype metatable the plugin registered - if that metatable carries a sol2 finalizer, a later collection jumps into now-unmapped memory. load_native now leaves the library mapped on a failed load too, mirroring the same invariant already applied to a successful load. Bundles a few reuse cleanups (shared plugin-load helper, deduped rollback lambda, centralized qualifier-join formula) that fell out of touching the same functions. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Consolidates duplication that built up over the PR's many fix commits, found by a /simplify pass: - Drop m_module_types: it was a per-module type list that went stale the moment a different module re-registered the same C++ type, requiring forget_plugin to cross-check it against m_type_owner anyway. m_type_owner alone (scanned directly) is the single source of truth and can't go stale. - Extract find_plugin, shared by assert_plugin_name_free and name_occupied, which had independently re-implemented the same m_plugins scan. - Extract record_type_registration, shared by register_type and modify_type, which duplicated the same ownership-bookkeeping block verbatim - and, in the process, stop each from computing module_qualifier(table) twice (once directly, once again inside qualify()'s internal fallback). Pure refactor, no behavior change - full C++ (186) and Python (19) test suites pass unchanged. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Collaborator
Author
|
Closing this in favor of #277. The latter has a cleaner seperation of CAD-AD example and grunk library additions for the plugin interface |
joergbrech
added a commit
that referenced
this pull request
Sep 17, 2026
Second round of fixes from #275's review: - load_native no longer erases an already-loaded plugin's bookkeeping when a retry/double-load fails on a name collision. - forget_plugin now clears the namespace table it created (not just plugins() bookkeeping), so a rolled-back plugin's partial registration is actually gone. - clear_module also clears package.loaded, so load_compiled_plugin genuinely reloads instead of returning a stale cached module. - Starting a plugin under a name already used by a plain module now throws instead of silently clobbering that module. - modify_type refuses to overwrite the type registry with an invalid/missing usertype table instead of corrupting native colon-call dispatch. - load_compiled_plugin's namespace table now supports qualifier auto-inference; register_external_type rejects a name missing its namespace prefix instead of silently serializing an unresolvable one. - Guard the cad_autodiff example's CMP0169 policy set for CMake <3.30, and scope PIC to grunk's own targets instead of the whole build. - Fix a library-handle leak in load_native, an unchecked int->unsigned narrowing cast into an AD derivative buffer, and a SWIG __index override that masked lookup errors as nil. - Add GRUNK_PLUGIN_REGISTER: a plugin's exceptions are now caught on its own side of the dlopen boundary and reported as a plain error string, since unwinding a C++ exception across that boundary is unsafe unless the plugin and host share the exact same compiler/stdlib/library versions. All bundled plugins are migrated onto it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #235
Summary
Implements grunk's plugin system: a way to share reusable types/functions at runtime,
loaded into a
grunk::state. Three plugin kinds share one contract (a name + version,and everything the plugin provides registered under a namespace table keyed by that
name), so the dynamic scripting engine never needs to know which kind loaded a given
symbol:
state::begin_pluginreturns aplugin_namespaceproxy toregister_type/register_function/register_external_typeagainst.state::load_compiled_pluginloads a compiled Lua Cextension via
luaL_requiref.state::load_lua_plugin_script/load_lua_plugin_file, thin wrappersover the existing
run_module_script/run_module_file.A new
grunk::pluginlayer (grunk/plugin/loader.hpp/.cpp) adds a cross-platformnative loader (
dlopen/dlsymon Linux/macOS,LoadLibraryW/GetProcAddressonWindows) that
dlopens a shared library and invokes two fixed ABI entry points(
grunk_plugin_info,grunk_plugin_register), generated safely via aGRUNK_PLUGIN_REGISTER(fn)macro that keeps a plugin author's own exceptions fromever crossing the
dlopenboundary. NewGRUNK_WITH_PLUGINCMake option (defaultON, requiresGRUNK_WITH_DYNAMIC). Python bindings for all of it.examples/cpp/cad_autodiffis rewritten end-to-end as a 3-stage worked example(plain CAD → CAD with a plugin-supplied geometry backend → CAD with automatic
differentiation) that migrates its three prototype plugins onto this layer, proving
the design against something more realistic than the unit tests.
Size, and how to review this
This is a big diff (~5000 lines across 40 files) built up over ~45 commits and several
rounds of AI-assisted review. Roughly half of it is the example
(
examples/cpp/cad_autodiff/, ~2400 lines, entirely new files) and half is theactual library + tests (~2700 lines across 24 files). I'd suggest reviewing in this
order:
grunk/plugin/loader.hpp— read this first. It's short and defines the wholecontract (the ABI, the
GRUNK_PLUGIN_REGISTERmacro, why the exception-safetyboundary matters) that everything else honors.
grunk/dynamic/state.hpp, plugin-related additions — this is where the actualcomplexity lives: the three
load_*_pluginentry points,plugin_namespace,rollback-on-failure semantics, and the qualifier/naming mechanism. Worth the most
scrutiny — see "Things worth double-checking" below.
grunk/plugin/loader.cpp— the cross-platformdlopenimplementation andload_native's own rollback logic.tests/cpp/plugin_*.cpp,dynamic_plugin.cpp,recipe_plugin.cpp— readalongside (2), since the tests document the intended failure/edge-case behavior
better than the code alone.
python/_bindings.cpp— thin, low-risk mechanical bindings.examples/cpp/cad_autodiff/**— can be skimmed. It's a consumer of the API, notlibrary logic, and I could only verify it locally against a hand-built OCCT/ADOL-C/
geoml toolchain (not something CI or a quick clone can reproduce) — see "Testing".
docs/usage.rst,README.md— prose only.Things worth double-checking
plugin_namespaceis an RAII scope guard, not just a proxy. Its destructor rollsthe plugin's registration back (via
forget_plugin) if it's destroyed while anexception is propagating (
std::uncaught_exceptions()), so a caller's ownregister_type/register_functioncall throwing afterbegin_pluginreturneddoesn't leave a permanently half-registered plugin. Copy/move are deleted — it only
exists as a stack-local object. If this exception-safety contract for a public-facing
type feels like it should be documented or tested differently, flag it.
What review already found and fixed
This PR went through several rounds of dedicated review (both human and AI-assisted)
before this description was written. Rather than list every commit, here's what each
round was looking for and found:
loaded;
forget_pluginerasing an unrelated pre-existing module on a name collision;two plugins registering the same C++ type causing one to erase the other's live
registration on rollback;
run_module_scriptable to silently mutate a live plugin'snamespace.
serializing its constructor unqualified (unresolvable once a saved recipe is read
back in);
register_external_type's validation being skippable, or silentlydouble-qualifying a name.
SEH 0xc0000005) in twoPluginLoadertests: the nativeloader was unmapping a failed plugin's shared library immediately after rolling it
back, before Lua's GC had a chance to collect a usertype metatable the plugin
registered — if that metatable carries a finalizer, a later GC cycle jumped into
now-unmapped memory. Fixed by leaving the library mapped on a failed load too
(mirroring the same already-accepted trade-off on the success path). The root cause
is well-evidenced from static analysis but not confirmed with a live Windows
debugger — this needs a green Windows CI run to be fully confident.
bookkeeping structures on
statehad accumulated redundantly across rounds (aper-module type list that duplicated a reverse-ownership map; two near-identical
"is this name already a plugin" scans; a copy-pasted ownership-bookkeeping block in
register_type/modify_type). Consolidated with no behavior change.Testing
pixi run test_cpp), including new filesplugin_begin.cpp,plugin_lua_script.cpp,plugin_loader.cpp(the last exercisesload_nativeagainst a real, on-disk.so, not just an in-process stand-in) andextended
dynamic_plugin.cpp/recipe_plugin.cppcoverage.pixi run test_python).examples/cpp/cad_autodiffverified end-to-end locally against this branch (viaFETCHCONTENT_SOURCE_DIR_GRUNK): all three stages produce identical output to beforethe migration, including the closed-form AD check in stage 3. This required a
hand-built OCCT/ADOL-C/geoml toolchain per the example's own README and isn't
something CI (or a reviewer without that setup) can reproduce.
pixi run -e docs build, not just inspected.Known limitations
Plugin discovery/distribution (a package manager for grunk plugins) remains out of
scope, per #235's own deferral of that concern.
Heavily AI-assisted, including the review rounds that found the issues listed above —
flagged so reviewers calibrate scrutiny accordingly, especially for the Windows-only
path and the exception-safety design of
plugin_namespace.