Compile cache and cached headers¶
@cpp functions use the compile cache
by default. The first run builds the function; later compatible runs load the
compiled code. Kit authors can also use cppdef_cached for reusable C++ helpers.
For library headers, kits can use automatic precompiled-header caching. A precompiled header (PCH) saves the parsed headers for reuse. That section explains startup-hook installation and status checks. Kits register their header lists; the cache can build in the background and load on a later run.
The manual bt_kit PCH recipe is for CI or controlled runs that need to build and select an artifact explicitly. The later native C++ example shows how to move a frequently called tree action to C++ and avoid entering Python on each call.
Levels and validation¶
| Level | What it is | bt_kit today |
|---|---|---|
| L0 | JIT prototype, headers parsed by Cling at bringup | the default kit |
| L1 | frozen, header AST loaded from a prebuilt PCH, no per-run parse | this doc |
| L2 | native C++ emitted for a hot path | one leaf, below |
In the bt_kit measurement below, header parsing accounted for about 89% of bringup
time, and a prebuilt Cling PCH removed that parse step. The 16-test test-bt suite
passed on both L0 and L1 (pixi run -e bt test-bt); the L2 leaf is
differential-tested against its L0 Python original.
1. How the PCH works¶
Bringup cost is dominated by one call: cppyy.include("behaviortree_cpp/bt_factory.h")
JIT-parses the header stack (~0.83 to 0.91 s, measured). A prior probe
(docs/bt_kit/REPORT.md §5 Gap 8) showed that a ROOT/genreflex dictionary does not
remove header parsing. It supplies reflection and autoload metadata, not a parsed AST.
Cling still parses the header on first class use.
What does work is the mechanism cppyy already uses for its own std headers: a
Cling precompiled header. Cling loads the PCH named by the CLING_STANDARD_PCH
environment variable when the interpreter initialises. We build a PCH that bakes
the kit's headers on top of cppyy's standard-header set and point
CLING_STANDARD_PCH at it. On the frozen path the header AST is materialised from
the PCH at interpreter start; cppyy.include(...) becomes a lookup (~6 ms) instead
of a parse.
The build reuses cppyy's shipped machinery: rootcling -generate-pch over
etc/dictpch/allHeaders.h + allLinkDefs.h with the env's allCppflags.txt
(exactly what etc/dictpch/makepch.py does), plus the kit header and its include
path inserted. The artifact is a normal Cling PCH, ~48 MB.
Internal-linkage statics¶
The AST-only PCH carries a declaration for the header's internal-linkage statics
but the JIT never emits their definition, and the library's own copy is a
non-exported local symbol. So JIT-compiled glue that ODR-uses one fails to link.
For bt_kit there is exactly one: BT::UndefinedAnyType
(static std::type_index = typeid(nullptr) in safe_any.hpp, used by every
Any/PortInfo). The fix, applied only on the frozen path, emits one strong,
externally-visible definition under its exact mangled name so every JIT module
resolves to it (cppyy_kit/freeze.py::_FORCE_SYMBOLS). In L0 the live-parsed
header already defines it, so this glue is not applied there (a second definition
would clash). If a freeze of another header surfaces more such symbols, add them to
that per-kit table.
2. Build and use a PCH for bt_kit¶
This is the explicit/manual path, useful for CI or controlled runs. §8 describes the optional startup hook and background build.
pixi install -e bt
pixi run build # install the package (bt_kit + freeze module)
pixi run -e bt freeze-bt-build # build the PCH into build/freeze/ (~30 to 60 s)
# run anything with the frozen PCH active:
pixi run -e bt demo-bt-t01-frozen
pixi run -e bt test-bt-frozen # the SAME 16 tests, frozen
pixi run -e bt freeze-bench # L0 vs L1 numbers (§4)
To freeze an arbitrary script, wrap it with the launcher:
Why a launcher (the import-order rule)¶
CLING_STANDARD_PCH must be set before the first import cppyy, Cling binds
its PCH at interpreter init, and setting the variable afterwards is ignored
(measured: 911 ms, i.e. still parsing). Because import rclcppyy imports cppyy
transitively, you cannot set it from inside a kit. scripts/freeze/run_frozen.py
resolves the artifact without importing rclcppyy/cppyy, sets the environment, and
execs the target in the same process image, so the target's first cppyy import
already sees the frozen PCH. bringup_bt() warns if RCLCPPYY_FROZEN is set but no
frozen PCH is active (i.e. the launcher was bypassed) and falls back to JIT.
3. Artifact lifecycle¶
- Location:
build/freeze/bt_kit.pch.native.<cppstd>.<cppyy-cling-version>(e.g.…native.17.6.32.8).build/is gitignored, never commit the PCH or the L2.so(they are large and environment-specific). - Env-version-matched: the filename carries the C++ standard and the
cppyy-cling version. A PCH is only valid for the Cling it was built with; a
version bump changes the tag, so the launcher will not select a stale artifact and
freeze.artifact_path()will not find one → the launcher runs JIT and prints how to rebuild. - Rebuild when: cppyy-cling or behaviortree_cpp changes version, or the kit's
header set changes. Just rerun
freeze-bt-build. - If no PCH is built: the kit uses JIT parsing. The PCH only reduces startup latency; it is not required for correctness.
4. Measurements from this shared machine¶
pixi run -e bt freeze-bench. Bringup is a once-per-process cost, so each sample
is a fresh subprocess.
| Bringup stage | L0 JIT | L1 frozen | speedup |
|---|---|---|---|
include(bt_factory.h), the parse |
~890 ms | ~6 ms | ~140× |
load_library |
~6 ms | ~5 ms | 1.2× |
cppdef(glue) |
~50 ms | ~78 ms | 0.6× |
| bringup total (through cppdef) | ~950 ms | ~90 ms | ~10.7× |
| first factory + register + tick (first-use JIT) | ~690 ms | ~690 ms | 1.0× |
end-to-end t01_first_tree.py (process start→exit) |
~1.9 s | ~1.1 s | 1.7× (−0.8 s) |
The freeze removes the ~0.83 to 0.91 s header parse. These costs remain:
load_library(~5 ms) and thecppdefC++ glue (~78 ms, slightly higher frozen, because the glue's template instantiations are JIT-emitted fresh rather than reused from the live parse);- first-use JIT (~0.69 s, unchanged L0↔L1), the subject of the section below.
First-use JIT and warmup()¶
The first tree build pays a one-time, per-signature cost as cppyy JIT-compiles a call wrapper for each C++ signature it crosses. Measurements:
| First-use step | cost | what it is |
|---|---|---|
std.function[sig] (type) |
~3 ms | template lookup, cheap |
| wrap the Python callable → thunk | ~126 ms | cppyy generates the Python↔C++ thunk |
registerSimpleAction(name, fn, ports) |
~299 ms | cppyy generates the call wrapper for that C++ method |
| stateful register (3 hook sigs) | ~342 ms | same, for the shim's signatures |
| 2nd registration (same sig) | ~50 ms | wrapper cached; residual per-call codegen |
Can cppyy 3.5 reduce this cost? We tested these options:
EXTRA_CLING_ARGS=-O0vs-O1vs default produced identical results: first register ~401 ms and tick rate ~1.41 M/s in all three cases. The cost comes from Clang front-end template instantiation. Changing the LLVM optimization level did not change these measurements.- A PCH cannot help: the frozen path pays the same ~690 ms (table above), and the cost comes from call-wrapper code generation triggered by the Python call. An AST-only PCH does not contain these wrappers. Pre-instantiating the wrapper types in the PCH would add AST, not the per-call thunk.
- cppyy 3.5 has no disk cache for per-call wrappers; its C++ modules cache stores
header ASTs.
warmup()moves wrapper compilation to initialization. To remove wrapper calls from a hot path, compile the leaf to L2 native code withregisterFromPlugin(§5).
bt_kit.warmup() exercises every wrapper signature on a throwaway factory during
initialization (see COMMON_PATTERNS §15). Results for the t01 workload on this
machine:
| bringup | warmup (init) | time-to-first-tick | end-to-end | |
|---|---|---|---|---|
| L0, no warmup | ~920 ms | - | ~678 ms | ~1.80 s |
| L0, warmup | ~905 ms | ~930 ms | ~98 ms | ~2.14 s |
| L1 frozen, no warmup | ~85 ms | - | ~667 ms | ~1.01 s |
| L1 frozen + warmup | ~85 ms | ~920 ms | ~94 ms | ~1.36 s |
The first live tick drops from 678 ms to 98 ms. Wrapper compilation moves into
initialization. For t01, end-to-end time rises because warmup() also initializes the unused
stateful path (~340 ms). For a tree that uses all node kinds, the totals converge.
warmup() moves work to startup and does not change steady-state throughput.
Observed cold-start result with freeze and cache. In the bt_kit benchmark below,
the compatible PCH and compiled wrapper artifacts were already available: the
freeze-plus-cache run took ~0.43 s end-to-end, compared with ~1.77 s for the JIT
baseline. A cache miss still requires building the artifact. warmup() moves wrapper JIT to
initialization when no compatible compiled artifact is available.
rclcpp header measurement¶
The same method was used for rclcpp/rclcpp.hpp (the rclcpp bringup's dominant
parse cost) on the same shared host:
| L0 JIT | L1 frozen | observed cold/warm ratio | |
|---|---|---|---|
include("rclcpp/rclcpp.hpp") |
~1.71 s | ~6 ms | ~290× |
Both header sets loaded from their PCH in roughly 6 ms in this run. This shows that the mechanism also works with the rclcpp headers. The rclcpp observation measures parse elimination only; a full frozen rclcpp bringup would need its own force-symbol pass and is out of scope.
Compile cache reduces first-use JIT time¶
The ~0.7 s first-use call-wrapper JIT can be moved to initialization with
warmup(). cppyy 3.5 does not provide a way to reduce its compilation time. The
compile cache compiles the crossing once into a shared library and loads it on later
runs. This avoids generating the wrapper at runtime.
The API is cppyy_kit.cppdef_cached (see COMMON_PATTERNS §23).
The wrapper JIT is Clang front-end codegen. On a compatible cache hit, loading the
.so replaces that code generation with a ~ms symbol call. Two things are cacheable:
- kit glue (
makePorts, the stateful shim, …), definitions we control, split into a bodiless-declarations header (cheap tocppdefon a hit) and the.so(the definitions). Cling emits any body it can see, so the fast path must give it only declarations. - the boundary crossing itself, the ~0.4 s comes from the
std::function<NodeStatus(TreeNode&)>thunk and theregisterSimpleActioncall wrapper. Build both in compiled code: a trampoline.sothat constructs thestd::functionwrapping the Python callable and does the registration, converting the C++TreeNode&to the Python node proxy with cppyy's publicCPyCppyy::Instance_FromVoidPtr. All the heavy instantiation then happens at.sobuild time.
For one isolated crossing, the bare std::function thunk and one
registerSimpleAction call took ~414 ms with JIT and ~16 ms with a cached library.
bt_kit adopted end-to-end (t01: 4 leaves in a Sequence, cold subprocesses, this
machine, pixi run -e bt bench-cache-bt[-frozen]):
| config | first register (first-use) | first tick | end-to-end wall |
|---|---|---|---|
| L0 JIT baseline | ~233 ms | ~8 ms | ~1770 ms |
| L0 + cache (run ≥2) | ~60 ms | ~5 ms | ~1200 ms |
| frozen JIT baseline | ~278 ms | ~9 ms | ~970 ms |
| frozen + cache (run ≥2) | ~62 ms | ~5 ms | ~425 ms |
| cached run 1 (miss) | - | - | +~2 s .so compile |
With compatible artifacts available, freeze + cache compose: the PCH removes the
~0.89 s parse, and the cache removes much of the first-use wrapper JIT. In
these runs, end-to-end time was ~1.77 s for L0 JIT and ~0.43 s for frozen + cache
(~4.1×); first-register time was ~233 ms and ~60 ms. The cache miss took ~2 s to
compile the .so. A kit can include a prebuilt artifact with
cppyy_kit.cache.prebuild.
Residual time (~60 ms). The cached .so contains the std::function thunk and
the registerSimpleAction/registerStateful wrapper. cppyy still JIT-generates a
call wrapper the first time Python calls the trampoline entry points
(register_py_action, makePorts). This cppyy-generated wrapper is not part of the
cached library. It has a simpler signature and took ~60 ms, compared with ~233 ms for
the uncached first register. Its cost was the same with and without the .so cache.
PCL measurement. pcl_kit.voxel_downsample compiles a
pcl::VoxelGrid<PointXYZ> template into the kit's .so. The filter's first-use time
fell from ~594 ms to ~5 ms. In the d02 benchmark, frame 0 (from_msg to voxel to
to_msg) fell from ~681 ms to ~88 ms (~7.7×). In bt, the cache compiles a callback
trampoline instead.
Cache scope. This caches the glue and trampolines the kit authors. cppyy's
on-demand template instantiations triggered by arbitrary user calls (e.g.
node.getInput[T](key) for a new T), and the call wrappers cppyy makes to reach
the kit's entry points, are not cached by this. Artifacts are env-version-tagged and
gitignored. Source, declarations, options, include paths, library paths and the
cppyy version tag participate in the compile key. Included header contents and
compiler/runtime replacements are not checked automatically. Clear the compile
cache after those changes and restart the process. When the compiler/CPyCppyy toolchain
is unavailable the kit falls back to the JIT registration path (a one-time notice),
so the cache is a pure optimisation, never a correctness dependency.
5. L2: compile one leaf to native C++¶
t01's ApproachObject Python leaf, emitted as a native BT::SyncActionNode in a
compiled plugin .so and registered JIT-free via
factory.registerFromPlugin(...) (the engine dlopens it; no cppyy, no Python in
the tick path).
pixi run -e bt freeze-l2-build # compile scripts/freeze/l2_approach_object.cpp -> .so
pixi run -e bt freeze-l2-diff # differential test vs the L0 Python leaf
Differential result (same tree XML, same node ID):
- Correctness: identical stdout (
ApproachObject: approach_object) and status (SUCCESS). The differential test checks behavior at both levels. - Tick rate (single-leaf tree, SUCCESS/tick, no I/O): L0 Python leaf ~0.55 µs/tick vs L2 native ~0.20 µs/tick, ~2.7× faster, i.e. the Python↔C++ boundary cost per leaf is removed.
The L2 implementation is hand-written. It shows that a Python leaf (L0) can have
a native C++ equivalent (L2) that passes the same test and runs in the engine tick
path. Registration still crosses cppyy once
(registerFromPlugin), but the leaf executes as native code every tick.
6. Files¶
| File | Role |
|---|---|
cppyy_kit/freeze.py |
artifact path/version tag, frozen-path detection, force-symbol glue |
scripts/freeze/build_bt_pch.py |
build the frozen PCH (rootcling -generate-pch) |
scripts/freeze/run_frozen.py |
launcher: set CLING_STANDARD_PCH before cppyy, exec target |
scripts/freeze/bench_freeze.py |
L0-vs-L1 numbers |
scripts/freeze/l2_approach_object.cpp / build_l2_node.py / l2_diff.py |
L2 leaf + build + differential test |
bt_kit/tests/test_bt_freeze.py, bt_kit/tests/_freeze_helper.py |
frozen-path tests (parse eliminated + correct) |
bt_kit/bt_kit/__init__.py |
bringup_bt() applies force-symbols when frozen; bt_kit.frozen() |
7. Limitations¶
- The PCH is a startup-latency optimisation for the parse only; the first-use
JIT of cppyy call wrappers (~0.7 s for t01) is not removed by the PCH.
warmup()moves it off the first live call. The compile cache avoids much of it (§4, "The compile cache"): freeze + cache compose into the best-case cold start (~1.77 s → ~0.43 s), leaving a small ~60 ms residual (cppyy's call wrappers to the kit's own trampoline entry points). - Artifacts are Cling-version-specific and must be rebuilt (never committed) on any cppyy-cling / library version change.
- Freezing a new header may surface further internal-linkage symbols to force (§1); the failure mode is a clear "unresolved while linking" error naming the symbol.
- The manual launcher must run before any cppyy import (import-order rule, §2);
the zero-config auto-PCH (§8) removes this constraint by activating from a startup
.pthbefore any user import.
8. Automatic PCH setup (cppyy_kit.autopch)¶
§1 to §4 prove the mechanism but ask the user to build an artifact and launch through a
wrapper. cppyy_kit.autopch can install a startup hook and schedule a PCH build on
first use. Once a compatible artifact is available, the hook can select it in later
processes using the same environment and cache directory. A missing or disabled cache
uses JIT parsing.
Startup hook activation¶
Cling binds its PCH when the interpreter first imports cppyy, so CLING_STANDARD_PCH
must be set before that. When enabled and installed, a .pth file in the environment's
site-packages activates the hook during normal Python startup, before user imports.
This allows the hook to set the variable before cppyy initializes Cling.
- The
.pthrunscppyy_kit._autopch_boot.activate()(installed alongside it as a standalone, stdlib-only module).activate()reads this environment's manifest and, if a matching PCH exists, pointsCLING_STANDARD_PCHat it and sets a marker. It is silent, costs a few milliseconds (it importscppyy_backendonly, to read the cppyy version for the cache key, not cppyy itself), respectsCPPYY_KIT_NO_AUTOPCH=1and any already-setCLING_STANDARD_PCH, and never raises (a broken bootstrap would otherwise print on everypythonstart). cppyy_kitself-installs the.pthon first native use (a one-time notice), and refreshes it if out of date.python -m cppyy_kit.autopch --uninstallremoves it;--statusshows install + cache state.- Native initialization (
autopch.setup()) reads the marker and prints a user-facing line,cppyy_kit: Cling PCH loaded from <path>. Before the.pthexists,setup()can activate from the manifest if cppyy has not yet been imported.
A kit declares the headers it parses via the hook
called at bringup around its cppyy.include(...). When the active PCH already bakes
those headers this is a no-op; otherwise, the header set is added to the environment
manifest and a detached background build is scheduled at interpreter exit
(lockfile-guarded and written atomically). A later run can use it after a successful
build, provided it uses the same compatible environment and cache. rclcpp_kit's
bringup_rclcpp() registers rclcpp/rclcpp.hpp +
rcl_interfaces/msg/parameter_event.hpp with every ament include dir; no
force-symbols are needed for rclcpp (verified: the full test-rclcpp suite passes with
the PCH active). The kit modules import cppyy_kit before cppyy as a fallback for
environments where the .pth could not be installed (for example, read-only
site-packages).
Cache layout, ${XDG_CACHE_HOME:-~/.cache}/cppyy_kit/pch/¶
| File | Role |
|---|---|
<env-tag>.manifest.json |
the accumulated baked-header set, include paths, and the current header-set's pch_key for this env; <env-tag> hashes the env prefix and the cppyy/backend versions |
<pch-key>.pch |
the artifact; <pch-key> hashes the same env material and the header set, so any change is a cache miss (never a silent ABI mismatch) |
<pch-key>.pch.json |
metadata (env tag, headers, version) used to group artifacts for pruning |
<pch-key>.pch.log |
the background build's output (and the prune summary), for diagnosis |
<pch-key>.pch.lock |
held while a build is in flight (prevents double-builds) |
A rebuilt env or an upgraded cppyy changes the tag/key, so a stale artifact is
not found and the run falls back to JIT, the same behavior as the manual PCH (§3). These artifacts are not committed. Pruning: after each successful build the cache is
trimmed to the newest few PCHs per environment (plus any still referenced by a live
manifest). It also removes orphaned sidecars, stale locks, and manifests for deleted
environments. Prune manually
with python -m cppyy_kit.autopch --prune.
rclcpp bringup measurements¶
Each row is a fresh process; the "header parse" is the rclcpp C++ headers loaded (…)
line, bringup is the whole bringup_rclcpp() call.
| Run | header parse | bringup total | notes |
|---|---|---|---|
| cold (auto-PCH disabled) | ~1.9 s | ~1.91 s | baseline JIT |
| first run (empty cache) | ~1.9 s | ~1.92 s | JIT + building … printed; build scheduled |
| warm run (PCH loaded) | ~0.0 s | ~0.06 s | Cling PCH loaded from … printed |
The header parse dropped from ~1.9 s to ~0 s in this run. The raw cold/warm bringup ratio was ~30×. These measurements are from one host and may differ elsewhere. As with the manual freeze, this removes the parse only; cppyy's first-use call-wrapper JIT is a separate cost (see §4, the compile cache).
Files¶
| File | Role |
|---|---|
cppyy_kit/_autopch_boot.py |
standalone, stdlib-only bootstrap; activate() runs from the .pth and is the single source of the cache-path/key logic (shared with autopch) |
cppyy_kit/autopch.py |
setup(), register_pch_headers(), .pth self-install/uninstall, generate_pch(), at-exit scheduler, prune(), the python -m CLI |
cppyy_kit/autopch_build.py |
detached worker that builds a PCH from a manifest, prunes, and releases the lock |
cppyy_kit/tests/test_autopch.py |
hermetic tests (keys/invalidation, override, .pth install/uninstall/opt-out/crash-proofing, manifest union, scheduling, pruning, cross-process pickup) + an opt-in real-build test |
9. Debugging: turning the caches off¶
cppyy_kit keeps two independent caches, and both are pure optimisations you can switch off when a run misbehaves and you want to rule caching out. They cover different costs and have different switches:
| Cache | What it removes | Artifacts | Turn it off with |
|---|---|---|---|
| auto-PCH (§8) | the header parse at bringup | ${XDG_CACHE_HOME:-~/.cache}/cppyy_kit/pch/*.pch |
CPPYY_KIT_NO_AUTOPCH=1 (env, before launch) |
compile cache (§4, cppdef_cached) |
cppyy's first-use call-wrapper JIT (kernel .sos, incl. @cpp) |
$CPPYY_KIT_CACHE_DIR or <cwd>/build/cppyy_kit_cache/ |
CPPYY_KIT_NO_CACHE=1 (env) · cppyy_kit.disable_caching() (runtime) · cached=False (per call) |
Source and configuration changes included in a cache key cause a cache miss. The compile cache does not detect changes to included header contents or the compiler/runtime automatically. Use these switches when investigating a stale artifact, a miscompiled kernel, or stepping through source code.
Decision tree¶
-
Bringup is slow, or a header change isn't taking, or a symbol resolves wrong at parse time → suspect the PCH. Launch with
CPPYY_KIT_NO_AUTOPCH=1to run entirely on the JIT path (the.pthandsetup()both honour it, no PCH is bound or built). If the JIT path works, the baked PCH is stale: rebuild it by pruning (python -m cppyy_kit.autopch --prune) or remove the startup hook entirely (python -m cppyy_kit.autopch --uninstall).--statusshows what is installed and how many PCHs are cached. Because the PCH binds at interpreter start (via the.pth), disable it with the environment variable or CLI. There is no runtime toggle because Cling binds the PCH before Python code runs. -
A kernel gives wrong results, or a
@cpp/cppdef_cachededit isn't taking, or you need to step into the source → suspect a stale kernel.so. Three bypasses, all makingcppdef_cachedbehave exactly like a plain in-memorycppyy.cppdef(code)(no.soread, no.sowrite): - Per call:
@cpp(cached=False)orcppyy_kit.cppdef_cached(..., cached=False)This affects only the specified call. - Runtime, process-wide:
cppyy_kit.disable_caching()(undo withenable_caching()), or the scopedwith cppyy_kit.caching_disabled(): .... - Whole process, before import: set
CPPYY_KIT_NO_CACHE=1in the environment.
If the run is then correct, the cached .so was stale; remove it (below) so the next
cached run rebuilds it.
Artifact locations and removal¶
- Compile cache.
$CPPYY_KIT_CACHE_DIRif set, else<cwd>/build/cppyy_kit_cache/, under a version-tagged subdir. Everything there is regenerable and gitignored.cppyy_kit.clear_cache()deletes every artifact in the active (version-tagged) dir and returns the count;cppyy_kit.cache_info()lists what's there;cache_dir()prints the path. You can also delete the directory by hand. A missing.sois treated as a cache miss. (Already-loaded.sos stay mapped in the running process; the switches above only affect later calls; restart the process to release the loaded artifacts.) - auto-PCH.
${XDG_CACHE_HOME:-~/.cache}/cppyy_kit/pch/.python -m cppyy_kit.autopch --prunetrims to the newest per environment (keeping any a live manifest references); deleting the dir is safe (the next run falls back to JIT and reschedules a build).
The compile cache keys on the cppyy version tag and supplied source/options. Clear it after replacing included headers or the compiler/runtime. The PCH has its own environment/header key described in §8. Use these switches to bypass either cache while debugging.