1.3 How a route runs: core to bindings
A route starts as builder calls in robot code, crosses the C ABI as two handles,
runs inside the Rust core’s auto runtime, and comes back each loop as three
speeds, a status block and a list of fired hooks. Read this chapter before a
change that spans a binding and the core, or when a bug could be on either side
of rust/core/src/ffi.rs.
The deep references stay where they are: Architecture for each core module, the FFI contract for ABI rules and every block layout, Wrapper policy for cross-language parity, and Repository layout for where each component lives.
The path at a glance
robot code (Java / Python / C++)
Composer.startAt(...).to(...)... authoring on the host, bounds checked by the core
first use -> freeze validate through tempo_authoring_query_v1
build runtime tempo_config_new_v1 + tempo_route_new_v1
-> tempo_auto_new_v2 (or tempo_auto_new with JSON)
disabled tempo_auto_warm, tempo_auto_warm_later_legs_v1
every loop tempo_auto_tick_status(pose, clock, host answers)
<- speeds[3], fired[(segment, kind, index)], status[27]
hooks host runs the commands the fired triples name
notifications tempo_auto_notify_* when a hook or hand-off ends
end tempo_auto_free
---------------------------------------------------------------- C ABI
rust/core: ffi.rs -> auto_runtime::AutoRuntime -> replanner::Replanner
-> follower -> output_limit::OutputLimiter
planning jobs -> worker_pool (urgent + background workers)Commands, subsystems and predicates never cross the boundary. The core sees predicate answers as bits and refers to hooks by index, and each binding resolves those indexes against its own copy of the route.
Authoring in Java
Java is the reference binding (Java is the spec).
A robot program calls Tempo.configure(config) once on its main thread, and that call
(java/src/main/java/com/tempo/Tempo.java) does four things in order:
NativeLoader.ensureLoaded()openslibtempo_core(see Loading the native library).TempoNative.INSTANCE.tempo_pool_start_v1()starts the core’s planning workers from the main thread, so they inherit its scheduling (Starting the planning workers).com.tempo.internal.Background.start()starts the binding’s two helper threads, after the workers.- The game pack is selected and loaded (
tempo_load_pack), the field is prebaked for both alliances (prebakeField), and registered autos prebuild (AutoRegistry.prebuildAll()).
Composer (java/src/main/java/com/tempo/Composer.java) is a mutable builder.
startAt(...) names a fixed start, and Tempo.to(...) starts from the live robot pose
and names the first target. Each to(...) opens a leg, and options written after it
bind to that open leg. While building, the builder asks the core authoring query
(java/src/main/java/com/tempo/internal/AuthoringQuery.java) to check start and
target bounds and .cross() ids, but the route itself reaches the core runtime only
at the first use.
Freeze
The first use of a Composer calls the private Composer.freeze(), which runs
prepareDefinition() inside a FreezeTransaction:
closeOpenLeg()commits the last leg.CoreAuthoring.validate(...)sends anop: "route"request throughAuthoringQuerytotempo_authoring_query_v1. The core’sauthoringmodule returns aproblemsarray, and the binding throws the first one with the exception typetests/fixtures/api/authoringRefusals.jsonassigns (Authoring queries).- Hooks are prepared (
prepareHooks), per-leg replanning config is folded in (resolveLegReplanning), and extensions are inferred (ExtensionInference.inferSegmentExtensions). warnLimitsAboveFullprints one console line when a leg asks for more thanSpeed.FULL. The core’sresolvelowers each such limit toSpeed.FULL’s.
The result is an immutable Definition, and every later occurrence of the Composer
builds fresh runtime state from it. A freeze also fails on an unknown .cross()
id or a differential leg with no track width, and both come back as authoring
problems.
Building a runtime
The core takes a route in two halves (Route configuration):
| Half | Java owner | Core reader | Schema |
|---|---|---|---|
| Robot configuration | com.tempo.internal.ConfigHandle | tempo_config_new_v1 -> drive_model::ResolvedConfig | tempo.route-config/v1 |
| Authored route | com.tempo.internal.AuthoredRoute (RouteSerializer writes it) | tempo_route_new_v1 -> auto_runtime::RouteTemplate | tempo.authored-route/v1 |
A configuration handle is written once per config value and an authored route
once per frozen definition. NativeAutoRuntime.create(config, route, ...) passes
both to tempo_auto_new_v2 with the pack, the runtime alliance, a planning mode
and a plan wait. In Rust, auto_runtime::resolve fills each leg’s Speed level,
angular caps and track width from the configuration, and AutoRuntime::new
builds the runtime. tempo_route_json_v1 writes the serialized
tempo.sequencing-route/v1 the pair stands for, and recorded traces and
tempo_auto_new use that JSON form. problem_code maps a refusal back to an
authoring exception type.
Both handles are Arc::into_raw pointers and follow the pack’s ownership rules
(Pack lifetime). Java frees
them through a Cleaner (ConfigHandle.CLEANER).
Warm-up
While the robot is disabled, tempo_auto_warm caches the first leg’s plan
without starting clocks or firing hooks, and the warm-up plans later planning
units ahead (AutoRuntime::warm_later_groups). A route whose first leg will not
start at its authored start, such as a Setlist’s later route, warms its later
legs alone through tempo_auto_warm_later_legs_v1. The rules are in
Route sequencing.
The tick
NativeAutoRuntime.tick (java/src/main/java/com/tempo/NativeAutoRuntime.java)
runs once per robot loop:
- It asks robot code for the current leg’s answers: the
endWhenpredicate,Condition.whentrigger bits, aim-arming bits, and supplier-backed aim values (two doubles per aim, NaN where the supplier yielded null).TreeSlotsasks each predicate once per loop. - It calls
TempoNativeFast.tempo_auto_tick_status(...)with the pose, the clock, those answers (aim targets go in a separateaimSuppliedinput array) and three caller-owned output buffers: 3 speeds, up to 64 fired triples (FIRED_CAP), and the 27-slot status block (STATUS_LEN). - A return of
-2means the tick moved into a leg that reads host answers, so the loop asks again for the new leg and repeats the call at the same clock. - A return of
-1means failure. The core has already written zero speeds and settempo_last_error, and Java reads that string at once and latches it astickFault. - A nonnegative return counts the fired hooks queued.
resolveFiredmaps each(segment, kind, index)triple to the command in the route’sComposer.SegmentSpeclist. Kinds are 0 runDuring, 1 trigger, 2 fail case, 3 arriveWith and 4 window end. - For a leg with a custom controller or filter, the binding reads
tempo_auto_control_reference, computes its own output, and reports the final command withtempo_auto_record_output_v1.
The returned speeds are robot-relative and go to the drivetrain’s velocity
callback. Hooks that end are reported back through tempo_auto_notify_*
(blocking done, arrived, failed, hand-off done). Events queued by those
notifications are pulled by drainFired. The status block is cached until the
next tick or notification, and The tick’s status block
lists the slots and phase codes.
Inside the core on one tick
ffi::auto_tick_impl checks the handle, rejects a non-finite clock (returns 0
with zero speeds), copies the host answers into the handle’s
AutoTickInputs, and calls AutoRuntime::tick_with. That function:
- Reads the tick’s pose through
pose_after_reset, which reports no pose while the route waits for an odometry reset to show (AutoRuntime::await_start_reset), and measures the drivetrain’s lag (measure_drive_lag). - Runs
tick_in_loop, which advances phases (NOT_STARTED,PRE_BLOCKING,DRIVING,POST_BLOCKING,WAITING,DONE,CANCELLED,HANDED_OFF) until it returns a command orAutoTick::NeedsFreshInputs. A driving leg goes throughtick_driving, which asks the leg’sReplannerfor its command. - Evaluates route state trees against the trigger bits.
- Passes the command through
limit_output(theOutputLimiterinrust/core/src/output_limit.rs) and records it in the sent history.
Replanner::compute (rust/core/src/replanner.rs) checks drift triggers and
rate limits, polls a pending worker replan, blends from the previous follower
after a replan, and asks the active PathFollower for feedforward plus feedback
(rust/core/src/follower.rs). The output limiter then bounds speed, the step
from the last command (the friction ellipse) and the turn rate by the
drivetrain’s ceilings. See
follower,
output_limit and
replanner.
A panic is caught at the boundary. A panic in a worker or in the status write
poisons the handle, and every later tick returns -1 with zero speeds until the
host frees it.
Planning off the loop
worker_pool.rs runs every plan a robot runtime needs on threads started once per
process. In PlanningMode::Robot (the default) no tick plans. The tick that needs
a plan waits up to PLAN_WAIT_BUDGET (1.5 ms, auto_runtime.rs), and a leg whose
plan has not arrived holds, coasting within its acceleration limit. In
PlanningMode::Replay, selected by config.planningMode or the
TEMPO_PLANNING_MODE environment variable, the tick waits for the plan so traces
repeat tick for tick.
Jobs carry a Lane:
| Lane | Work | Runs on |
|---|---|---|
Now | a leg’s plan, junction negotiation, the warm-up’s first-leg plan | the urgent worker |
Ahead | look-ahead plans for later legs | background, promoted when waited on |
Soon | replans | background, promoted after the follower misses it for a couple of loops |
Background | plan-graph bakes | background |
Spare | warm-up plans of later legs | background, before bakes in bursts of at most eight |
The control thread hands a job over with a channel send and waits on the job’s
own flag with a timeout (Ticket::wait). A dropped Ticket cancels its job.
Console lines go to a chore thread (say), and finished plans go to a reclaimer
thread (retire), so the loop never prints or frees a large plan.
Threading model
| Thread | Owner | Scheduling on Linux |
|---|---|---|
| Robot loop | robot program | whatever robot code sets |
| Urgent planning worker | worker_pool | SCHED_BATCH, nice 0 (run_beside_the_loop) |
| Background planning workers | worker_pool | SCHED_BATCH, nice 19 (run_below_the_loop); one on three cores or fewer, two otherwise |
| Chore and reclaimer threads | worker_pool | below the loop |
Field bake threads (tempo-bake, one per tempo_auto_prebake_field call, ending with the bake) | ffi | below the loop (spawn_below_the_loop) |
Binding urgent helper (TempoUrgent in Java and C++) | binding | nice 0 via tempo_run_beside_the_loop |
Binding background helper (TempoBuild in Java and C++) | binding | nice 19 via tempo_run_below_the_loop |
Binding console thread (TempoConsole in Java, C++ and Python) | binding | nice 19 via tempo_run_below_the_loop |
A Linux thread can lower its priority without privilege but cannot raise it, and
a new thread inherits its parent’s scheduling, so each binding starts the
pool on the main thread before any helper exists. Work a thread comes to wait on
moves to the urgent class, and no thread is ever raised. Java’s helpers are in
com.tempo.internal.Background, Python’s in python/tempo/_background.py and
C++‘s in cpp/src/internal/Background.cpp. Every binding prints one line on
a roboRIO whose loop thread is not at real-time priority (Java’s
LoopPriority).
wasm32 has no threads, so worker_pool::submit refuses every job there and callers
plan in place.
Python and C++ differences
The three robot bindings drive the same entry points, and their differences are in loading, ownership and the host loop.
| Concern | Java | Python | C++ |
|---|---|---|---|
| ABI mapping | JNA interface TempoNative; per-tick calls through TempoNativeFast (Native.register) | ctypes in python/tempo/_native.py | function-pointer table Symbols in cpp/src/Native.cpp, declared in cpp/include/tempo/detail/Native.h |
| Hot-path calls | direct-mapped, owned Memory buffers | read-only status queries through _fast, a ctypes.PyDLL handle that keeps the GIL; planning calls stay on _lib, which releases it | plain function pointers |
| Configure | Tempo.configure | Tempo.configure in python/tempo/tempo_facade.py | cpp/src/Facade.cpp |
| Runtime shell | NativeAutoRuntime | python/tempo/_native_auto.py | cpp/src/TempoAuto.cpp |
| Config and route handles | ConfigHandle, AuthoredRoute | python/tempo/_route_config.py | cpp/src/internal/RouteConfig.cpp |
| Authoring queries | CoreAuthoring, AuthoringQuery | python/tempo/_authoring.py | cpp/src/internal/Authoring.h |
| Scheduler | Commands v2 or v3 through internal.cmd2 / internal.cmd3 adapters | RobotPy commands2 | WPILib-free core plus the tempo::wpi adapter (cpp/src/wpi/) |
Python releases the GIL on every _lib call, so other Python threads run while
the core plans. Each status read on _fast copies fields out of a runtime and
never blocks, so holding the GIL there cannot deadlock. The C++ core accepts opaque
commands and explicit scheduler callbacks
(Wrapper policy).
Setlists and connecting drives
A Setlist runs several routes as one auto. Before each route after the first, the
binding compares the live pose with the route’s start using the test in
java/src/main/java/com/tempo/wpi/RouteJoin.java (Python and C++ carry the same
test, C++ in cpp/src/internal/RouteJoin.h). All three read
tests/fixtures/sequencing/routeJoins.json. When the robot is outside the arrival
tolerance, the binding builds a connecting drive with
tempo_route_connector_v1 and runs it first. The core applies the same rule from
authored ends in rust/core/src/route_join.rs when a route decides whether to
end moving into the next one (tempo_auto_flow_into_v2,
Route flow).
Loading the native library
| Binding | Search order | Failure |
|---|---|---|
| Java | jna.library.path, then the JAR resource for Platform.RESOURCE_PREFIX, then the system loader (NativeLoader) | TempoLoadException naming the platform and paths |
| Python | the package directory, ../native/, then rust/target/{release,debug} and the two cross-target release directories; never the system path | OSError from _search_failure_message |
| C++ | the executable’s own directory, then a bare-name dlopen / LoadLibraryA | std::runtime_error from open_library_or_throw; a missing symbol names the stale library |
JAR resource prefixes are linux-armel (roboRIO), linux-aarch64
(SystemCore and Linux ARM desktops), linux-x86-64, win32-x86-64 and
darwin-universal (one dylib for Apple silicon and Intel). The C++ order is a
security property.
GradleRIO installs third-party natives in a world-writable directory on the
roboRIO, so the copy beside the executable wins (cpp/src/Native.cpp,
open_library). Source-checkout loading is in
Native loading in source checkouts.
In Java, TempoNative.INSTANCE is initialized by NativeLoader.loadTempoNative().
When the WPILib version check refuses, that method returns a proxy whose every call
throws the refusal, so no class initializer throws
(Two WPILib seasons).
The editor’s wasm build
rust/wasm is a separate Cargo workspace that depends on tempo-core by path and
exports a browser API with wasm-bindgen (rust/wasm/src/lib.rs). It links the
same planner and has no C ABI, no pack handles from tempo_load_pack, and no
threads. CI builds it with:
wasm-pack build rust/wasm --target web --out-dir "$PWD/gui/wasm/web" --release -- --lockedThe editor imports it as @pkg/wasm.js (aliased in
gui/web/vite.config.ts). gui/web/src/planner/plannerWorker.ts
runs it in a Web Worker started by WasmWorkerBackend. The main exports:
| Export | Core path |
|---|---|
PackHandle::new(pack_toml, robot_radius_m) | field parse and plan-graph cache |
plan_preview, plan_preview_with_waypoints | spline and trajectory for a free-hand path |
plan_preview_routed, plan_preview_routed_with_waypoints, start_routed_preview | Replanner::plan_route_cached_with_waypoints per planning group, the same grouping and junction rules a robot uses |
route_join_query | tempo_core::route_join |
authoring_query | the authoring module, without a pack handle |
parse_pack | field validation |
rust/wasm/build.rs
fingerprints the wasm source closure listed in rust/wasm/conformanceSources.txt
plus fixed inputs, so read Pins and surfaces before editing
any of them.
Module map of rust/core/src
lib.rs declares every module. Grouped by role:
| Role | Modules |
|---|---|
| Field and geometry | field (pack TOML, obstacles, terrain, origin), geometry, clearance_margin, contact_sweep |
| Path planning | visibility_graph, pathfinding, plan_reuse (crate-private), traversal (crossings), free_heading |
| Trajectory | spline, trajectory (with trajectory/aims.rs, mecanum.rs, narrow_turns.rs), rotation, rotation_locks, aim, drive_model |
| Following and output | follower, sampled_follower, output_limit, replanner |
| Runtime and sequencing | auto_runtime, route_join, auto_log, authoring, worker_pool, sim_physics |
| C ABI | ffi |
| Numeric support | portable_math (acos, atan2, fma, hypot, sin_cos) |
pathfinding_direct_tests.rs holds direct-route planning tests.
The largest files are auto_runtime.rs, replanner.rs, ffi.rs and
visibility_graph.rs, so search them by function name.
Where to start for common changes
Add an FFI function
- Read Adding a new FFI function and Pins and surfaces.
- Add the
#[no_mangle] extern "C"function inrust/core/src/ffi.rsinside a new// BEGIN/END TEMPO <NAME> ADDITIVE BOUNDARYblock, wrapped incatch_unwind, usingu32lengths andu8booleans. - Test it through raw pointers in Rust, in
ffi.rsorrust/core/tests/. - Declare it in
java/src/main/java/com/tempo/internal/TempoNative.java(andTempoNativeFastwhen a loop calls it),python/tempo/_native.py, and theSymbolstable incpp/include/tempo/detail/Native.hpluscpp/src/Native.cpp. C++ resolves every symbol at load, so a stale library fails with the symbol’s name. - Re-pin in the same commit where the pins require it, then run the gates in Building and testing.
Add a Composer option across languages
- Java first: the builder method in
Composer.java, its field onComposer.SegmentSpec, and its serialization inRouteSerializer.java(tempo.authored-route/v1and the sequencing route). - Core: read the field in
auto_runtime.rs(RouteTemplate,route_from_json) and use it in the runtime. Validation that should refuse at freeze belongs inauthoring.rs, with a code intests/fixtures/api/authoringRefusals.json. - Python:
python/tempo/composer.pyandpython/tempo/_route_serializer.py. C++:cpp/include/tempo/Composer.h,cpp/src/Composer.cpp, and the route writer incpp/src/TempoAuto.cpp/cpp/src/internal/RouteConfig.h. - Editor: when the option changes a preview, carry it into the routed preview
request (
gui/web/src/planner/buildRoutedPlanRequest.ts) and the wasm reader, and when it is generated code, updaterobotCodegen.ts. - Surfaces: name the new declarations in the pull request, so the
tests/fixtures/api/{java,python,cpp}.txtsnapshots are refreshed additively.
The full sequence is The porting checklist.
Change per-tick behavior
Start in AutoRuntime::tick_with and tick_driving (auto_runtime.rs), then
Replanner::compute. Recorded traces in tests/fixtures/sequencing/ are frozen, and
a change that moves one edits the trace by hand in a commit that names the
behavior (Fixtures).
Change what the host reads each tick
Add a slot to the status block in write_auto_status (ffi.rs) only inside an
additive block, then update STATUS_LEN and the slot constants in
NativeAutoRuntime.java, _native_auto.py and TempoAuto.cpp. Callers that pass
a shorter capacity keep reading a prefix.