Skip to content

META: type-erasure burn-down -- collapse template-instantiation taxes across containers / RPC / visitors / fl::function / chipset controllers #3235

Closed

Description

@zackees

Goal

FastLED's core value prop is "smallest possible footprint for LED control on embedded MCUs." Meta #3224 (closed) demonstrated that surgical #if FL_PLATFORM_HAS_LARGE_MEMORY gating can recover 22% of flash on a 64 KB part. This meta tracks the next architectural axis: replacing per-template-instantiation codegen taxes with shared runtime-typed thunk layers (the type erasure pattern that fl::vector_basic already pioneered under fl::vector<T>).

This is a burn-down meta: file sub-issues against it, link PRs, retire items as they land. Each sub-issue carries its own concrete byte target on a defined target sketch + board. Close this meta when ≥75% of the catalog has landed or been formally deferred with rationale.

Why type erasure now

The Tier 3H finding from #3224 — TypedRpcBinding<Sig>::invokeWithReturn consuming ~2.1 KB per registered method — is the entry point. But it's the symptom of a broader pattern. After dispatching five parallel sub-agent audits across the codebase, the same shape appears in at least six independent subsystems:

Subsystem Per-instantiation tax (estimate) Pattern
fl::unordered_map<K, V> ~2.6 KB / instance Hot methods (rehash_internal, find_slot, operator[]) are pure pointer/bitset arithmetic that doesn't depend on K,V
fl::flat_map<K, V, Less> ~300 B / instance × ~30 call sites lower_bound, upper_bound, operator[] are pure binary search over byte storage
fl::variant<...>::visit_fn<T, V> thunk table ~50-164 B × (alternatives × visitors) json_value has 10 alts × ~9 visitors = ~330 thunks (~6.7 KB on LPC845)
fl::function<Sig> 5-alternative variant ~2 KB / signature × ~25-30 signatures 5 alternatives × 4 ops × N sigs; MemberCallable variants are dead code in production
JSON visitors (per (visitor, T) pair) ~700 B per visitor Quadratic codegen tax over (10 alternatives × 9 visitors)
RPC dispatch templates (TypedRpcBinding, JsonArgConverter, TypeToJson) ~2.1 KB per signature The Tier 3H item; entirely re-implementable as RuntimeRpcBinding + ~150 B trampoline
ClocklessController<TIMING, PIN, ORDER> (32 chipset families) ~0.8-2 KB per (chipset × pin × order) Already nearly type-erased on RMT5; runtime variant viable on ESP32/Teensy/RP2040/WASM

Estimated total flash recovery across the catalog: 25-50 KB on a kitchen-sink sketch (e.g. AutoResearch on ESP32-S3 with the full RPC + JSON surface and 4-6 LED controllers). LPC8xx / AVR builds were already squeezed in #3079 and #3224 so the headroom for those is smaller — but the same patches help every embedded target.

Measurement methodology

