Skip to content

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:

  1. NativeLoader.ensureLoaded() opens libtempo_core (see Loading the native library).
  2. 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).
  3. com.tempo.internal.Background.start() starts the binding’s two helper threads, after the workers.
  4. 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 an op: "route" request through AuthoringQuery to tempo_authoring_query_v1. The core’s authoring module returns a problems array, and the binding throws the first one with the exception type tests/fixtures/api/authoringRefusals.json assigns (Authoring queries).
  • Hooks are prepared (prepareHooks), per-leg replanning config is folded in (resolveLegReplanning), and extensions are inferred (ExtensionInference.inferSegmentExtensions).
  • warnLimitsAboveFull prints one console line when a leg asks for more than Speed.FULL. The core’s resolve lowers each such limit to Speed.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):

HalfJava ownerCore readerSchema
Robot configurationcom.tempo.internal.ConfigHandletempo_config_new_v1 -> drive_model::ResolvedConfigtempo.route-config/v1
Authored routecom.tempo.internal.AuthoredRoute (RouteSerializer writes it)tempo_route_new_v1 -> auto_runtime::RouteTemplatetempo.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:

  1. It asks robot code for the current leg’s answers: the endWhen predicate, Condition.when trigger bits, aim-arming bits, and supplier-backed aim values (two doubles per aim, NaN where the supplier yielded null). TreeSlots asks each predicate once per loop.
  2. It calls TempoNativeFast.tempo_auto_tick_status(...) with the pose, the clock, those answers (aim targets go in a separate aimSupplied input array) and three caller-owned output buffers: 3 speeds, up to 64 fired triples (FIRED_CAP), and the 27-slot status block (STATUS_LEN).
  3. A return of -2 means 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.
  4. A return of -1 means failure. The core has already written zero speeds and set tempo_last_error, and Java reads that string at once and latches it as tickFault.
  5. A nonnegative return counts the fired hooks queued. resolveFired maps each (segment, kind, index) triple to the command in the route’s Composer.SegmentSpec list. Kinds are 0 runDuring, 1 trigger, 2 fail case, 3 arriveWith and 4 window end.
  6. 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 with tempo_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:

  1. 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).
  2. Runs tick_in_loop, which advances phases (NOT_STARTED, PRE_BLOCKING, DRIVING, POST_BLOCKING, WAITING, DONE, CANCELLED, HANDED_OFF) until it returns a command or AutoTick::NeedsFreshInputs. A driving leg goes through tick_driving, which asks the leg’s Replanner for its command.
  3. Evaluates route state trees against the trigger bits.
  4. Passes the command through limit_output (the OutputLimiter in rust/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:

LaneWorkRuns on
Nowa leg’s plan, junction negotiation, the warm-up’s first-leg planthe urgent worker
Aheadlook-ahead plans for later legsbackground, promoted when waited on
Soonreplansbackground, promoted after the follower misses it for a couple of loops
Backgroundplan-graph bakesbackground
Sparewarm-up plans of later legsbackground, 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

ThreadOwnerScheduling on Linux
Robot looprobot programwhatever robot code sets
Urgent planning workerworker_poolSCHED_BATCH, nice 0 (run_beside_the_loop)
Background planning workersworker_poolSCHED_BATCH, nice 19 (run_below_the_loop); one on three cores or fewer, two otherwise
Chore and reclaimer threadsworker_poolbelow the loop
Field bake threads (tempo-bake, one per tempo_auto_prebake_field call, ending with the bake)ffibelow the loop (spawn_below_the_loop)
Binding urgent helper (TempoUrgent in Java and C++)bindingnice 0 via tempo_run_beside_the_loop
Binding background helper (TempoBuild in Java and C++)bindingnice 19 via tempo_run_below_the_loop
Binding console thread (TempoConsole in Java, C++ and Python)bindingnice 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.

ConcernJavaPythonC++
ABI mappingJNA interface TempoNative; per-tick calls through TempoNativeFast (Native.register)ctypes in python/tempo/_native.pyfunction-pointer table Symbols in cpp/src/Native.cpp, declared in cpp/include/tempo/detail/Native.h
Hot-path callsdirect-mapped, owned Memory buffersread-only status queries through _fast, a ctypes.PyDLL handle that keeps the GIL; planning calls stay on _lib, which releases itplain function pointers
ConfigureTempo.configureTempo.configure in python/tempo/tempo_facade.pycpp/src/Facade.cpp
Runtime shellNativeAutoRuntimepython/tempo/_native_auto.pycpp/src/TempoAuto.cpp
Config and route handlesConfigHandle, AuthoredRoutepython/tempo/_route_config.pycpp/src/internal/RouteConfig.cpp
Authoring queriesCoreAuthoring, AuthoringQuerypython/tempo/_authoring.pycpp/src/internal/Authoring.h
SchedulerCommands v2 or v3 through internal.cmd2 / internal.cmd3 adaptersRobotPy commands2WPILib-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

BindingSearch orderFailure
Javajna.library.path, then the JAR resource for Platform.RESOURCE_PREFIX, then the system loader (NativeLoader)TempoLoadException naming the platform and paths
Pythonthe package directory, ../native/, then rust/target/{release,debug} and the two cross-target release directories; never the system pathOSError from _search_failure_message
C++the executable’s own directory, then a bare-name dlopen / LoadLibraryAstd::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:

Shell
wasm-pack build rust/wasm --target web --out-dir "$PWD/gui/wasm/web" --release -- --locked

The 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:

ExportCore path
PackHandle::new(pack_toml, robot_radius_m)field parse and plan-graph cache
plan_preview, plan_preview_with_waypointsspline and trajectory for a free-hand path
plan_preview_routed, plan_preview_routed_with_waypoints, start_routed_previewReplanner::plan_route_cached_with_waypoints per planning group, the same grouping and junction rules a robot uses
route_join_querytempo_core::route_join
authoring_querythe authoring module, without a pack handle
parse_packfield 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:

RoleModules
Field and geometryfield (pack TOML, obstacles, terrain, origin), geometry, clearance_margin, contact_sweep
Path planningvisibility_graph, pathfinding, plan_reuse (crate-private), traversal (crossings), free_heading
Trajectoryspline, trajectory (with trajectory/aims.rs, mecanum.rs, narrow_turns.rs), rotation, rotation_locks, aim, drive_model
Following and outputfollower, sampled_follower, output_limit, replanner
Runtime and sequencingauto_runtime, route_join, auto_log, authoring, worker_pool, sim_physics
C ABIffi
Numeric supportportable_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

  1. Read Adding a new FFI function and Pins and surfaces.
  2. Add the #[no_mangle] extern "C" function in rust/core/src/ffi.rs inside a new // BEGIN/END TEMPO <NAME> ADDITIVE BOUNDARY block, wrapped in catch_unwind, using u32 lengths and u8 booleans.
  3. Test it through raw pointers in Rust, in ffi.rs or rust/core/tests/.
  4. Declare it in java/src/main/java/com/tempo/internal/TempoNative.java (and TempoNativeFast when a loop calls it), python/tempo/_native.py, and the Symbols table in cpp/include/tempo/detail/Native.h plus cpp/src/Native.cpp. C++ resolves every symbol at load, so a stale library fails with the symbol’s name.
  5. 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

  1. Java first: the builder method in Composer.java, its field on Composer.SegmentSpec, and its serialization in RouteSerializer.java (tempo.authored-route/v1 and the sequencing route).
  2. 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 in authoring.rs, with a code in tests/fixtures/api/authoringRefusals.json.
  3. Python: python/tempo/composer.py and python/tempo/_route_serializer.py. C++: cpp/include/tempo/Composer.h, cpp/src/Composer.cpp, and the route writer in cpp/src/TempoAuto.cpp / cpp/src/internal/RouteConfig.h.
  4. 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, update robotCodegen.ts.
  5. Surfaces: name the new declarations in the pull request, so the tests/fixtures/api/{java,python,cpp}.txt snapshots 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.

esc

Loading search...