Repository navigation
feat(log): centralised log_emit helper (Proposal B Option 3 of #2963) - #2968
Conversation
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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughCentralizes 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. ChangesLogging Macro Centralization
Gamma8 LUT construction and fast-path
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/fl/log/log.cpp.hppsrc/fl/log/log.h
… 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.
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
src/fl/math/ease.cpp.hpp
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.
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_emithelper. Lifetime-safe variant of the Option 1 attempt that hit ASAN on PR #2964.What changes
Macros now expand to one helper call:
fl::detail::log_emitrebuilds the prefixed result IN PLACE inside body — the FL_WARN-caller's temporary:Why this is lifetime-safe (and Option 1 wasn't)
PR #2964's Option 1 built the result in a
fl::sstream prefixedLOCAL 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'sfl::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 tofl::printlnhas the same lifetime guarantee as before.Why
FL_NO_INLINEmattersWithout 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
#if FASTLED_LOG_RUNTIME_ENABLEDgating PRs. Phase 6 of fl::sstream cost-reduction audit: flip the default so FL_WARN/FL_ERROR are compiled by default #2963.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).<<chain, FL_ERROR, FL_INFO, FASTLED_WARN/ERROR/INFO, FL_WARN_ONCE, FL_WARN_IF, FL_WARN_LIT.bash compile esp32s3 --examples Blink --platformiosucceeds in ~1m45s.test / buildASAN job) — the design proof. Will report once it settles.Related
🤖 Generated with Claude Code
Summary by CodeRabbit
Chores
Bug Fixes / Improvements
Tests