Skip to content

refactor(deque): chunked map-of-fixed-size-blocks layout (closes #3270) - #3282

Merged
zackees merged 1 commit into
masterfrom
feat/3270-deque-chunked
Jun 19, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3270-deque-chunked

Conversation

@zackees

@zackees zackees commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces fl::deque<T>'s vector-style contiguous-ring + 2x-doubling-realloc storage with the textbook chunked-deque layout: a small map of chunk pointers, each chunk a fixed-size T[kChunkSize] allocated independently. Existing elements are never moved on grow; only the chunk-pointer map ever reallocates. T* / iterator stability across push at either end is now provided by construction.

Closes #3270.

Why this matters

Pre-#3270 the deque was a fl::vector<T> with a ring-buffer index trick on top. That violates std::deque's "no element move on grow + stable pointer/iterator" contract: every overflow walked N elements and invalidated every T* / iterator.

In-tree call sites that depend on std::deque-shaped semantics:

Site Type
src/fl/audio/detector/transient.h deque<float> sliding window
src/fl/audio/detector/tempo_analyzer.h deque<u32>, deque<float> sliding windows
src/fl/audio/detector/musical_beat_detector.h deque<u32> IBI window
src/fl/audio/detector/downbeat.h, backbeat.h deque<float>, deque<u8> accent windows
src/fl/stl/json.cpp.hpp deque<char> serializer buffer
src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h deque<u8> DMA queue

These all use the deque as a stable-storage sliding buffer. The pre-#3270 layout would have done an O(N) move-and-deallocate inside the audio hot path on every chunk fill -- a hard real-time stall. Today it happened to work only because the windows were sized to never realloc post-warm-up; that's a fragile invariant that the chunked layout makes structural.

Design

  • fl::deque_traits<T>::chunk_size controls per-type chunk size. Default forks on FL_PLATFORM_HAS_LARGE_MEMORY (16 for low-memory targets, 64 for large-memory). Per-type override by partial specialization.
  • src/fl/stl/deque_basic.h/cpp.hpp: helper replaced. deque_grow_capacity and deque_physical_index (vector-style) deleted. New deque_grow_map_capacity is the only non-template arithmetic shared across every deque<T> instantiation.
  • push_back / push_front allocate one chunk at a time when crossing a boundary; existing elements are never moved.
  • insert / emplace / erase route through push_back + operator[] assignment so chunk-allocation tracking lives in exactly one place. insert(count, v) allocates ceil(count / kChunkSize) chunks via the same path.
  • clear() retains chunks for reuse; shrink_to_fit() releases chunks outside [front..back]. Capacity is now chunk-quantized (multiple of kChunkSize), no longer element-exact.
  • json::to_string_native no longer treats deque<char> as contiguous -- the pre-[Container shape] fl::deque<T> should be chunked, not 2x-doubling vector-ring #3270 result.assign(&json_chars[0], json_chars.size()) was UB even on the old layout after a wraparound; the chunked layout makes it an immediate buffer overrun. Replaced with per-element reserve + push_back.

Acceptance tests (tests/fl/stl/deque.cpp)

5 new test cases covering the issue's acceptance bullets:

  • pointer stability across push_back grow -- 10 × kChunkSize pushes; T* taken at insertion still dereferences to the original value.
  • pointer stability across push_front grow -- exercises the front-grow path (mFrontMapIdx / mFrontOffset).
  • push_back across chunk boundary -- verifies the boundary-crossing allocation does not disturb the prior chunk.
  • insert(count) allocating multiple chunks -- 3 × kChunkSize value copies; checks chunk-allocation bookkeeping and verifies pre-shift anchor stability.
  • deque_traits<T> partial-spec override -- SmallChunkTag pins chunk_size = 4; verifies capacity quantization tracks the per-type override.

The existing shrink_to_fit test was loosened from EQ to GE/LE -- chunked capacity is chunk-quantized. Documented in the test.

Verification

Flash impact (LPC845-BRK / AutoResearch)

Metric Post-#3267 master This branch Delta
Flash (.bin) 46,864 B 46,500 B −364 B
Flash % of 64 KB 71.5% 71.0% −0.5%

The issue predicted "slightly larger -- chunked deques are not a flash-size win, they are a correctness + real-time-safety win". The actual measurement on LPC845 is a small flash decrease, driven by the removal of the deque_grow_capacity / deque_physical_index helper symbols (the old vector-style was already paying for a non-template helper but only had 1-2 deque<T> instantiations to amortize it across, per meta #3244's lesson-learned). Net: the chunked layout is at least neutral on flash for the current low-memory link profile.

Test plan

  • bash test --cpp — 331/331 pass
  • bash test fl_stl_deque --debug — 51/51 pass under ASAN/UBSAN (incl. 5 new tests)
  • bash lint --cpp clean
  • bash compile lpc845brk --examples AutoResearch succeeds
  • CI green across full platform matrix (waiting on this PR's CI)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Fixed JSON serialization compatibility

Replaces fl::deque<T>'s vector-style contiguous-ring + 2x-doubling-realloc
storage with the textbook chunked-deque layout: a small map of chunk
pointers, each chunk a fixed-size T[kChunkSize] allocated independently.
Existing elements are never moved on grow; only the chunk-pointer map
ever reallocates. T* / iterator stability across push at either end is
now provided by construction.

Key changes
- New `fl::deque_traits<T>::chunk_size` controls per-type chunk size, with
  a `FL_PLATFORM_HAS_LARGE_MEMORY` default fork (16 for low-memory
  targets, 64 for large-memory). Per-type override by partial spec.
- `src/fl/stl/deque_basic.h/cpp.hpp`: helper replaced. `deque_grow_capacity`
  and `deque_physical_index` deleted (vector-style); new
  `deque_grow_map_capacity` non-template doubling helper handles chunk-map
  growth across every deque<T> instantiation.
- `push_back` / `push_front` allocate one chunk at a time; never move
  existing elements. `insert` / `emplace` / `erase` route through
  push_back + operator[] assignment so chunk allocation lives in exactly
  one place. `clear()` retains chunks for reuse; `shrink_to_fit()`
  releases chunks outside [front..back].
- `json::to_string_native` no longer treats deque<char> as contiguous --
  the pre-#3270 `result.assign(&json_chars[0], json_chars.size())` was
  UB even on the old layout after a wraparound; the chunked layout makes
  it an immediate buffer overrun. Replaced with per-element reserve +
  push_back.

Acceptance tests (`tests/fl/stl/deque.cpp`)
- Pointer stability across push_back grow (10 * kChunkSize pushes;
  T* taken at insertion still dereferences to the original value).
- Pointer stability across push_front grow.
- push_back across exact chunk boundary (verifies the boundary-crossing
  allocation does not disturb the prior chunk).
- insert(count) allocating multiple chunks (3 * kChunkSize values).
- deque_traits<T> partial-spec override (SmallChunkTag pins chunk_size=4).
- `shrink_to_fit` capacity test loosened from `EQ` to `GE`/`LE` --
  chunked capacity is chunk-quantized (multiple of kChunkSize), no longer
  element-exact. Documented in the test.

Verification
- 331/331 unit tests pass (incl. 5 new #3270 tests, debug + ASAN/UBSAN).
- bash lint --cpp clean (FL_NOEXCEPT added to all new methods).
- LPC845-BRK AutoResearch flash: 46500 B (was 46864 B post-#3267).

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

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

fl::deque<T> is rewritten from a contiguous ring-buffer (single allocation, mFront index) to a map-of-fixed-size-chunks layout. A per-type deque_traits<T>::chunk_size controls chunk sizing; a new deque_grow_map_capacity helper replaces the old deque_grow_capacity/deque_physical_index helpers. All public API is updated to route through locate into the chunk map. json::to_string_native is adapted for non-contiguous storage. New tests cover pointer stability, chunk boundary behavior, multi-chunk insert, and per-type trait overrides.

Changes

Chunked deque rewrite

Layer / File(s) Summary
Chunk-map grow-policy contract
src/fl/stl/deque_basic.h, src/fl/stl/deque_basic.cpp.hpp
Removes kDequeInitialCapacity, deque_physical_index, and deque_grow_capacity; introduces kDequeInitialMapCapacity = 4 and deque_grow_map_capacity(current_map_capacity, min_required_chunks) with overflow-safe doubling saturation.
Core chunked storage internals
src/fl/stl/deque.h (lines 5–163)
Introduces deque_traits<T>::chunk_size and kChunkSize; replaces mData/mCapacity/mFront fields with mMap/mMapCapacity/mFrontMapIdx/mFrontOffset; adds locate, allocate_chunk, deallocate_chunk, allocate_map, deallocate_map, grow_map, ensure_back_room, and ensure_front_room.
Public API: constructors, destructor, move assignment, element access, capacity
src/fl/stl/deque.h (lines 371–586)
Rewrites destructor to tear down all chunk pointers and mMap; overhauls move assignment to deallocate before ownership transfer; routes operator[], at, iterators, capacity, reserve, shrink_to_fit, and clear through the chunked locate/mMap model.
Mutation operations
src/fl/stl/deque.h (lines 587–839)
Updates push_back, push_front, pop_back, pop_front, resize, swap, insert, erase, and emplace operations to allocate/release chunks and update mFrontOffset/mFrontMapIdx under the chunked layout.
JSON adaptation and acceptance tests
src/fl/stl/json.cpp.hpp, tests/fl/stl/deque.cpp
Fixes json::to_string_native to iterate per-character instead of dereferencing a contiguous pointer; adds SmallChunkTag trait specialization and new tests for pointer stability, chunk-boundary behavior, multi-chunk insert, and per-type chunk_size override.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant DequeT as deque
  participant ChunkMap as mMap
  participant Chunk as T_chunk

  Caller->>DequeT: push_back(value)
  DequeT->>DequeT: ensure_back_room()
  alt back chunk is full or missing
    DequeT->>Chunk: allocate_chunk()
    DequeT->>ChunkMap: mMap[new_back_idx] = chunk
  end
  DequeT->>Chunk: construct at mMap[c][o]
  DequeT-->>Caller: element constructed, no existing elements moved

  Caller->>DequeT: operator[](logical_idx)
  DequeT->>DequeT: locate(logical_idx) returns chunk_idx and offset
  DequeT->>ChunkMap: mMap[chunk_idx]
  ChunkMap->>Chunk: offset
  Chunk-->>Caller: T ref
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3267: The predecessor PR that introduced deque_basic.h/deque_basic.cpp.hpp with deque_physical_index and deque_grow_capacity, which this PR replaces with deque_grow_map_capacity and chunk-map arithmetic.

Poem

🐰 Hop, hop, a chunk at a time,
No more ring-buffer juggling rhyme!
Each pointer stands stable and true,
While the map grows by doubling through.
The deque is chunked, neat and right—
A real-time safe, embedded delight! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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: refactoring deque from a vector-style contiguous buffer to a chunked map-of-fixed-size-blocks layout, and correctly references the resolved issue #3270.
Linked Issues check ✅ Passed The PR fully satisfies all coding requirements from #3270: chunked map-of-fixed-size-blocks implementation with O(1) push operations, pointer stability across grows, configurable chunk size via deque_traits, per-type override support, all existing tests passing, and JSON/audio-detector integration verified.
Out of Scope Changes check ✅ Passed All changes are scoped to deque implementation internals (deque.h, deque_basic.h/cpp.hpp), JSON buffer conversion (json.cpp.hpp to handle non-contiguous storage), and deque tests. No unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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/3270-deque-chunked

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.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 19, 2026
@zackees
zackees merged commit a8b5cac into master Jun 19, 2026
8 of 10 checks passed
@zackees
zackees deleted the feat/3270-deque-chunked branch June 19, 2026 19:16
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 19, 2026
zackees added a commit that referenced this pull request Jun 19, 2026
…ak (closes #3286) (#3289)

Regression introduced by #3282 (chunked map-of-fixed-size-blocks layout,
commit a8b5cac). Surfaced as macOS-arm64 unit test failure
fl_audio_detectors with ASAN LeakSanitizer reporting ~5KB leaked in 20
allocations, all rooted in fl::deque<float>::ensure_back_room() →
DefaultMemoryResource::do_allocate(). Linux x86-64 jobs don't run
leak-detection, so the regression only tripped CI on the macos workflow.

Root cause
----------
`pop_front()` / `pop_back()` advance mFrontMapIdx / mSize past an
emptied chunk without freeing or nulling the chunk pointer. The chunk
is left orphaned in mMap[]. The destructor sweeps the entire map so
orphans are harmless as long as the map itself survives.

But `grow_map()` only copies pointers in [mFrontMapIdx,
mFrontMapIdx+used) forward into the new map; it then deallocates the
old map. Every orphaned chunk pointer outside that range is silently
lost, leaking its backing storage.

The audio TempoAnalyzer hits this directly: mOnsetTimes (50-entry
sliding window) and mBPMHistory (20-entry sliding window) do
push_back + pop_front each frame. After enough frames, an old chunk
gets orphaned, then a later push_back forces grow_map, then the orphan
leaks.

Fix
---
In `grow_map()`, after a successful new-map allocation but before
deallocating the old map, free any chunk pointers in the old map that
fall outside the live [mFrontMapIdx, mFrontMapIdx+used) range. The
live range still copies forward unchanged, so chunk addresses remain
stable for elements that survive a grow (preserving the #3270 design
intent of pointer / iterator stability).

Test
----
tests/fl/stl/deque.cpp gains `fl::deque - grow_map releases orphaned
chunks (#3286)`. It uses SmallChunkTag (chunk_size=4) to reproduce the
push/pop/push-grow leak pattern in a few dozen ops instead of the
thousands needed at the default chunk_size=64; ASAN under macOS-arm64
flags the leak immediately on the broken code.

Verification
- bash test fl_stl_deque --debug → pass (Windows clang+ASAN)
- bash test fl_audio_detectors --debug → pass (Windows clang+ASAN)
- bash lint --cpp → clean

References
- Breaking PR: #3282 (commit a8b5cac)
- Regression issue: #3286

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jul 29, 2026
CodeRabbit review catch on #3759, and it was a hole in the HARD-FAIL
tier rather than a cosmetic gap.

find_element_address_uses parsed exactly one identifier after `&`, then
bailed whenever the following token was a `.`/`->` whose member was not
at/front/back. So `&this->mQueue[0]`, `&obj.mQueue[0]` and
`&state.inner.mQueue[2]` never reached the declaration lookup at all.
Members are the common shape for fl::deque FIELDS -- which is precisely
why the checker scans declarations across the whole file -- so the tier
meant to gate the #3282/#3286 UB could miss it.

The scanner now walks the full receiver chain and re-anchors on each
member, treating the LAST identifier before the subscript or accessor as
the container. An accessor call (`.front()`, `.at(...)`) terminates the
chain; a plain member access continues it.

Verified with an end-to-end probe: `&this->mQueue[0]`, `&mQueue[0]`,
`this->mQueue.data()`, `&this->mQueue.front()`, `&obj.mQueue[0]` and
`obj.mQueue.data()` all flag hard; `&this->mVec[0]` flags warn;
`this->mVec.data()`, `&raw[0]`, `&&` and bitwise `&` all stay clean --
7 hits, exactly as expected, up from 3 before the fix.

Tree counts are unchanged: still 0 hard-fail and 7 warn-only, so no
existing deque member misuse was hiding behind the gap and the hard-fail
tier remains safe to land.

Also fixes 4 byte constants that reached the file as literal tabs rather
than `\t` escapes, which broke the build.

Co-Authored-By: Claude <[email protected]>
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.

[Container shape] fl::deque<T> should be chunked, not 2x-doubling vector-ring

1 participant