Skip to content

perf(rpc): non-template RuntimeRpcBinding dispatch on low-memory (#3246 Tier 1A) - #3258

Merged
zackees merged 1 commit into
masterfrom
feat/3246-runtime-rpc-binding
Jun 19, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3246-runtime-rpc-binding

Conversation

@zackees

@zackees zackees commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces the per-signature TypedRpcBinding<Sig>::invokeWithReturn body (observed at 2,074 B on LPC845-BRK for fl::string(int,int,int,int)) with a non-template fl::detail::RuntimeRpcBinding plus a small per-Sig trampoline + per-type ops table.

Architecture:

  • RuntimeRpcBinding (non-template ErasedInvoker): one signature-agnostic decode/encode/dispatch body shared across every signature.
  • RpcTypeOps table (one static per unique storage type), generated by RpcTypeOpsFor<T>, reuses existing JsonToType<T> / TypeToJson<T> specializations.
  • Per-Sig runtime_rpc::TrampolineHelper<R, Args...> produces a ~50-100 B trampoline + ~10 B destroy fn + 8 B × argc rodata table.
  • Rpc::registerMethod<Sig> forks at compile time on FL_PLATFORM_HAS_LARGE_MEMORY: low-memory uses RuntimeRpcBinding; large-memory keeps the existing inline TypedInvoker<Sig> (faster -- no per-call heap, no indirect dispatch).

Measurement (LPC845-BRK / AutoResearch / LowMemory mode)

Metric Master Branch Delta
Flash (.bin) 47,020 B 46,704 B -316 B
Text (.text) 48,258 B 47,252 B -1,006 B
Flash % of 64 KB 71.7% 71.3% -0.4%

Symbol-level structural win (the original issue's hot symbol is gone):

  • TypedRpcBinding<fl::string (int,int,int,int)>::invokeWithReturn -- 2,074 B → 0 (replaced)
  • TypedRpcBinding<int(int)>::invokeWithReturn -- 516 B → 0 (replaced)
  • RuntimeRpcBinding::invoke -- 0 → 1,536 B (shared across every Sig)
  • RpcTypeOpsFor<int>::decode_ -- 0 → 454 B (one-time per type)
  • RpcTypeOpsFor<fl::string>::decode_ -- 0 → 224 B (one-time per type)

Honest caveat re acceptance bullet ≥ 1.5 KB net flash drop

The 1,006 B .text / 316 B flash savings is below the issue's predicted 1.5 KB target, but the structural win is correct -- per-Sig template tax is gone. This matches the meta #3244 lesson-learned (verbatim from #3235 retrospective):

The audit's per-tier savings predictions assumed kitchen-sink builds with ~30 distinct container instantiations. AutoResearch has 2 of each.

AutoResearch's LowMemory mode registers only 2 unique RPC signatures. Per-Sig accounting shows the leverage axis works (2nd-Sig cost drops from 516 B to ~20 B trampoline) but full ~6 KB savings need a multi-method sketch (RpcServer, etc.). Leaving #3246 open so a follow-up can run the kitchen-sink benchmark.

Test plan

  • 7 new FL_TEST_CASE in tests/fl/remote/rpc/runtime_rpc_binding.hpp exercising the runtime path directly on host (host targets default through TypedInvoker; the new tests force RuntimeRpcBinding to verify decode/encode/error/lifetime).
  • bash test --cpp -- 328/328 unit tests pass.
  • bash test rpc --debug -- ASAN/LSAN/UBSAN clean on the new path.
  • bash lint --cpp -- 0 violations.
  • LPC845-BRK / AutoResearch builds (host-cross via ./compile lpc845brk --examples AutoResearch), no regression.
  • Multi-method sketch flash measurement (deferred to follow-up).

Refs #3246, #3244 (Tier 1A), #3235.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced runtime RPC binding system for resource-constrained platforms, enabling flexible method registration with adaptive behavior based on available system memory.
  • Tests

    • Added comprehensive test coverage for RPC binding across multiple signature types, error scenarios, argument handling, and resource cleanup.

…ets (#3246 / #3244 Tier 1A)

Replace the per-signature `TypedRpcBinding<Sig>::invokeWithReturn` body
(2,074 B observed on LPC845-BRK for `fl::string(int,int,int,int)`) with
a non-template `RuntimeRpcBinding` plus a per-Sig trampoline + per-type
ops table.

Implementation
- New `fl::detail::RuntimeRpcBinding` (non-template `ErasedInvoker`) with
  one signature-agnostic decode/encode/dispatch body shared across every
  signature. Per-call: alloc slot buffers, decode via type-keyed ops,
  trampoline into the user lambda, encode the result.
- New `fl::detail::RpcTypeOps` table (one static per unique storage
  type), driven by templated `RpcTypeOpsFor<T>` so existing
  `JsonToType<T>` / `TypeToJson<T>` specializations are reused without
  copy.
- Per-Sig trampoline in `runtime_rpc::TrampolineHelper<R, Args...>`
  (~50-100 B). All cross-type behaviour lives in the shared invoke().
- `Rpc::registerMethod<Sig>` forks at compile time on
  `FL_PLATFORM_HAS_LARGE_MEMORY`: low-memory targets get
  `RuntimeRpcBinding`; large-memory keeps `TypedInvoker<Sig>` (no
  per-call heap, no indirect dispatch -- faster path retained).

Measurement (LPC845-BRK / AutoResearch)
- Master baseline:  47,020 B flash (.bin); 48,258 B .text
- This branch:      46,704 B flash (.bin); 47,252 B .text
- Net:              **316 B flash / 1,006 B .text saved**
- Structural: `TypedRpcBinding<fl::string(int,int,int,int)>::invokeWithReturn`
  (2,074 B) and `TypedRpcBinding<int(int)>::invokeWithReturn` (516 B)
  are gone, replaced by `RuntimeRpcBinding::invoke` (1,536 B, shared).

The 1,006 B observed is below the issue's ~1.5 KB target, but the
structural win is correct -- the per-Sig template tax is gone. This
matches the meta #3244 lesson-learned: AutoResearch registers only 2
unique signatures, so amortization of the shared dispatch body across
signatures is limited at this sketch size. Per-Sig accounting (2nd-sig
cost drops from 516 B to ~20 B trampoline) shows the leverage axis
works; full ~6 KB savings need a multi-method sketch (RpcServer, etc.)
to demonstrate.

Tests
- 7 new FL_TEST_CASEs in tests/fl/remote/rpc/runtime_rpc_binding.hpp
  exercise the runtime path directly on host (host targets default
  through TypedInvoker; the new tests force RuntimeRpcBinding to verify
  decode/encode/error/lifetime). All 328 unit tests pass quick + debug.
- ESP32/Teensy/LPC845 compile path verified; existing
  tests/fl/remote/rpc/rpc.hpp suite continues to pass.

Refs #3246, #3244 (Tier 1A), #3235.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 58eae44f-3233-41e3-b384-93b6e74da8d7

📥 Commits

Reviewing files that changed from the base of the PR and between 71a2122 and 6661ab5.

📒 Files selected for processing (6)
  • src/fl/remote/rpc/_build.cpp.hpp
  • src/fl/remote/rpc/rpc.h
  • src/fl/remote/rpc/runtime_rpc_binding.cpp.hpp
  • src/fl/remote/rpc/runtime_rpc_binding.h
  • tests/fl/remote/rpc.cpp
  • tests/fl/remote/rpc/runtime_rpc_binding.hpp

📝 Walkthrough

Walkthrough

Introduces RuntimeRpcBinding, a non-template type-erased RPC invoker for !FL_PLATFORM_HAS_LARGE_MEMORY targets. It uses per-type RpcTypeOps tables, per-signature trampolines (TrampolineHelper), and a single shared invoke body to replace per-signature TypedInvoker instantiations. Rpc::registerMethod is forked at compile time to select the appropriate invoker. Tests and Unity build wiring are included.

Changes

RuntimeRpcBinding type-erased invoker

Layer / File(s) Summary
RpcTypeOps table, TrampolineHelper, and ArgTypesTable contracts
src/fl/remote/rpc/runtime_rpc_binding.h
Defines RpcTypeOps (per-storage-type default-construct/destroy/decode/encode ops table), RpcTypeOpsFor<T> generator (including void specialization), RpcTrampolineFn ABI, TrampolineHelper<R,Args...> trampoline and destroy generator with a void-return specialization, and ArgTypesTable<Args...> for static per-signature arg-ops arrays.
RuntimeRpcBinding class and makeRuntimeRpcBinding factory
src/fl/remote/rpc/runtime_rpc_binding.h
Defines the RuntimeRpcBinding non-template ErasedInvoker subclass holding heap user-fn, trampoline, destroy, arg-ops table, arg count, and result-ops pointer; destructor cleanup; and makeRuntimeRpcBinding<R,Args...> factory that heap-allocates the fl::function and returns a fl::shared_ptr<RuntimeRpcBinding>.
RuntimeRpcBinding::invoke implementation
src/fl/remote/rpc/runtime_rpc_binding.cpp.hpp
Implements the non-template invoke body: validates jsonArgs is an array with matching element count, allocates/default-constructs per-argument raw buffers with RuntimeRpcSlotCleanup RAII, decodes each argument via RpcTypeOps, dispatches through mTrampoline, encodes or nullifies the result, and returns a TypeConversionResult/json tuple.
Rpc::registerMethod platform fork and build wiring
src/fl/remote/rpc/rpc.h, src/fl/remote/rpc/_build.cpp.hpp
Adds runtime_rpc_binding.h and sketch_macros.h includes to rpc.h; replaces unconditional TypedInvoker<Sig> construction with a FL_PLATFORM_HAS_LARGE_MEMORY compile-time branch; adds the Unity build #include for runtime_rpc_binding.cpp.hpp.
RuntimeRpcBinding test suite
tests/fl/remote/rpc.cpp, tests/fl/remote/rpc/runtime_rpc_binding.hpp
Adds test cases for scalar and void return via type-erased invoke, error propagation for non-array and count-mismatched args, fl::string/const char* argument storage round-trips, and binding lifetime/cleanup; wires the test header into rpc.cpp.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant registerMethod as Rpc::registerMethod
  participant makeRTB as makeRuntimeRpcBinding
  participant invoke as RuntimeRpcBinding::invoke
  participant Trampoline as TrampolineHelper::trampoline
  participant UserFn as fl::function~R(Args...)~

  rect rgba(70, 130, 180, 0.5)
    note over registerMethod,makeRTB: !FL_PLATFORM_HAS_LARGE_MEMORY path
    Client->>registerMethod: registerMethod("name", fn)
    registerMethod->>makeRTB: makeRuntimeRpcBinding(fn)
    makeRTB->>makeRTB: heap-allocate fl::function, build RuntimeRpcBinding
    makeRTB-->>registerMethod: shared_ptr~RuntimeRpcBinding~
  end

  rect rgba(60, 179, 113, 0.5)
    note over invoke,UserFn: invoke call path
    Client->>invoke: invoke(jsonArgs)
    invoke->>invoke: validate array & arg count
    loop per argument
      invoke->>invoke: default_construct + decode slot via RpcTypeOps
    end
    invoke->>Trampoline: mTrampoline(mUserFn, result_buf, slot_ptrs)
    Trampoline->>UserFn: call fn(cast args...)
    UserFn-->>Trampoline: R value
    Trampoline-->>invoke: result written to result_buf
    invoke->>invoke: encode result via RpcTypeOps
    invoke-->>Client: tuple(TypeConversionResult, json)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

A rabbit hops past the template bloat,
Each signature once a heavy coat—
Now trampolines leap, one shared dispatch flies,
RpcTypeOps tables wave good-byes.
Low-memory boards breathe easy at last,
The era of bloated invokers is past! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a non-template RuntimeRpcBinding dispatch mechanism optimized for low-memory platforms, with the issue reference clearly identifying the work scope.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3246-runtime-rpc-binding

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant