Repository navigation
refactor(deque): chunked map-of-fixed-size-blocks layout (closes #3270) - #3282
Conversation
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]>
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthrough
ChangesChunked deque rewrite
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~90+ minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
…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]>
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]>
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-sizeT[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 violatesstd::deque's "no element move on grow + stable pointer/iterator" contract: every overflow walked N elements and invalidated everyT*/ iterator.In-tree call sites that depend on
std::deque-shaped semantics:src/fl/audio/detector/transient.hdeque<float>sliding windowsrc/fl/audio/detector/tempo_analyzer.hdeque<u32>,deque<float>sliding windowssrc/fl/audio/detector/musical_beat_detector.hdeque<u32>IBI windowsrc/fl/audio/detector/downbeat.h,backbeat.hdeque<float>,deque<u8>accent windowssrc/fl/stl/json.cpp.hppdeque<char>serializer buffersrc/platforms/esp/32/drivers/parlio/channel_driver_parlio.hdeque<u8>DMA queueThese 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_sizecontrols per-type chunk size. Default forks onFL_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_capacityanddeque_physical_index(vector-style) deleted. Newdeque_grow_map_capacityis the only non-template arithmetic shared across everydeque<T>instantiation.push_back/push_frontallocate one chunk at a time when crossing a boundary; existing elements are never moved.insert/emplace/eraseroute throughpush_back+operator[]assignment so chunk-allocation tracking lives in exactly one place.insert(count, v)allocatesceil(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 ofkChunkSize), no longer element-exact.json::to_string_nativeno longer treatsdeque<char>as contiguous -- the pre-[Container shape] fl::deque<T> should be chunked, not 2x-doubling vector-ring #3270result.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-elementreserve+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 ×kChunkSizepushes;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 ×kChunkSizevalue copies; checks chunk-allocation bookkeeping and verifies pre-shift anchor stability.deque_traits<T> partial-spec override--SmallChunkTagpinschunk_size = 4; verifies capacity quantization tracks the per-type override.The existing
shrink_to_fittest was loosened fromEQtoGE/LE-- chunked capacity is chunk-quantized. Documented in the test.Verification
bash lint --cppclean (FL_NOEXCEPT added to all new methods).Flash impact (LPC845-BRK / AutoResearch)
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_indexhelper symbols (the old vector-style was already paying for a non-template helper but only had 1-2deque<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 passbash test fl_stl_deque --debug— 51/51 pass under ASAN/UBSAN (incl. 5 new tests)bash lint --cppcleanbash compile lpc845brk --examples AutoResearchsucceeds🤖 Generated with Claude Code
Summary by CodeRabbit