Use bash bloat <board> --example <sketch> (works as of #3225 across ESP32 + arm-none-eabi via fbuild symbols delegation). Compare top-N symbols before and after each PR. Acceptance threshold per sub-issue: ≥80% of the predicted savings on the primary target sketch.

Baseline (today, master + #3232):

Board: lpc845brk
Example: AutoResearch (LowMemory mode)
Total flash: 51,538 B   RAM: 9,959 B   Headroom: ~14 KB

Top contributors (per arm-none-eabi-nm --print-size):
  1  2,270 B  autoResearchLowMemorySetup
  2  2,142 B  fl::TypedRpcBinding<string(int×4)>::invokeWithReturn   ← Sub-issue A target
  3  1,982 B  fl::JsonBuilder::on_token
  4  1,576 B  fl::Rpc::handle
  5  1,024 B  autoResearchLowMemorySetup lambda#2
  6    792 B  fl::function<string(int×4)>::InlinedLambda::invoke_lambda
  7    762 B  fl::basic_string::write(char const*, unsigned int)
  8    660 B  __clzdi2 (libgcc)
  9    650 B  fl::JsonTokenizer::parse
 10    628 B  fl::unordered_map<string, RpcEntry>::rehash_inline_no_resize   ← Sub-issue C target

Sub-issues to file

Tier 1 — highest leverage, well-scoped

# Title Target tax Predicted saving Difficulty Notes
A RuntimeRpcBinding: replace TypedRpcBinding<Sig> with a non-template binding + per-Sig trampoline ~2.1 KB / Sig ~1.5-1.8 KB / Sig (one-time +1 KB amortized) medium-hard Tier 3H from #3224. Per-Sig template tax → per-Sig trampoline (50-150 B). Phase via FL_PLATFORM_HAS_LARGE_MEMORY opt-in; ESP32/Teensy hot path can keep templates. Detailed design + risk in sub-issue.
B fl::function<Sig> Option B: single SBO + invoker/manager fn ptrs ~2 KB / Sig ~1.5 KB / Sig on Large-memory; ~25-35 KB cumulative medium Replaces the 5-alternative variant with one struct holding (invoker, manager, char[SBO]). Member-fn support survives as a thin wrapper. Audit confirmed zero production uses of &Class::method outside one test file. Side-effect: fixes a latent UB in memcpy-based InlinedLambda copy.
C unordered_map_basic: pointer/bitset arithmetic into a non-template base ~2.6 KB / instance ~3 KB on LPC845, ~6-9 KB on full builds medium Mirror fl::vector_basic pattern. rehash_internal, rehash_inline_no_resize, find_slot, find_index are all signature-agnostic. unordered_set gets the win for free as a wrapper.

Tier 2 — high leverage, more invasive

# Title Target tax Predicted saving Difficulty Notes
D flat_map_basic: shared binary-search core ~300 B / instance × ~30 instances ~6-9 KB on full builds easy lower_bound, upper_bound, operator[] are pure pointer arithmetic + less_fn(const void*, const void*). Easiest container win after unordered_map_basic.
E json_visit_dispatch: non-template dispatch core for visitors ~700 B per visitor × ~9 visitors ~2.5-3.5 KB on LPC845, ~5+ KB on Large-memory medium Replaces per-(visitor × T) operator() overloads with json_convert_to_<int/bool/float/string>_core(tag, storage, out). Templated wrapper handles final type narrowing only. SizeVisitor / IsArrayVisitor reduce to tag-table lookups in Phase 1 (free ~250 B trial).
F ClocklessControllerRuntime: runtime-timing variant for ESP32/Teensy/RP2040/WASM ~0.8-2 KB per chipset specialization ~8-25 KB on Blink-like sketches with many chipsets medium-hard Preserves FastLED.addLeds<CHIPSET, PIN, ORDER>(...) API surface. AVR / LPC8xx / ESP8266 keep template path (cycle-tight bit-banging needs compile-time constants). Gated via FL_USE_RUNTIME_CLOCKLESS.

Tier 3 — modest wins, defer until Tier 1/2 measured

# Title Target tax Predicted saving Difficulty Notes
G Variant trivial-destructor / trivial-copy collapse ~50-164 B × N (T, V) pairs ~2-3 KB on variant-heavy targets (json_value) hard Share destroy_fn across is_trivially_destructible Ts (collapse to noop_destroy). Share copy_fn/move_fn across trivially-copyable Ts (collapse to memcpy(storage, other, size) thunks parameterized at runtime by sizeof(T)). Doesn't touch visit semantics.
H deque_basic shadow class ~250 B / instance ~150 B per future instantiation easy Mirror vector_basic. Only 1-2 deque instantiations today (deque<char> for json, deque<u8> for parlio). Limited ROI but cheap to land alongside Tier 2D.
I Visitor warning-string outlining (formatter-only) ~150-250 B / visitor × ~9 visitors ~1-2 KB easy Today each visitor inlines a fl::to_string(value, 6) warning formatter that anchors basic_string machinery. Outline to a single format_warning_value(tag, storage) helper that only links if any visitor actually emits a warning at runtime.

Tooling dependency

Both of these are documented in agents/docs/binary-size-analysis.md so any future agent picking up sub-issues has the right measurement workflow.

Predecessors

Acceptance for closing this meta

  • At least 4 of {A, B, C, D, E} closed via merged PRs
  • Tier 1 items A and B both addressed (the two biggest leverage items)
  • Each sub-issue's predicted byte saving is verified within 25% accuracy on its target sketch
  • bash bloat <board> workflow documented in agents/docs/binary-size-analysis.md (already mostly there post-feat(bloat): delegate nm + ELF path resolution to fbuild symbols (arm support) #3225)
  • Tier 3 items either filed as separate trackers or explicitly deferred with rationale

How to claim a sub-issue

  1. File the sub-issue against this meta with the title pattern [Type-Erasure] <subsystem>: <approach> and a concrete byte target on a named sketch+board.
  2. Run bash bloat <board> --example <sketch> before starting work to capture the baseline.
  3. Implement with whatever pattern fits (*_basic shadow class, runtime dispatch core, trampoline approach, etc.).
  4. Run bash bloat <board> --example <sketch> after and post the delta in the PR.
  5. Reference this meta in the PR body via Closes #<sub-issue> so it tracks against the burn-down.

Out of scope

Sub-agent audit reports

The five parallel audits that informed this meta are summarized in the table above. Full reports (one per subsystem) available on request; each covers current cost, proposed design, savings estimate, risk assessment, and migration plan. They follow the same shape and arrived at consistent conclusions, lending confidence to the catalog numbers.

Activity

  1. zackees commented on Jun 18, 2026

    @zackees
    MemberAuthor

    Large-memory baseline added: Teensy 4 / AutoResearch

    Board: teensy40
    Example: AutoResearch (full Large-memory mode -- includes the LED protocol matrix)
    Total flash: 285,844 B   RAM: 83,629 B
    
    Top 12 contributors:
      1  9,436 B  AutoResearchRemoteControl::runSingleTestImpl     [sketch-side]
      2  5,608 B  fl::Channel::showPixels<PixelController<GRB,1,0xFFFFFFFF>>     ← Tier 2F target
      3  4,700 B  AutoResearchRemoteControl::registerFunctions (ltrans9.part.0)  ← Tier 1A scales w/ #methods
      4  4,564 B  capture<...> (RX measurement)
      5  4,506 B  AutoResearchRemoteControl::registerFunctions (ltrans9.part.1)
      6  4,372 B  AutoResearchRemoteControl::runParallelTestImpl
      7  4,216 B  runMultiTest(...)
      8  3,208 B  setup
      9  3,072 B  hab_csf (security descriptor)
     10  2,836 B  fl::ChannelManager::instance()
     11  2,720 B  loop
     12  2,536 B  fl::Rpc::handle(fl::json const&)                                ← Tier 1A target
    

    What this confirms

    • fl::Channel::showPixels at 5,608 B for a single chipset specialization — exactly the Tier 2F (ClocklessControllerRuntime) leverage point. A sketch with 4 chipset variants (e.g. Blink with WS2812 + APA102 + SK9822 + WS2811) would pay 4× this tax (~22 KB) where the runtime variant collapses to one ~6 KB body.
    • AutoResearchRemoteControl::registerFunctions partitioned at 4,700 + 4,506 = 9.2 KB across two LTO chunks — this is the per-method rpc.bind() registration code. With ~10 methods registered, Tier 1A (RuntimeRpcBinding) would drop this to ~2-3 KB total. Net win on Teensy 4: ~6-7 KB just from the registration path.
    • fl::Rpc::handle at 2,536 B (down from META: LPC845 64 KB flash bloat hunt -- clear 11 KB overage to unblock FASTLED_LPC_RX_SCT_WS2812=1 #3079 / META: LPC845 flash-budget Phase 2 — grow headroom from 1.4 KB to ~6-10 KB for feature capacity #3224 work) — the dispatch core is now well-trimmed, but per-Sig TypedRpcBinding<>::invokeWithReturn instantiations (each ~2 KB) live separately and aren't in the top 12 list because each is amortized across LTO partitions. They exist in the binary — nm --print-size | grep TypedRpcBinding | awk would show the aggregate.

    On the LPC845 baseline (also in the meta body)

    Board: lpc845brk
    Example: AutoResearch (LowMemory mode)
    Total flash: 51,538 B   RAM: 9,959 B   Headroom: ~14 KB
    
      2  2,142 B  fl::TypedRpcBinding<string(int×4)>::invokeWithReturn   ← Tier 1A target
     10    628 B  fl::unordered_map<string, RpcEntry>::rehash_inline_no_resize   ← Tier 1C target
    

    Same patterns, different magnitudes. The Tier 1 items (A, B, C) hit both targets equally.

    ESP32-S3 sketch measurements

    5 sketches (AutoResearch, Animartrix, Chromancer, Json, FxNoiseRing) were queued for ESP32-S3 bloat analysis. The build hit FastLED/fbuild#627 (zccache daemon wedge under concurrent worktree use) on AutoResearch — typical of the current daemon flakiness. Per-sub-issue PRs will rebuild + measure on their target sketch + board fresh; the cross-sketch ranking from LPC845 + Teensy 4 establishes the priority order, and individual sub-issues will validate against whichever sketch best exercises their target subsystem.

  2. zackees commented on Jun 18, 2026

    @zackees
    MemberAuthor

    Reopening: PR #3238 closed Tier 1B item B (fl::function Option B, -9.2 KB on Teensy 4) but the meta also tracks Tier 1A (RuntimeRpcBinding), Tier 1C (unordered_map_basic), Tier 2D (flat_map_basic), Tier 2E (json_visit_dispatch), Tier 2F (ClocklessControllerRuntime), and Tier 3 G/H/I. Per the meta's own acceptance criteria, ≥4 of {A, B, C, D, E} must close via merged PRs; one down, three to go.

  3. zackees commented on Jun 18, 2026

    @zackees
    MemberAuthor

    Implementation findings after Tier 1B (PR #3238 merged)

    While working through this meta I prototyped Tier 2D (flat_map_basic) and started on Tier 1C (unordered_map_basic). Honest finding: the per-instantiation savings predicted by the original audit don't materialize on the AutoResearch sketch because that build only has 2 distinct instantiations each of flat_map<> and unordered_map<>. The audit's "~6-9 KB on kitchen-sink builds" prediction assumed ~30 distinct map types; AutoResearch is nowhere near that.

    Concrete measurements

    Target unordered_map symbol mass flat_map instances flat_map symbol mass
    LPC845 / AutoResearch 5,592 B 1 included in variant fan-out
    Teensy 4 / AutoResearch (similar) 2 (similar)

    Tier 2D prototype outcome

    I built the type-erased binary-search helpers (flat_map_lower_bound_idx / upper_bound_idx) with FL_NO_INLINE to defeat LTO inlining. On AutoResearch:

    • LPC845: +72 B (regression — the per-call thunk overhead exceeded the savings on 1 instance)
    • Teensy 4: ±0 B (linker DCE'd one of the cores; net neutral)

    The implementation is correct. The leverage just isn't there on a 2-instance build. The vector_basic precedent works because fl::vector<T> is instantiated for many T's across the codebase. For flat_map and unordered_map on focused sketches like AutoResearch, the per-instance savings (~80-150 B from sharing inner loops) are smaller than the per-call thunk overhead (~30-50 B × N call sites).

    What this means for the meta

    The "≥4 of {A, B, C, D, E} closed" acceptance criterion was based on the assumption that each Tier item would be a positive-value ship. That assumption holds for Tier 1B (fl::function Option B, shipped via #3238, −9.2 KB Teensy 4) because every embedded build instantiates ~25-30 distinct fl::function<Sig> signatures. It does not hold for Tier 1C/2D on small / focused sketches because the per-call thunk overhead can dominate.

    Revised acceptance proposal

    The original framing was right that this meta is a burn-down, not a single-PR effort. But I'd revise the success criterion to be more measurement-driven:

    • Accept "this item is done" when its PR demonstrates positive savings on at least one production target (any sketch + board combination shipping in the repo's CI matrix).
    • Accept "this item is deferred with rationale" when the PR's measurement shows no positive movement on any target — the work goes to a follow-up tracker that waits for the codebase to grow enough instantiations to flip the math.

    Under that framing:

    • Tier 1B: CLOSED (positive on Teensy 4 + LPC845).
    • Tier 1A: still open and high-leverage (the per-Sig RPC tax is ~2.1 KB and grows with method count; sketches with many rpc.bind() calls will demonstrate it).
    • Tier 1C / 2D / 2E: CONDITIONALLY DEFERRED until either (a) a sketch with enough container instantiations to clear the per-call overhead lands in CI, OR (b) the type-erased core is implemented with zero-overhead call dispatch (e.g. via __attribute__((flatten)) at call sites, or hand-rolled assembly thunks that fit in a few bytes).
    • Tier 2F (ClocklessControllerRuntime): still high-leverage — the audit specifically estimated 8-25 KB on Blink-like sketches with multiple chipsets. That's a different dimension of leverage (per-chipset, not per-container) and should still pay off.
    • Tier 3 items: defer as originally planned.

    I'm leaving the meta open. The realistic short-term win-list is:

    1. Tier 1A (RuntimeRpcBinding) — biggest remaining single-PR leverage. Has the cleanest design (per-Sig template → per-Sig trampoline). I'll tackle this as a follow-up.
    2. Tier 2F (ClocklessControllerRuntime) — different leverage axis; sketches with multiple chipsets will demonstrate.

    Tier 1C/2D should be revisited once the codebase has more container instantiations OR a CI target sketch is specifically chosen to exercise them.

    What I'd recommend the next agent picking this up do

    1. Don't repeat my Tier 2D path on AutoResearch. Pick a target sketch first (something with 5+ unordered_map / flat_map instantiations — likely the WASM compiler runtime, since it touches every type in the codebase). Measure baseline, implement the type-erased core, re-measure. If still neutral, defer with clear rationale.
    2. Try Tier 1A. The RPC trampoline pattern has very different mechanics — per-call dispatch is one runtime switch on a small argument-type table, not a function-pointer-thunk-per-comparison. The leverage scales with method count, not instance count.
    3. Try Tier 2F. Per-chipset duplication is the biggest standing leverage item that's distinct from the container story.

    Reopening + commenting on the meta rather than silently letting it expire because the "≥4 of 5" math doesn't add up on a sketch-by-sketch basis.

  4. moved this from Triage to Done in FastLED Trackeron Jun 18, 2026
  5. moved this from Done to Triage in FastLED Trackeron Jun 18, 2026
  6. moved this from Triage to Done in FastLED Trackeron Jun 18, 2026
  7. zackees commented on Jun 18, 2026

    @zackees
    MemberAuthor

    Forward link: remaining Tier 1A / 2E Phase 2 / 2F / 3 G/H/I items rolled into Phase 3 burn-down at #3244.

  8. added a commit that references this issue on Jun 19, 2026
    a23ad43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions