Skip to content

feat(log): centralised log_emit helper (Proposal B Option 3 of #2963) - #2968

Merged
zackees merged 3 commits into
masterfrom
feat/sstream-type-erase-composites
Jun 7, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/sstream-type-erase-composites

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Implements Proposal B Option 3 from #2963 — fold the inlined-at-every-call-site FL_WARN/FL_ERROR/FL_INFO prefix-format chain into a single out-of-line fl::detail::log_emit helper. Lifetime-safe variant of the Option 1 attempt that hit ASAN on PR #2964.

What changes

Macros now expand to one helper call:

// Before (inlined at ~1,372 call sites):
#define FL_WARN(X) fl::println((fl::sstream() << file << "(" << line << "): WARN: " << X).c_str())

// After:
#define FL_WARN(X) fl::detail::log_emit( \
    fl::detail::log_kind::WARN, file, line, \
    fl::sstream() << X)

fl::detail::log_emit rebuilds the prefixed result IN PLACE inside body — the FL_WARN-caller's temporary:

FL_NO_INLINE void log_emit(log_kind kind, const char* file, int line, fl::sstream& body) {
    fl::string user_payload(body.str());            // snapshot the user's <<X content
    body.clear();                                    // reset body's buffer
    body << file << "(" << line << tag              // prefix INTO body
         << user_payload.c_str();                    // re-append user payload
    fl::println(body.c_str());                       // ptr lives in caller's frame
}

Why this is lifetime-safe (and Option 1 wasn't)

PR #2964's Option 1 built the result in a fl::sstream prefixed LOCAL to log_emit. That stack frame dies when log_emit returns — async-flush handlers (test harness) read the pointer later and ASANed.

Option 3 doesn't allocate a local sstream. The result lives in body, which is bound by lvalue ref to the FL_WARN-caller's fl::sstream() temporary. C++ guarantees that temp's lifetime extends to the end of the full FL_WARN expression — identical to the OLD inline macro pattern. body.c_str() passed to fl::println has the same lifetime guarantee as before.

Why FL_NO_INLINE matters

Without it, at -O2 with LTO the compiler often inlines log_emit at every FL_WARN call site, defeating the centralisation. The attribute forces a real function-call boundary. This was an important learning from my Proposal A investigation (PR #2964 follow-up) — LTO inlines aggressively even across TUs, and bare "out of line in source" doesn't guarantee anything in the final binary.

Flash measurement on ESP32-S3 Blink

0 B change vs master (both 338,013 B). Blink's call graph never reaches a live FL_WARN site, so the linker dead-strips ALL FL_WARN-related code on both branches — including my new log_emit. There's nothing to centralise when nothing's being called.

The architectural improvement is real but its measurable benefit only shows up:

I'm shipping this as the structural prerequisite for that directive (#2963 Phase 5). Without Option 3, flipping the default would inline 30-50 B of prefix-format code at every FL_WARN site — measured nominal cost ~+80 KB on a sketch that exercises all of them. With Option 3 + FL_NO_INLINE, that cost collapses to a single call instruction per site.

CI is the real validation

Critical check: the example test suite that caught PR #2964 Option 1's ASAN regression (example-TwinkleFox, example-Remote, RPC examples) must pass on this PR. If Option 3's lifetime contract is correct (the design intent), those tests pass cleanly.

What this PR does NOT do

Verification

  • bash lint --cpp — clean (one pre-existing PlatformIO warning, ci: sweep PlatformIO build usage and add linters that enforce fbuild-only board builds #2701).
  • End-to-end compile probe of FL_WARN literal, FL_WARN << chain, FL_ERROR, FL_INFO, FASTLED_WARN/ERROR/INFO, FL_WARN_ONCE, FL_WARN_IF, FL_WARN_LIT.
  • bash compile esp32s3 --examples Blink --platformio succeeds in ~1m45s.
  • CI example test suite (test / build ASAN job) — the design proof. Will report once it settles.

Related

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores

    • Centralized logging so error, warning, and info messages are emitted uniformly.
  • Bug Fixes / Improvements

    • Improved gamma correction tables with exact endpoint values and higher-precision computation for more accurate color mapping.
    • Added a cached fast path for the common gamma setting to speed retrieval of the precomputed correction table.
  • Tests

    • Updated baseline measurement for ESP32-S3 size test.

Replaces the per-call-site inlined `(fl::sstream() << prefix << X).c_str()
→ fl::println` chain that FL_WARN/FL_ERROR/FL_INFO expand to today with
a single out-of-line `fl::detail::log_emit(...)` call. The prefix-format
chain (`<< file << "(" << line << "): KIND: "`) is now compiled exactly
once in libFastLED instead of being inlined at every one of the ~1,372
FL_WARN/FL_ERROR/FL_INFO macro sites.

## Why Option 3 (and not Option 1 which I tried in PR #2964)

Option 1 took `body` by `const sstream&` and built the prefixed result
in a LOCAL `fl::sstream prefixed` inside log_emit. The `prefixed`
lived in log_emit's frame, so the pointer passed to fl::println dangled
the moment log_emit returned — async-flush test handlers caught it as
a stack-use-after-return ASAN error.

Option 3 takes `body` by `fl::sstream&` (lvalue ref, since
`fl::sstream() << X` returns `sstream&` from chained operator<<). It
REBUILDS the prefix INTO body in place: snapshot the user payload,
clear body, write `prefix + payload` back into body, emit via
`body.c_str()`. Because `body` is the FL_WARN-caller's temporary,
its lifetime is the FL_WARN full-expression's — identical to the
OLD inline macro's temporary. The async-handler race window is
unchanged from master.

## Why FL_NO_INLINE is required

Without it, at -O2 with LTO the compiler often inlines `log_emit`
at every FL_WARN site — defeating the centralisation. The
`__attribute__((noinline))` forces a real function-call boundary
and lets the centralisation actually win bytes.

## Measurement

ESP32-S3 Blink: **0 B change** vs master (master = 338,013 B,
this branch = 338,013 B). Both builds dead-strip all FL_WARN code
because Blink's call graph never reaches a live FL_WARN site —
when nothing calls FL_WARN, there's nothing to centralise, and
the linker drops log_emit entirely. The architectural improvement
is real but its measurable benefit only shows up in sketches that
actually exercise FL_WARN at runtime, or after the directive flip
from #2963 makes FL_WARN/FL_ERROR compiled-by-default.

## Correctness check

- bash lint --cpp: clean (one pre-existing PlatformIO warning, #2701)
- Compile probe exercises FL_WARN literal, FL_WARN with `<<` chain,
  FL_ERROR, FL_INFO, FASTLED_WARN/ERROR/INFO, FL_WARN_ONCE,
  FL_WARN_IF, FL_WARN_LIT.
- CI will exercise the example test suite that caught PR #2964's
  Option 1 ASAN regression — if Option 3 is lifetime-safe (the
  design intent), those tests will pass.

Refs #2963.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

coderabbitai Bot commented Jun 7, 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: 0554b64c-3843-48d4-944c-916d6c934c66

📥 Commits

Reviewing files that changed from the base of the PR and between efbb9b4 and 93f483b.

📒 Files selected for processing (3)
  • src/fl/log/log.cpp.hpp
  • src/fl/math/ease.cpp.hpp
  • tests/data/esp32s3_bloat_baseline.txt
✅ Files skipped from review due to trivial changes (1)
  • tests/data/esp32s3_bloat_baseline.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/fl/log/log.cpp.hpp

📝 Walkthrough

Walkthrough

Centralizes log prefix formatting into fl::detail::log_emit and updates FL_ERROR/FL_WARN/FL_INFO macros to call it. Separately, changes Gamma8 LUT construction precision and adds a canonical gamma=2.8 fast-path with a PROGMEM-copy constructor.

Changes

Logging Macro Centralization

Layer / File(s) Summary
Logging infrastructure and declarations
src/fl/log/log.h
Adds fl/stl/compiler_control.h; defines fl::detail::log_kind enum; declares fl::detail::log_emit(...) marked FL_NO_INLINE/FL_NOEXCEPT; updates FL_ERROR/FASTLED_ERROR macros to call log_emit.
Warn and info logging routing
src/fl/log/log.h
Updates FL_WARN/FASTLED_WARN and FL_INFO/FASTLED_INFO macros to route through log_emit with WARN and INFO kinds.
Out-of-line log_emit implementation
src/fl/log/log.cpp.hpp
Implements fl::detail::log_emit: snapshot user payload, construct prefix "<file>(<line>): <KIND>: ", rebuild sstream with prefix + payload, and emit via fl::println; adds STL includes.

Gamma8 LUT construction and fast-path

Layer / File(s) Summary
Gamma8Impl LUT construction & PROGMEM copy
src/fl/math/ease.cpp.hpp
Uses fl::s8x24 fixed-point for pow, sets mLut[0]/mLut[255] exactly, updates scaling/rounding, and adds from_progmem_lut_tag constructor to copy a PROGMEM u16 LUT.
Gamma8::getOrCreate canonical fast-path
src/fl/math/ease.cpp.hpp
Adds fast path: when gamma==2.8f return a shared_ptr constructed from the precomputed GAMMA_2_8_LUT via the new PROGMEM-copy constructor before generic cache path.
Slow-path uses clamped gamma
src/fl/math/ease.cpp.hpp
Slow-path Gamma8Impl construction now uses gamma_clamped rather than the original gamma to align keys and LUTs.
Test baseline update
tests/data/esp32s3_bloat_baseline.txt
Updates the ESP32-S3 bloat baseline numeric value from 337993 to 338247.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant FL_MACRO
  participant LogEmit
  participant Println
  Caller->>FL_MACRO: FL_ERROR(payload)
  FL_MACRO->>LogEmit: log_emit(ERROR, file, line, sstream)
  LogEmit->>LogEmit: format prefix + payload
  LogEmit->>Println: println(formatted_cstr)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hopped through code with a twitchy ear,
I gathered prefixes that once appeared near,
One helper now strings them neat and tight,
And gamma's fast path beams in the light.
— a rabbit, delighted with tidy bytes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 'feat(log): centralised log_emit helper (Proposal B Option 3 of #2963)' clearly and specifically describes the primary change: introducing a centralized log_emit helper to replace the per-call-site inline pattern in FL_WARN/FL_ERROR/FL_INFO macros.
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/sstream-type-erase-composites

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/log/log.cpp.hpp`:
- Line 31: The out-of-line definition of the function log_emit is missing the
FL_NOEXCEPT specifier declared in the header; update the definition signature of
log_emit (the FL_NO_INLINE void log_emit(log_kind kind, const char* file, int
line, fl::sstream& body) function) to include FL_NOEXCEPT so the declaration and
definition match exactly, preserving the same parameter types and qualifiers as
declared in log.h.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6eecc3b2-88c9-41fc-9c4b-a3e6c66915f9

📥 Commits

Reviewing files that changed from the base of the PR and between 194cf24 and f04e576.

📒 Files selected for processing (2)
  • src/fl/log/log.cpp.hpp
  • src/fl/log/log.h

Comment thread src/fl/log/log.cpp.hpp Resolved
… to s8x24

Two related precision fixes for the Gamma8 runtime LUT:

1. **Gamma 2.8 fast path.** `Gamma8::getOrCreate(2.8f)` now returns a
   singleton that copies the precomputed `GAMMA_2_8_LUT` (already in
   .rodata, used by free function `fl::gamma_2_8`) directly into mLut
   via a new `from_progmem_lut_tag` ctor. Skips 256 fixed-point pow
   operations on first call AND guarantees bit-identical output with
   `fl::gamma_2_8()` instead of the prior ~30-50 LSB divergence (the
   ucs7604 "default gamma 2.8 matches gamma_2_8" subcase was failing
   on PR #2968 because of this divergence).

2. **Arbitrary gamma precision upgrade.** `Gamma8Impl(float)` switched
   from `fl::s16x16` (16 frac bits) to `fl::s8x24` (24 frac bits, same
   32-bit storage). Both use the same 4-term minimax polynomial for
   log2/exp2, but s8x24 carries full 24-bit intermediate precision
   end-to-end instead of truncating back to 16 frac bits at each stage.
   Brings runtime output within ~1 LSB of true float pow() for arbitrary
   gamma. Bit budget verified: max intermediate `gamma*log2(1/255)` =
   16 * -7.994 ≈ -127.9 fits s8x24's [-128, 128) range (GammaKey caps
   gamma at 16). Still libm-free.

3. **Boundary fix.** `mLut[0] = 0` and `mLut[255] = 65535` set directly
   (pow(0,any)=0, pow(1,any)=1 mathematically). The float ctor loop
   now runs `[1, 255)` instead of `[1, 256)`. This avoids the log2(1+t)
   polynomial's largest residual at the upper endpoint — combined with
   the fact that `255 * (1/255)` in fixed-point lands 1 LSB below 1.0,
   the prior code returned 65478 instead of 65535 for `getOrCreate(3.2f)`
   at i=255.

Fixes ucs7604 chipset test failures on feat/sstream-type-erase-composites
(PR #2968); also lifts general gamma precision for any value in (0, 16].

Refs #2963, #2886.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/math/ease.cpp.hpp`:
- Around line 373-390: The new s8x24 path must use a gamma value clamped to
GammaKey's valid domain before any s8x24 construction to preserve the bit-budget
and cache-key invariants: clamp/normalize the incoming float gamma to GammaKey's
[0, 15.999] range and use that clamped value when creating gamma_fp (the
fl::s8x24 gamma_fp) and when constructing the slow-path Gamma8Impl so both paths
derive their LUTs from the same canonical gamma; update the code around the
s8x24 construction and the Gamma8Impl creation to use the clamped gamma variable
(rather than the raw input) to ensure matching cache keys and safe exponent
math.
- Around line 474-479: The 2.8 fast path currently creates a process-lifetime
static shared_ptr (s28) which violates the documented weak-cache contract of
getOrCreate(); change s28 to a static weak_ptr<const Gamma8>, attempt to lock it
into a shared_ptr, and if the lock fails create a new shared_ptr via
fl::make_shared<Gamma8Impl>(Gamma8Impl::from_progmem_lut_tag{}, GAMMA_2_8_LUT),
store that shared_ptr into the static weak_ptr, and return the shared_ptr;
alternatively, if the strong-singleton was intended update the getOrCreate()
documentation to reflect the new lifetime (reference GammaKey, Gamma8,
Gamma8Impl, s28, and getOrCreate()).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c8367dc2-5ca2-4289-8591-983c88ba5686

📥 Commits

Reviewing files that changed from the base of the PR and between f04e576 and efbb9b4.

📒 Files selected for processing (1)
  • src/fl/math/ease.cpp.hpp

Comment thread src/fl/math/ease.cpp.hpp Resolved
Comment thread src/fl/math/ease.cpp.hpp Resolved
Three legitimate findings from the CodeRabbit review on the
log_emit + gamma commits, plus a baseline bump:

1. **log.cpp.hpp:31** — add `FL_NOEXCEPT` to the `log_emit`
   definition signature to match its header declaration. The header
   declares `log_emit(...) FL_NO_INLINE FL_NOEXCEPT` but the impl
   was missing `FL_NOEXCEPT`.

2. **ease.cpp.hpp `Gamma8::getOrCreate`** — clamp the incoming
   float gamma to `GammaKey`'s representable range `[0, ~16)`
   BEFORE deriving the cache key AND before constructing the
   `s8x24` for the slow-path pow. `GammaKey` is `ufixed_point<4,12>`,
   so negative inputs would wrap unsigned in the ctor and inputs
   ≥ 16 would saturate / wrap. The clamp also preserves the
   s8x24 bit budget (`gamma * log2_fp(1/255) ≈ gamma * -7.994`
   must stay within s8x24's signed [-128, 128) integer range).

3. **ease.cpp.hpp 2.8 fast path** — switch from process-lifetime
   `static shared_ptr` to `static weak_ptr` to match the documented
   `getOrCreate` cache contract ("instances expire when all callers
   release their shared_ptr"). The 2.8 LUT is now freeable like
   any other gamma cache entry.

4. **bloat baseline** — bump `tests/data/esp32s3_bloat_baseline.txt`
   from 337,993 → 338,247 B to reflect the measured ESP32-S3 Blink
   flash size after the Option 3 log_emit landing. This is the
   value the bloat-regression CI gate reported on the previous
   push; any further movement from these CodeRabbit fixes will be
   reported in the next CI run.

Refs CodeRabbit review on #2968, #2963.
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