Skip to content

fl::sstream cost-reduction audit: flip the default so FL_WARN/FL_ERROR are compiled by default #2963

Closed

Description

@zackees

Directive

FL_WARN and FL_ERROR should be compiled by default on every build. They are only stripped when:

  1. fbuild --release explicitly defines a release-strip macro (e.g. FASTLED_RELEASE_STRIP_LOGS), OR
  2. The user opts out: -DFASTLED_LOG_VERBOSITY=0 (existing knob, behavior preserved).

The current default — NDEBUG → FASTLED_LOG_VERBOSITY=0 → all FL_WARN/FL_ERROR no-op — inverts: diagnostics that only fire on optimized builds are exactly the ones users see in field reports, and stripping them in release hides production bugs.

Recent gating PRs (#2918, #2925, #2929, #2943, #2950, #2952, #2954, #2956) traded diagnostic visibility for ~10–15 KB of flash. The new direction: keep the diagnostics, reduce the per-call-site cost of using them.

Audit — current state

Call-site density (grep -rE over src/)

Macro Count
FL_WARN(...) 1,277
FL_ERROR(...) 74
FL_WARN_ONCE(...) 19
FL_INFO(...) 2
Total ~1,372

Top contributing directories:

Dir Files w/ FL_WARN/ERROR/INFO
platforms/esp/* 50
platforms/arm/* 41
fl/channels/* 14
platforms/shared/* 12
platforms/wasm/* 10
platforms/stub/* 8
fl/math/* 8
fl/audio/* 7
fl/gfx/* 6
fl/task/* 5

Macro expansion today (src/fl/log/log.h:147,173)

#define FL_WARN(X) fl::println( \
    (fl::sstream() << (fl::fastled_file_offset(__FILE__)) << "(" \
                   << int(__LINE__) << "): WARN: " << X).c_str())

Each call site emits:

  • A __FILE__ literal (path string in .rodata, often 40-80 B; deduped per TU but not across TUs unless LTO).
  • The constant prefix "(...): WARN: " (12 B, deduped).
  • An inline fl::sstream temporary on the stack (carries a fl::string with a 64-byte inline buffer → ~80 B stack frame).
  • One inlined call per << operand: fl::sstream::operator<<(...) bodies (next section).
  • A final .c_str() call which may materialise the embedded string.

fl::sstream cost vectors (in src/fl/stl/strstream.h)

Vector Where Bytes per call site (approx)
27 non-template operator<< bodies inline in header strstream.h:34-340 8-30 B per << operand used at the site
Template operator<<(const vec2<T>&), operator<<(const vector<T>&), operator<<(const span<T>&), operator<<(const fl::optional<T>&), operator<<(const fl::unordered_set<...>&), operator<<(const fl::flat_map<...>&) strstream.h:62-204 60-200 B per T instantiation per TU
Embedded fl::string mStr (always 64-byte inline buffer + heap overflow) strstream.h:369 80 B stack frame per call site
__FILE__ literal macro 40-80 B .rodata per call site

Already out-of-line (good, single-copy):

  • appendFormatted(i8/i16/i32/i64/u16/u32/u64) → strstream.cpp.hpp:62-108
  • Tile2x2_u8 / Tile2x2_u8_wrap / audio::fft::Bins formatters → strstream.cpp.hpp:12-43
  • Manipulator helpers (hex, dec, oct) → strstream.cpp.hpp:46-58

Flash projection if the default flips today (no other change)

Conservative estimate: 1,372 call sites × ~60 B per site (avg of inline body + literal + per-operand emit) = +82 KB. ESP32-S3 Blink would go from current 338 KB → ~420 KB, blowing past the #2886 target.

That's why the cost reduction has to land FIRST.

Cost reduction proposals (ordered by impact ÷ effort)

A. Push every non-template operator<< body to strstream.cpp.hpp (low-hanging)

Status: 27 non-template bodies currently inline in strstream.h. The fl::string, char*, const string&, float, double, char, signed char, unsigned char, bool, CRGB, etc. variants all live in the header.

Action: move every non-template operator<< body to strstream.cpp.hpp. Header keeps declarations only.

Cost impact: each currently-inlined body emitted at every call site that uses it collapses to a single call instruction (4 B on Xtensa, 4 B on RISC-V). For the typical FL_WARN with 4-6 << operands and ~20 B/body avg, expect 30-60 B saved per call site. At 1,372 sites = ~50-80 KB.

Risk: very low — pure refactor, identical semantics.

B. Centralise the FL_WARN prefix via a helper function

Status: every FL_WARN(X) bakes __FILE__ + __LINE__ + "(...): WARN: " inline at the call site. Each TU's instances dedup; cross-TU does not unless LTO.

Action: replace the macro expansion with a helper:

namespace fl::detail {
void log_emit(LogLevel lvl, const char* file, int line, const fl::sstream& msg) noexcept;
}

#define FL_WARN(X) fl::detail::log_emit( \
    fl::detail::LogLevel::WARN, \
    fl::fastled_file_offset(__FILE__), __LINE__, \
    fl::sstream() << X)

log_emit does the prefix formatting ONCE (inside its single compiled body) instead of inlining the prefix-format chain at every call site.

Cost impact: drops the inlined prefix-format code at each site. Estimate 15-25 B per site × 1,372 = 20-35 KB.

Risk: low — same observable output, slightly different call shape.

C. Type-erase the composite-formatter templates

Status: operator<<(const vec2<T>&), operator<<(const vector<T>&), operator<<(const span<T>&), operator<<(const optional<T>&), operator<<(const fl::unordered_set<...>&), operator<<(const fl::flat_map<...>&) are all templated — per-T per-TU instantiations.

Action: convert to a visitor pattern. Each template forwards into a non-template helper taking a callback for the per-element formatter:

namespace fl::detail {
// Non-template; one copy in the binary.
void sstream_append_container(
    sstream& s,
    const char* open, const char* sep, const char* close,
    size_t count,
    void (*format_one)(sstream&, const void*, size_t index),
    const void* opaque);
}

template <typename T>
sstream& sstream::operator<<(const fl::vector<T>& v) {
    fl::detail::sstream_append_container(
        *this, "[", ", ", "]", v.size(),
        +[](sstream& s, const void* opaque, size_t i) {
            s << static_cast<const fl::vector<T>*>(opaque)->operator[](i);
        },
        &v);
    return *this;
}

The template body is now 3-5 instructions (a lambda pointer + call). The loop / container-walk logic lives in sstream_append_container (single copy).

Cost impact: each templated container formatter today is ~80-150 B per (T × TU) instantiation. Conservative estimate: 20 KB saved across the codebase (depends heavily on how many distinct Ts are actually used in FL_WARN).

Risk: medium — slightly slower per call (one extra indirect call); behaviour preserved. Lambda + raw function pointer (not fl::function) keeps it allocation-free.

D. Replace the embedded fl::string in fl::sstream with a deferred-emit pattern

Status: fl::sstream always carries an fl::string mStr member with a 64-byte inline buffer. Each FL_WARN reserves 80 B of stack frame even when the message is short.

Action: change fl::sstream to write directly into a transient buffer owned by the log_emit helper (proposal B), OR keep the embedded string but reduce its inline-buffer size to e.g. 32 bytes (most FL_WARN messages are short).

Cost impact: stack RAM only (does NOT save flash). Matters for ISR contexts and constrained-stack RTOS tasks where 80 B per FL_WARN is significant.

Risk: low (smaller buffer) to medium (deferred-emit), depending on choice.

E. FL_WARN_LIT everywhere it applies (already exists, underused)

Status: FL_WARN_LIT(LITERAL) exists (src/fl/log/log.h:198) for fixed-message sites. Bypasses fl::sstream entirely. Today only ~30 of 1,277 FL_WARN sites use it.

Action: audit FL_WARN call sites; convert any that use ONLY a string literal (no << chain) to FL_WARN_LIT.

Cost impact: substantial — FL_WARN_LIT is essentially free (one fl::println(literal) call). A site that's FL_WARN("RMT: alloc failed") saves the entire sstream temporary + operator<< chain → ~50-80 B per converted site. If 30% of sites convert (400 sites × 60 B) = 24 KB.

Risk: zero — direct simplification at each site.

Combined projected savings

Proposal Conservative Optimistic
A: out-of-line operator<< bodies 50 KB 80 KB
B: centralised FL_WARN prefix helper 20 KB 35 KB
C: type-erase composite templates 10 KB 20 KB
D: stack-frame reduction 0 KB flash 0 KB flash (RAM only)
E: convert literal-only sites to FL_WARN_LIT 15 KB 25 KB
Total 95 KB 160 KB

Cost of flipping the default (FL_WARN/FL_ERROR compiled by default): ~+82 KB (estimated).

Net at conservative savings: 82 − 95 = −13 KB net win (i.e. enabling warnings by default actually shrinks the binary because we now have a reason to do the deduplication work).

Net at optimistic savings: 82 − 160 = −78 KB net win.

Either way, the directive is achievable without a flash budget regression IF the cost reduction lands first.

Recommended landing order

  1. Phase 1 — Proposal A (out-of-line bodies). Pure refactor; ship as one PR. Measure delta.
  2. Phase 2 — Proposal E (audit + convert literal-only FL_WARN sites). Mechanical; can ship in batches per subsystem.
  3. Phase 3 — Proposal B (centralised helper). API change; ship behind a feature flag and migrate.
  4. Phase 4 — Proposal C (type-erase composite templates). Touchy; ship one container family at a time.
  5. Phase 5 — Flip the default: NDEBUG → 1 (or a new explicit FASTLED_RELEASE_STRIP_LOGS knob driven by fbuild --release). Run the bloat regression and ratchet the baseline.
  6. Phase 6 — Revisit the #if FASTLED_LOG_RUNTIME_ENABLED gates added in perf(esp32): gate emit* cold helpers on FASTLED_LOG_RUNTIME_ENABLED (~800 B) #2918/fix(esp32): correct FASTLED_ASSERT release no-op + ratchet baseline 344769 -> 340832 #2925/perf(gamma): simplify Gamma8::getOrCreate to single-entry weak_ptr cache #2929/perf(channel): skip auto-naming in release builds (#2942) #2943/Gate emitDisabledDriverError diagnostic chain in release builds (~300-800 B) #2950/Gate resolveDynamicDriver bus-miss diagnostic probe in release builds #2952/Skip RxChannel auto-naming in release builds (companion to #2943) #2954/Gate handleAllocateTxFailure's diagnostic-only locals + suggestion blocks in release #2956. With the per-call-site cost reduced, those gates are no longer needed; remove them so the diagnostic code is always live.

Success criteria

  • ESP32-S3 Blink flash budget stays ≤ 340 KB with FL_WARN/FL_ERROR compiled by default (currently 338 KB with logs stripped — we get 2 KB of headroom).
  • Per-FL_WARN call site cost drops from ~60-80 B to ≤ 25 B (literal-string portion still counts; that's the irreducible floor for diagnostic identity).
  • fl::sstream stack frame drops from 80 B to ≤ 40 B (or document why not).
  • fbuild --release adds -DFASTLED_RELEASE_STRIP_LOGS=1 to strip; default builds keep diagnostics live.
  • Phases 5 and 6 land on the same PR (bloat measurement only meaningful with both).

Related

🤖 Generated with Claude Code

Activity

  1. added
    deferred
    on Aug 20, 2026
  2. zackees commented on Aug 20, 2026

    @zackees
    MemberAuthor

    Triaged against current master 31167ea.

    Marking deferred: the issue is materially incomplete, but later logging redesigns turned it into a stale cross-repository, multi-phase directive rather than one bounded patch.

    Current evidence:

    Restart after #2974/#2982 are resolved or explicitly re-scoped, with a current diagnostics-enabled size report, a defined FastLED/fbuild ownership contract, focused default/NDEBUG/verbosity-0/release-strip compile tests, and refreshed measured ceilings.

  3. zackees commented on Sep 24, 2026

    @zackees
    MemberAuthor

    Post-#4559 restart scope: one logging spelling without losing the flash win

    #2982 is now resolved by #4559, so the prerequisite in the deferred-status comment above is satisfied and we have a current logging-enabled baseline.

    New evidence

    ESP32-S3 Blink built with FASTLED_LOG_VERBOSITY=1, before/after #4559:

    Metric Before After Delta
    Firmware flash 473,372 B 467,328 B -6,044 B
    Symbol-attributed flash 387,006 B 381,678 B -5,328 B
    Symbol-attributed RAM 41,887 B 41,887 B unchanged
    emitRmtChannelWarning 712 B 280 B -432 B

    Disassembly confirmed that one-argument _F literal sites changed from inline sstream construction/destruction plus log_emit to direct log_emit_f<> calls.

    Remaining API problem

    The savings currently depend on keeping two spellings:

    FL_WARN("literal");    // one argument -> stream path -> sstream cost
    FL_WARN_F("literal");  // explicit format path -> direct log_emit_f

    The earlier #3272/#3273 unification made _F an alias of FL_WARN. That looked API-equivalent but silently routed one-argument _F literals back through sstream; #4559 restored the explicit fast path and recovered 5-6 KB.

    Argument-count dispatch alone cannot distinguish these two one-argument forms:

    FL_WARN("literal");
    FL_WARN("value=" << value);

    The second expression only parses because the macro injects fl::sstream() as the left operand. A function overload cannot inspect it first and then choose a literal fast path. Therefore an alias-only implementation is not sufficient.

    Proposal to investigate

    Find one public logging spelling (FL_WARN, FL_ERROR, FL_PRINT, category logs, and async-main logs) that keeps literal/format call sites on the direct formatting path. Evaluate at least:

    1. Make the unsuffixed macros format-first for every arity, using the existing type-aware {} support in fl::printf for values, and migrate stream expressions to that syntax.
    2. If downstream stream compatibility must remain, retain it behind an explicit compatibility wrapper/opt-in during a deprecation window rather than making every one-argument literal pay for sstream.
    3. Consider a compiler/macro technique only if generated code proves it distinguishes literals without constructing sstream; source-level unification alone is not evidence.

    Acceptance criteria

    • RED -> GREEN evidence: add a focused expansion/codegen test that fails today because FL_WARN("literal") reaches sstream, then passes when the unified spelling reaches the direct formatting path.
    • Remove active in-tree use of _F variants and update LegacyLogMacroChecker to enforce the single spelling; account for WARN, ERROR, PRINT, DBG where applicable, category macros, async-main macros, and IF/ONCE/EVERY wrappers.
    • Preserve output and gating semantics for FASTLED_LOG_VERBOSITY=0/1, constrained-memory targets, conditional, once, rate-limited, category, and async-main forms.
    • Document and test the downstream compatibility decision for legacy FL_WARN("x=" << x) expressions. Do not silently reinterpret % in a one-argument literal.
    • Repeat the ESP32-S3 Blink measurement with FASTLED_LOG_VERBOSITY=1 on the same toolchain. The unified spelling must retain the perf(log): keep explicit format macros off stream path #4559 win: no flash regression against the current _F implementation and at least 5,000 B saved versus the pre-perf(log): keep explicit format macros off stream path #4559 control.
    • Keep attributed RAM at or below the current 41,887 B baseline.
    • Preserve disassembly evidence for a representative multi-site function: literal calls must not contain call-site sstream construction/destruction.
    • Run focused output-equivalence tests, scoped lint, and the normal C++ validation required for the eventual implementation.

    Decisions

    Strongly related history

  4. zackees commented on Sep 24, 2026

    @zackees
    MemberAuthor

    Mandatory completion / non-regression gate

    Do not close this work based on source cleanup, successful compilation, or unit tests alone. Completion requires confirming both correctness and generated-code impact after the _F variants are removed.

    The implementation PR must provide reproducible before/after evidence from the same source revision and toolchain, differing only in the logging-dispatch implementation:

    1. Behavior is fixed

      • Focused RED -> GREEN tests prove the single public spelling selects the direct formatting path for one-argument literals.
      • Output-equivalence tests cover literal, formatted, conditional, once, rate-limited, category, and async-main logging.
      • Legacy stream-expression behavior is either preserved and tested or intentionally deprecated with a tested compatibility path and migration documentation.
      • FASTLED_LOG_VERBOSITY=0/1 and constrained-memory gating remain correct.
    2. No flash or RAM regression

      • Build ESP32-S3 Blink with FASTLED_LOG_VERBOSITY=1 using the same compiler/toolchain and flags for both variants.
      • Run bash bloat esp32s3 against both resulting ELFs and retain both reports.
      • Unified-spelling attributed flash must be no larger than the current _F fast-path implementation (381,678 B in the perf(log): keep explicit format macros off stream path #4559 measurement), subject only to a clearly explained toolchain-wide baseline movement proven by the paired build.
      • Unified-spelling firmware flash must retain at least the measured 5,000 B saving versus the pre-perf(log): keep explicit format macros off stream path #4559 control (the observed saving was 6,044 B).
      • Attributed RAM must not exceed the paired current implementation (41,887 B in the perf(log): keep explicit format macros off stream path #4559 measurement).
      • Disassembly of a representative multi-site function must show that literal logging sites do not construct/destroy sstream and route directly to the shared formatter.
    3. Repository regression gates are green

      • The focused logging test passes in quick and debug/sanitizer modes.
      • Scoped lint passes, including the updated logging-macro checker.
      • The repository's required C++ validation passes.

    If any of those measurements regress, the API consolidation is not fixed and must not merge until the regression is explained and eliminated. Absolute byte values may move as master/toolchains evolve, so the authoritative result is the paired same-SHA/same-toolchain comparison, with the #4559 artifacts retained as historical reference.

  5. zackees commented on Sep 24, 2026

    @zackees
    MemberAuthor

    The single-spelling / no-regression phase requested above is now merged in #4560 (merge commit 7f432a1).

    Paired ESP32-S3 Blink results (FASTLED_LOG_VERBOSITY=1, xtensa-esp-elf-gcc 14.2.0):

    Metric #4559 baseline Unified spelling Delta
    Firmware flash 467,328 B 466,944 B -384 B
    Attributed flash 381,726 B 381,285 B -441 B
    Attributed RAM 41,887 B 41,887 B unchanged

    This retains 6,428 B of firmware savings versus the 473,372 B pre-#4559 control. emitRmtChannelWarning remains 280 B, and disassembly shows literal branches calling log_emit_literal directly without call-site sstream construction/destruction.

    Validation: focused logging and stdio sanitizer tests, 310 unit + 95 example C++ targets, C++/Rust lint, focused Rust checker test, paired bloat reports, and final code review. The PR also removed unsafe fl::sprintf, migrated callers to fl::snprintf, and added a Rust C++ lint ban.

    Keeping #2963 open because its separately scoped later phase—compiling diagnostics by default—remains outstanding.

  6. zackees commented on Sep 24, 2026

    @zackees
    MemberAuthor

    Closing as completed by #4560. The unified logging spelling retained the #4559 flash savings, reduced paired firmware/attributed flash further, kept attributed RAM unchanged, removed fl::sprintf, and passed the documented regression gates. Measurement details: #2963 (comment)

  7. moved this from Triage to Done in FastLED Trackeron Sep 24, 2026
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

    deferred

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions