Skip to content

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

Closed

Description

@zackees

Problem

fl::deque<T> (src/fl/stl/deque.h) is structurally a single contiguous ring buffer that doubles its capacity on overflow — i.e. a fl::vector<T> with a mFront index trick on top. PR #3267 (deque_basic Tier 3H) made the grow-arithmetic non-template but did not change the shape.

The grow body today:

// detail::deque_grow_capacity
fl::size next = current_capacity == 0
                    ? kDequeInitialCapacity   // = 8
                    : current_capacity * 2;
while (next < min_required) { next *= 2; }
return next;
// fl::deque<T>::ensure_capacity
T* new_data = allocate(new_capacity * sizeof(T));   // one contiguous slab
for (i in [0, mSize)) { new(new_data[i]) T(move(mData[old_idx])); mData[old_idx].~T(); }
deallocate(mData, mCapacity * sizeof(T));

That is not the right shape for a deque. std::deque is specified as a sequence container with O(1) push_front / push_back where existing elements are never moved on grow and references / pointers to elements remain stable across insertions at either end. The current implementation violates both: every overflow walks N elements and invalidates every pointer / iterator that wasn't sourced from the new allocation.

Why the shape matters here

In-tree call sites that are demonstrably the wrong shape under doubling-realloc:

Site Type Pattern
src/fl/audio/detector/transient.h:62 deque<float> Sliding energy-history window
src/fl/audio/detector/tempo_analyzer.h:69 deque<u32> Sliding onset-time window
src/fl/audio/detector/tempo_analyzer.h:84 deque<float> Sliding BPM-history window
src/fl/audio/detector/musical_beat_detector.h:157 deque<u32> Sliding inter-beat-interval window
src/fl/audio/detector/downbeat.h:127,131 deque<float>, deque<u8> Sliding beat-accent / meter-candidate windows
src/fl/audio/detector/backbeat.h:149,150 deque<float> × 2 Sliding backbeat-accent windows
src/fl/stl/json.cpp.hpp deque<char> Streaming-parse working buffer
src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h deque<u8> DMA byte queue

Every audio-detector deque is a fixed-cadence sliding window. Under doubling-realloc, hitting capacity inside the ISR / audio-thread hot path triggers a synchronous O(N) move-and-deallocate, which on an embedded target is a hard real-time stall the audio pipeline cannot absorb. Today it works only because the windows are sized such that the realloc happens once at warm-up and then never again — i.e. the deque is being used as if it were stable-storage, which is exactly the contract a real chunked deque provides cheaply.

Proposed shape

Replace the contiguous-slab + doubling-realloc strategy with the textbook map-of-fixed-size-chunks layout:

  • T* chunks[] — small map of chunk pointers (itself a small contiguous array; reallocated rarely, only when the chunk-map fills up).
  • Each chunk is a fixed-size T[kDequeChunkSize] allocated independently.
  • push_back / push_front allocate one new chunk when the active end-chunk is full. Existing elements are never moved.
  • Multi-element insert (insert, resize(n)) allocates ceil(needed / kDequeChunkSize) new chunks in one go.
  • kDequeChunkSize is a compile-time constant with an overridable default:
    • Default: 16 for !FL_PLATFORM_HAS_LARGE_MEMORY (LPC845, ESP8266, AVR), 64 for Large-memory (Teensy, ESP32, host).
    • Per-type override via partial-spec fl::deque_traits<T>::chunk_size or a compile-time template parameter, so audio detectors that know their window size can pin chunk-size to match.

Acceptance criteria

  • fl::deque<T> reimplemented as a map-of-chunks. Element access remains O(1); the map lookup is one indirection followed by intra-chunk indexing.
  • push_back / push_front are O(1) with no element moves. Verified by a unit test that pushes 10 × kDequeChunkSize items and asserts that pointers to previously-inserted elements remain valid (T* taken at insertion time still dereferences to the same value after subsequent pushes).
  • kDequeChunkSize default fork on FL_PLATFORM_HAS_LARGE_MEMORY (16 vs 64).
  • Per-type override mechanism wired (either deque_traits<T>::chunk_size partial-spec or template parameter — author's choice).
  • All existing deque tests (tests/fl/stl/deque/*) pass unchanged. New tests cover: pointer stability across grow, chunk-boundary push/pop, multi-element insert allocating multiple chunks, iterator validity across grow.
  • No regression in the json / parlio / audio-detector call sites. bash test --cpp green.
  • LPC845-BRK / AutoResearch flash impact recorded. Expected: slightly larger (chunk-map + chunk-allocation bookkeeping) but bounded — chunked deques are not a flash-size win, they are a correctness + real-time-safety win.

Migration plan for current call sites

The current deque<T>::operator[], front(), back(), begin(), end(), iterator semantics, and size() / empty() are externally observable. Preserving them is the migration plan: the rewrite is opaque to every existing caller as long as the external API stays byte-identical. The iterator must internally carry (chunk_map_idx, intra_chunk_idx) instead of a single mIndex, but its public operators (++, --, +=, -=, *, ->, comparison) keep the same signatures.

The two intentionally-removed semantics are:

  1. data() — does not exist on a chunked deque (no contiguous storage). Verify no caller uses it. (std::deque also does not expose data().)
  2. Pointer / iterator invalidation rules — change from "invalidated on any grow" to "stable across push at either end; invalidated only on element relocation in the middle." This is a strengthening of the contract; no existing caller can depend on the weaker rule being wrong.

Out of scope

  • fl::queue<T> (which defaults its container to fl::deque<T>) — gets the new shape for free; no changes needed.
  • The deque_basic non-template helper from PR perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #3244 Tier 3H) #3267 — entirely replaced by chunk-arithmetic helpers (deque_chunk_index, deque_grow_chunkmap). The deque_grow_capacity body in src/fl/stl/deque_basic.cpp.hpp is deleted as part of this work.
  • Allocator customization beyond the existing memory_resource* — chunk allocation uses the same resource the deque was constructed with.
  • shrink_to_fit aggressive chunk-release — first pass releases empty end-chunks on pop_back / pop_front; further compaction is a follow-up.

Risk

  • The audio-detector sliding-window pattern may be deliberately sized to never realloc today. The chunked version will allocate chunks one at a time as the window grows, so heap pressure during warm-up is N small allocations instead of 1 doubling allocation. For platforms with a fragmenting allocator this could be a regression — flag during review.
  • Chunk-size tuning is a workload-dependent knob. The default fork on FL_PLATFORM_HAS_LARGE_MEMORY is a first guess; per-type override is the escape hatch.
  • The iterator becoming a 2-field struct (chunk-map idx + intra-chunk idx) inflates its size from one fl::size to two. Audit fl::deque<T>::iterator callers — most pass by value, but anything copying iterators heavily (e.g. find, find_if over the entire deque) will see a small per-call cost.

Refs

Activity

  1. added a commit that references this issue on Jun 19, 2026
    a8b5cac
  2. moved this from Triage to Done in FastLED Trackeron Jun 19, 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

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions