Imported from GitHub aien-dev/interplane-mv#10 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base 2f7b0cc44b74aad64d86a19780216e099c07909f · Head bae078afba16488bff80405d1195835a488a7f69
greptile-apps[bot] commented on docs/external/nightdriver/565/harness/run.sh line 8 on 2026-10-04 22:54 UTC
The harness needs a separate fork checkout, so its default run cannot compile from a fresh checkout of this repository. Although the report names the intended commit, the script accepts any supplied checkout without verifying its revision. This makes the recorded results difficult to reproduce and can cause a run to test different code. This is a non-blocking reproducibility concern.
This is a comment left during a code review.
Path: docs/external/nightdriver/565/harness/run.sh
Line: 6-8
Comment:
**Harness checkout is unchecked**
The harness needs a separate fork checkout, so its default run cannot compile from a fresh checkout of this repository. Although the report names the intended commit, the script accepts any supplied checkout without verifying its revision. This makes the recorded results difficult to reproduce and can cause a run to test different code. This is a non-blocking reproducibility concern.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
When the test executable fails, set -e exits before the final rm runs. Its temporary output remains, so repeated failures accumulate files. This is a non-blocking cleanup concern.
This is a comment left during a code review.
Path: docs/external/nightdriver/565/harness/run.sh
Line: 7-9
Comment:
**Failed runs leave temporary files**
When the test executable fails, `set -e` exits before the final `rm` runs. Its temporary output remains, so repeated failures accumulate files. This is a non-blocking cleanup concern.
```suggestion
OUT=$(mktemp)
trap 'rm -f "$OUT"' 0
g++ -std=gnu++17 -O1 -Wall -I"$H/stubs" -I"$FIX/include" "$H/host/test_budget.cpp" -o "$OUT"
"$OUT"
```
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
### Issue 1
docs/external/nightdriver/565/harness/run.sh:6-8
The harness needs a separate fork checkout, so its default run cannot compile from a fresh checkout of this repository. Although the report names the intended commit, the script accepts any supplied checkout without verifying its revision. This makes the recorded results difficult to reproduce and can cause a run to test different code. This is a non-blocking reproducibility concern.
### Issue 2
docs/external/nightdriver/565/harness/run.sh:7-9
When the test executable fails, `set -e` exits before the final `rm` runs. Its temporary output remains, so repeated failures accumulate files. This is a non-blocking cleanup concern.
```suggestion
OUT=$(mktemp)
trap 'rm -f "$OUT"' 0
g++ -std=gnu++17 -O1 -Wall -I"$H/stubs" -I"$FIX/include" "$H/host/test_budget.cpp" -o "$OUT"
"$OUT"
```
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
</details>
<details open><summary>Summary</summary>
The PR documents the NightDriverStrip #565 investigation and adds a host-model harness. A fresh checkout cannot compile the harness without the separate fork, and the script does not verify that a supplied checkout matches the documented commit. A failed test run also leaves a temporary file behind. These concerns do not block merging.
</details>
diff --git a/docs/external/nightdriver/565/REPORT.md b/docs/external/nightdriver/565/REPORT.md
new file mode 100644
index 0000000..8d92954
--- /dev/null
+++ b/docs/external/nightdriver/565/REPORT.md
@@ -0,0 +1,79 @@
+# NightDriverStrip issue 565: "Memory allocations fail in low memory situations, but too early"
+
+Lane D2. Upstream project: PlummersSoftwareLLC/NightDriverStrip. Nothing here has been sent upstream
+(`upstreamed` is not claimed anywhere below). Pinned main: `4d79c290` (same SHA as lane D1).
+
+**Outcome: root cause NOT proven; one verified capability mismatch in a size decision (hardening, not a claimed fix for #565); real reproduction BLOCKED on a physical M5StickC Plus.**
+
+Evidence tags: observed, reproduced, inferred, hypothesized, fixed, tested, upstreamed, accepted.
+"Model" means a host simulation of documented ESP-IDF semantics, never the real allocator.
+
+## Observed
+
+The issue (Dave Plummer, 2023-12-10), complete text of the claim:
+- [observed] "Even allocating 4K when 50K is free, and 34K is the largest block, can fail." Mostly on builds "like M5DEMO where there is no PSRAM". No call site, no caps, no log, no firmware version. Two comments: robertlipe asks for a reproducer and suspects `String` fragmentation (guess, no profile); rbergen points at discussion #562.
+- [observed] Discussion #562 is the only thread with numbers (M5StickC Plus, FANSET; discussioncomment-7934601 and the replies):
+ - M5StickC Plus has no PSRAM (robertlipe, 2023-12-24). The `m5demo` env of that era extends `dev_m5stick-c`, platform `platformio/espressif32@^6.3.0` (`platformio.ini` at `960daf50`, lines 239 and 322-326). So the chip is the classic ESP32.
+ - Boot log: "Reserving 49 LED buffers for a total of 29792 bytes". Heap at "Launching Drawing Thread": Mem 136412, LargestBlk 90100. At "Launching Remote Thread": Mem 123576, LargestBlk 86004 (a drop of exactly 4096). After WiFi starts: Mem 70692, LargestBlk 36852; then Mem 44532, LargestBlk 31732.
+ - rbergen: "With all other servers disabled there's 47K of RAM left, with the reported biggest block being 31K. That's just not enough to start the webserver successfully."; later: lowering MAX_BUFFERS to 5 fixed the reboots on WiFi connect; "bad_alloc" in the log is "a dead give-away"; a dependency update "chewed up ~30K"; free RAM "hovers around 55K" around the crashes.
+ - Two non-allocator bugs in that same thread were fixed separately (FireFanEffect negative index; JSON halving of LED count on every reboot). Not part of #565.
+- [observed] No failing allocation size or caps is stated anywhere in the issue or in #562. The "4K with 50K free, 34K largest" figures cannot be matched to a call site.
+
+Allocation and sizing path on pinned main `4d79c290`:
+- [observed] `psram_allocator<T>::allocate` (`include/interfaces.h:94-99`): `heap_caps_malloc(SPIRAM|8BIT)`, then on failure `heap_caps_malloc(INTERNAL|8BIT)`, then `throw std::bad_alloc`. It has a fallback and the capability sets are right for a byte-addressed buffer. It makes no total-free or largest-block decision itself.
+- [observed] The only project-side admission decision is `SystemContainer::SetupBufferManagers` (`src/systemcontainer.cpp:213-241`): free memory = `ESP.getFreePsram()` if `USE_PSRAM`, else `ESP.getFreeHeap()`; `memtouse = free - RESERVE_MEMORY` (saturating); `cBuffers = memtouse / bytes-per-set`; throw if `< MIN_BUFFERS` (3); clamp to `MAX_BUFFERS` (24 without PSRAM, `include/globals.h:425-430`). `RESERVE_MEMORY` is 150000 without PSRAM (`globals.h:547-552`).
+- [observed] The issue-era code was `ESP.getFreeHeap() - RESERVE_MEMORY` with unsigned arithmetic (`960daf50:include/systemcontainer.h:163`). The wrap-around was fixed in `b13a22ec` (2026-07-12, "Saturate at zero" comment, `systemcontainer.cpp:219-224`). [inferred] Before that fix a board with less free memory than the reserve got `MAX_BUFFERS` buffers regardless; whether any shipped config hit that is not known.
+- [observed] `-DUSE_PSRAM=0` appears nowhere, so the `#ifdef USE_PSRAM` at `globals.h:548` versus `#if USE_PSRAM` elsewhere does not bite today (grep over include, src, platformio.ini). Dropped as a lead.
+- [observed] Main already prints `LargestBlk` and `PSRAM Free` (`ESP.getMaxAllocHeap()`, e.g. `src/taskmgr.cpp:156`, `src/main.cpp:861`). It does not register an allocation-failure hook and prints nothing per capability.
+- [observed] Pinned toolchain: platform `55.03.37` -> arduino-esp32 3.3.7 and ESP-IDF v5.5.2 (`platform.json` lines 32-61 of the release zip). The 2023 report ran on an older stack (Arduino 2.x, IDF 4.4, same `Esp.cpp` query).
+
+ESP-IDF semantics (all quoted from source; ESP-IDF v5.5.2 unless stated):
+- [observed] `EspClass::getFreeHeap()` is `heap_caps_get_free_size(MALLOC_CAP_INTERNAL)` and `getMaxAllocHeap()` is `heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)` (arduino-esp32 3.3.7 `cores/esp32/Esp.cpp:163-173`; same in 2.0.14).
+- [observed] Both are computed by summing, respectively taking the max over every heap whose capabilities include the request (`components/heap/heap_caps.c:277-286` and `:367-389`).
+- [observed] On the original ESP32 the IRAM region has capabilities `INTERNAL|EXEC|32BIT` and no `8BIT` (`components/heap/port/esp32/memory_layout.c:16-18,54`; docs `mem_alloc.rst:27,36,69-72`: "At startup, the IRAM heap contains all instruction memory that is not used by the app executable code"; `heap_caps_get_free_size(MALLOC_CAP_8BIT)` is the free size of all DRAM heaps). Same row in IDF 4.4.5 (`memory_layout.c:25-27`).
+- [observed] A heap can serve a request only if it has all requested caps (`components/heap/heap_caps_base.c:147`). So an `INTERNAL|8BIT` allocation can never come from IRAM, while `getFreeHeap()` and `getMaxAllocHeap()` count it.
+- [observed] Plain `malloc` is `heap_caps_malloc_default`, caps `DEFAULT|INTERNAL` (`heap_caps.c:107-111`); IRAM has no `DEFAULT` cap, so it is not used. With PSRAM enabled and `heap_caps_malloc_extmem_enable(limit)` (project sets 96, `src/main.cpp:387`), requests over `limit` go to SPIRAM first and then fall back to default (`heap_caps.c:113-131`).
+- [observed] `heap_caps_register_failed_alloc_callback` exists and reports size, caps and function name of every failed allocation (`heap_caps.c:49-53,62-70`; `esp_heap_caps.h:52-66`).
+- [not verified] TLSF size-class rounding and per-block overhead (multi_heap). A block of at least the requested size is therefore necessary, not proven sufficient. Not read from `multi_heap.c`; the model below does not claim it.
+
+## Reproduction
+
+- [tested, model only; not a reproduction] Host logic test of the new helper `FreeInternalBytes8Bit()` (real project header from the fork branch) against a model of the documented capability rules. Run: `docs/external/nightdriver/565/harness/run.sh` (needs a checkout of the fork branch, default `~/workspace/external/nd565-fix`); output in `harness/results.txt`:
+ - Case 1, illustrative layout (160000 B of 8-bit DRAM, 90000 B of IRAM, 9000 B per buffer set): the old query (`getFreeHeap` semantics, 250000) admits 11 buffer sets and leaves 61000 B of 8-bit memory, below the 150000 B reserve; the new query (160000) refuses cleanly.
+ - Case 2, 20000 deterministic layouts: invariant "after admitting, 8-bit free >= RESERVE" is violated 14018 times by the old query and 0 times by the new one. (Violations scale with IRAM free; the sizes are synthetic. This says the quantity is wrong, not how often it matters on a real board.)
+ - Case 3, the issue's literal numbers as a model shape: INTERNAL free 50000, largest 34000, but the largest block is IRAM and DRAM has only fragments up to 3000. A 4096 B `INTERNAL|8BIT` allocation fails, a 4096 B `32BIT` one succeeds. [hypothesized] This is one way the issue's numbers could be true. It is not shown to be what happened.
+- [observed] In the #562 log the INTERNAL largest block fell by exactly 4096 (90100 at the Audio launch line, 86004 at the Remote launch line). Between those two lines the Audio Sampler task is created with `AUDIO_STACK_SIZE` 4096 (`taskmgr.h:55,315` at `960daf50`). [inferred] The largest INTERNAL block was therefore the one a task stack was carved from; task stacks need byte access, so it was DRAM, not IRAM (the port code that allocates stacks was not read). That weakens the IRAM hypothesis for the #562 board. [inferred] So the M5StickC Plus numbers in #562 are not explained by IRAM counting; the later "47K free, 31K largest, web server fails" is real shortage for a larger allocation, not a 4K one.
+- [BLOCKED] True fragmentation behaviour cannot be reproduced on this host: it depends on the TLSF multi_heap, the real task and WiFi allocation order, and the chip's actual region sizes. No claim of "reproduced" is made for the original failure.
+
+## Root Cause
+
+Not proven. What is established (observed, from source): the project sizes its LED buffer budget from a quantity (`INTERNAL`, aggregate) that is not the quantity its allocator consumes (`INTERNAL|8BIT`, per block). What is not established: that this mismatch caused any failure in #562 or in Dave's report, and which allocation failed. The #562 thread points to a different, ordinary cause for the rebooting board: a fixed 150 kB reserve consumed at runtime by WiFi, task stacks and the web server on a board with ~180 kB free at boot (observed numbers above), plus a framework update (rbergen: ~30K). That is a capacity problem, not an allocator-decision defect.
+
+## Fix
+
+Branch `fix/565-buffer-budget-8bit` on `aien-dev/NightDriverStrip` (fork), commit `8e3d3515c36bebea464467b7834c8ca95afe8925`, based on `4d79c290`. Two files: new `include/heapbudget.h` (`FreeInternalBytes8Bit()`, one `heap_caps_get_free_size(INTERNAL|8BIT)` call) and a 3-line change in `SystemContainer::SetupBufferManagers` for the non-PSRAM branch. PSRAM builds unchanged.
+- [tested, model-level; not fixed on a device] The invariant above holds for the new query in the model.
+- [not tested] Not compiled for an ESP32 target (no PlatformIO toolchain here); not run on a device. Behaviour change: on classic ESP32 without PSRAM the buffer count can drop by about (IRAM free / bytes per set), so a few boards may need MAX_BUFFERS or MIN_BUFFERS review. That cost is the point: the old count was too high by that amount.
+- It does not claim to fix #565. See `upstream-pr-draft.md` for the wording.
+
+## Regression
+
+`harness/run.sh` (above), 3 cases. Red/green: the old query violates the invariant 14018 times and the new helper 0 times in the same run; negative control [tested]: the same test against a copy of the helper that queries `INTERNAL` only prints `RESULT FAIL (3)` (both recorded in `harness/results.txt`). Limits: the arithmetic from `systemcontainer.cpp` is copied into the test, not compiled from source; the heap is a model.
+
+## Instrumentation proposal (device run; nothing applied)
+
+The decisive missing datum is the failing allocation's size and caps. IDF already provides it (`heap_caps_register_failed_alloc_callback`). Proposed minimal diagnostic, in project style, to be tried on a device first (untested):
+1. At boot, `heap_caps_register_failed_alloc_callback(cb)`. The callback only stores `size`, `caps`, `function_name`, a failure counter and a snapshot of `heap_caps_get_free_size` and `heap_caps_get_largest_free_block` for `INTERNAL`, `INTERNAL|8BIT`, `DMA`, `SPIRAM|8BIT` into a static struct. No printing, no allocation, no locks in the callback (it runs inside the allocator; `esp_heap_caps.h:68-77` warns about the neighbouring hook for the same reason).
+2. Print that struct from the existing periodic status line (`main.cpp:861` area) next to `LargestBlk`, plus `heap_caps_get_minimum_free_size(INTERNAL|8BIT)` and `uxTaskGetStackHighWaterMark` per task where `taskmgr.cpp:156` already logs thread launches.
+3. Replace `ESP.getMaxAllocHeap()` in those lines (or add beside it) with the `INTERNAL|8BIT` largest block so the logged number is the one an 8-bit allocation can use.
+4. `CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS` (`heap_caps.c:29,55`) is an sdkconfig option. Not checked whether pioarduino 55.03.37 can set it for the Arduino libraries; the callback does not need it.
+
+## Scope
+
+- Only `SetupBufferManagers`' non-PSRAM free-memory source changes. No protocol, architecture, allocator-interface or configuration change; no change to PSRAM routing or `RESERVE_MEMORY`.
+- Not examined: `String` fragmentation (robertlipe's hypothesis), WiFi stack growth, effect-internal allocations. They remain candidates for the original failure.
+- Device run needed to close the issue: an M5StickC Plus (classic ESP32, no PSRAM), env `m5demo` or `fanset`-equivalent from current main, with the instrumentation above, WiFi and web server on, cycling effects until `bad_alloc`; capture the failing size and caps and the per-cap largest blocks at that instant. A second run on a PSRAM board (to see `extmem` fallback behaviour) is optional.
+
+## INTERPLANE Lesson
+
+Admission decisions must use the capability-qualified resource the consumer will actually draw from, not an aggregate that merely sounds like it.
diff --git a/docs/external/nightdriver/565/harness/host/test_budget.cpp b/docs/external/nightdriver/565/harness/host/test_budget.cpp
new file mode 100644
index 0000000..e643f51
--- /dev/null
+++ b/docs/external/nightdriver/565/harness/host/test_budget.cpp
@@ -0,0 +1,71 @@
+// Logic-level test (MODEL of documented ESP-IDF semantics, not a device run, not the real allocator).
+// Real project code under test: include/heapbudget.h (FreeInternalBytes8Bit) from the fork branch.
+// Copied from src/systemcontainer.cpp at the same branch (arithmetic only, not compiled from source):
+// memtouse = free > RESERVE ? free - RESERVE : 0; cBuffers = memtouse / memtoalloc; throw if < MIN; clamp to MAX.
+#include <cstdio>
+#include <cstdlib>
+#include "heapbudget.h"
+using namespace heapmodel;
+
+static const uint32_t RESERVE = 150000, MIN_BUF = 3, MAX_BUF = 24;
+static int fails = 0;
+#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL %s:%d ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
+
+static uint32_t buffers_for(uint32_t freeMem, uint32_t setBytes, bool* admitted) {
+ uint32_t memtouse = freeMem > RESERVE ? freeMem - RESERVE : 0;
+ uint32_t c = memtouse / setBytes;
+ *admitted = c >= MIN_BUF;
+ return c > MAX_BUF ? MAX_BUF : c;
+}
+static uint32_t old_free() { return (uint32_t)heap_caps_get_free_size(MALLOC_CAP_INTERNAL); } // Esp.cpp:164 getFreeHeap
+
+static void layout(size_t dram, size_t iram) { reset(); heaps().push_back(DRAM({dram})); heaps().push_back(IRAM({iram})); }
+
+int main() {
+ // Case 1: documented classic-ESP32 region mix (mem_alloc.rst:91-93 shows 14+111 KiB D/IRAM and 90 KiB IRAM). Numbers illustrative.
+ layout(160000, 90000);
+ CHECK(old_free() == 250000, "old=%u", old_free());
+ CHECK(FreeInternalBytes8Bit() == 160000, "new=%u", FreeInternalBytes8Bit());
+ const uint32_t setBytes = 9000;
+ bool okOld, okNew;
+ uint32_t nOld = buffers_for(old_free(), setBytes, &okOld);
+ uint32_t nNew = buffers_for(FreeInternalBytes8Bit(), setBytes, &okNew);
+ printf("case1 old: admit=%d buffers=%u | new: admit=%d buffers=%u\n", okOld, nOld, okNew, nNew);
+ uint32_t left8 = (uint32_t)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) - (okOld ? nOld * setBytes : 0);
+ CHECK(okOld && left8 < RESERVE, "old query should over-admit (8-bit left %u vs reserve %u)", left8, RESERVE);
+ CHECK(!okNew, "new query should refuse cleanly");
+
+ // Case 2: invariant sweep. If admitted, 8-bit free after taking the buffers must be >= RESERVE.
+ uint32_t seed = 12345, oldViol = 0, newViol = 0, n = 0;
+ for (int i = 0; i < 20000; i++) {
+ seed = seed * 1664525u + 1013904223u;
+ size_t dram = 100000 + (seed >> 8) % 200000;
+ seed = seed * 1664525u + 1013904223u;
+ size_t iram = (seed >> 8) % 100000;
+ seed = seed * 1664525u + 1013904223u;
+ uint32_t sb = 600 + (seed >> 8) % 12000;
+ layout(dram, iram); n++;
+ bool a, b;
+ uint32_t co = buffers_for(old_free(), sb, &a), cn = buffers_for(FreeInternalBytes8Bit(), sb, &b);
+ if (a && dram < RESERVE + (size_t)co * sb) oldViol++;
+ if (b && dram < RESERVE + (size_t)cn * sb) newViol++;
+ }
+ printf("case2 sweep n=%u old_invariant_violations=%u new_invariant_violations=%u\n", n, oldViol, newViol);
+ CHECK(oldViol > 0, "expected old query to violate the invariant somewhere");
+ CHECK(newViol == 0, "new query violated the invariant %u times", newViol);
+
+ // Case 3: the issue's literal numbers as a MODEL shape (hypothesis only: the issue gives no caps or call site).
+ // 50K INTERNAL free, 34K INTERNAL largest, but the 34K block is in IRAM and DRAM has only small fragments.
+ reset(); heaps().push_back(DRAM({3000, 3000, 3000, 3000, 2000, 2000})); heaps().push_back(IRAM({34000}));
+ CHECK(old_free() == 50000, "free=%u", old_free());
+ CHECK(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL) == 34000, "largest internal");
+ CHECK(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) == 3000, "largest 8bit");
+ printf("case3 internal free/largest = %zu/%zu, 8bit free/largest = %zu/%zu\n",
+ heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL),
+ heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
+
+ CHECK(heap_caps_malloc(4096, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) == nullptr, "4K 8-bit alloc must fail in this state");
+ CHECK(heap_caps_malloc(4096, MALLOC_CAP_INTERNAL | MALLOC_CAP_32BIT) != nullptr, "4K 32-bit alloc succeeds from IRAM");
+ printf(fails ? "RESULT FAIL (%d)\n" : "RESULT PASS\n", fails);
+ return fails ? 1 : 0;
+}
diff --git a/docs/external/nightdriver/565/harness/results.txt b/docs/external/nightdriver/565/harness/results.txt
new file mode 100644
index 0000000..675059a
--- /dev/null
+++ b/docs/external/nightdriver/565/harness/results.txt
@@ -0,0 +1,15 @@
+== green: fork branch helper (INTERNAL|8BIT) ==
+case1 old: admit=1 buffers=11 | new: admit=0 buffers=1
+case2 sweep n=20000 old_invariant_violations=14018 new_invariant_violations=0
+case3 internal free/largest = 50000/34000, 8bit free/largest = 16000/3000
+RESULT PASS
+
+== negative control: helper with INTERNAL-only query (expected FAIL) ==
+FAIL /home/drakestapleton/workspace/interplane-nd565/docs/external/nightdriver/565/harness/host/test_budget.cpp:28 new=250000
+case1 old: admit=1 buffers=11 | new: admit=1 buffers=11
+FAIL /home/drakestapleton/workspace/interplane-nd565/docs/external/nightdriver/565/harness/host/test_budget.cpp:36 new query should refuse cleanly
+case2 sweep n=20000 old_invariant_violations=14018 new_invariant_violations=14018
+FAIL /home/drakestapleton/workspace/interplane-nd565/docs/external/nightdriver/565/harness/host/test_budget.cpp:55 new query violated the invariant 14018 times
+case3 internal free/largest = 50000/34000, 8bit free/largest = 16000/3000
+RESULT FAIL (3)
+exit=1
diff --git a/docs/external/nightdriver/565/harness/run.sh b/docs/external/nightdriver/565/harness/run.sh
new file mode 100755
index 0000000..f330ddc
--- /dev/null
+++ b/docs/external/nightdriver/565/harness/run.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+# Usage: run.sh <fork-checkout-with-include/heapbudget.h> (default: ~/workspace/external/nd565-fix)
+# Logic-level test against a MODEL of ESP-IDF heap semantics. Not a device run.
+set -e
+H=$(cd "$(dirname "$0")" && pwd)
+FIX=${1:-$HOME/workspace/external/nd565-fix}
+OUT=$(mktemp)
+g++ -std=gnu++17 -O1 -Wall -I"$H/stubs" -I"$FIX/include" "$H/host/test_budget.cpp" -o "$OUT"
+"$OUT"; rc=$?; rm -f "$OUT"; exit $rc
diff --git a/docs/external/nightdriver/565/harness/stubs/esp_heap_caps.h b/docs/external/nightdriver/565/harness/stubs/esp_heap_caps.h
new file mode 100644
index 0000000..e86969e
--- /dev/null
+++ b/docs/external/nightdriver/565/harness/stubs/esp_heap_caps.h
@@ -0,0 +1,54 @@
+// Host MODEL of ESP-IDF heap capability semantics. Written for this harness, contains no project code.
+// Sources (ESP-IDF v5.5.2, the version pinned by NightDriverStrip main via pioarduino 55.03.37):
+// caps bit values: components/heap/include/esp_heap_caps.h:29-41
+// region capabilities: components/heap/port/esp32/memory_layout.c:49-54 (DRAM, D/IRAM, IRAM rows)
+// free size / largest: components/heap/heap_caps.c:277-286 (sum over matching heaps), :367-389 (max over matching heaps)
+// eligibility rule: components/heap/heap_caps_base.c heap_caps_aligned_alloc_base: (get_all_caps(heap) & caps) == caps
+// NOT modelled: TLSF size classes and per-block overhead (a real allocation can fail where this model succeeds,
+// never the other way round for the cases below), block-owner bytes, EXEC special cases, PSRAM.
+#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+#include <algorithm>
+
+#define MALLOC_CAP_EXEC (1u<<0)
+#define MALLOC_CAP_32BIT (1u<<1)
+#define MALLOC_CAP_8BIT (1u<<2)
+#define MALLOC_CAP_DMA (1u<<3)
+#define MALLOC_CAP_INTERNAL (1u<<11)
+#define MALLOC_CAP_DEFAULT (1u<<12)
+
+namespace heapmodel {
+struct Region { const char* name; uint32_t caps[3]; std::vector<size_t> freeBlocks; };
+inline std::vector<Region>& heaps() { static std::vector<Region> h; return h; }
+inline uint32_t all_caps(const Region& r) { return r.caps[0] | r.caps[1] | r.caps[2]; }
+// memory_layout.c:49-54
+inline Region DRAM (std::vector<size_t> b) { return {"DRAM", {MALLOC_CAP_8BIT|MALLOC_CAP_DEFAULT, MALLOC_CAP_INTERNAL|MALLOC_CAP_DMA|MALLOC_CAP_32BIT, 0}, b}; }
+inline Region DIRAM(std::vector<size_t> b) { return {"D/IRAM", {0, MALLOC_CAP_DMA|MALLOC_CAP_8BIT|MALLOC_CAP_INTERNAL|MALLOC_CAP_DEFAULT, MALLOC_CAP_32BIT|MALLOC_CAP_EXEC}, b}; }
+inline Region IRAM (std::vector<size_t> b) { return {"IRAM", {MALLOC_CAP_INTERNAL|MALLOC_CAP_EXEC|MALLOC_CAP_32BIT, 0, 0}, b}; }
+inline void reset() { heaps().clear(); }
+inline size_t sum(const Region& r) { size_t s = 0; for (auto b : r.freeBlocks) s += b; return s; }
+inline size_t largest(const Region& r) { size_t m = 0; for (auto b : r.freeBlocks) m = std::max(m, b); return m; }
+// heap_caps_base.c eligibility, first fit over priorities then regions; returns true if a block was found
+inline bool try_alloc(size_t size, uint32_t caps) {
+ for (int prio = 0; prio < 3; prio++)
+ for (auto& r : heaps())
+ if ((r.caps[prio] & caps) != 0 && (all_caps(r) & caps) == caps)
+ for (auto& b : r.freeBlocks)
+ if (b >= size) { b -= size; return true; }
+ return false;
+}
+}
+
+inline size_t heap_caps_get_free_size(uint32_t caps) {
+ size_t t = 0;
+ for (auto& r : heapmodel::heaps()) if ((heapmodel::all_caps(r) & caps) == caps) t += heapmodel::sum(r);
+ return t;
+}
+inline size_t heap_caps_get_largest_free_block(uint32_t caps) {
+ size_t m = 0;
+ for (auto& r : heapmodel::heaps()) if ((heapmodel::all_caps(r) & caps) == caps) m = std::max(m, heapmodel::largest(r));
+ return m;
+}
+inline void* heap_caps_malloc(size_t size, uint32_t caps) { return heapmodel::try_alloc(size, caps) ? (void*)1 : nullptr; }
diff --git a/docs/external/nightdriver/565/memory-cases.md b/docs/external/nightdriver/565/memory-cases.md
new file mode 100644
index 0000000..bd1781b
--- /dev/null
+++ b/docs/external/nightdriver/565/memory-cases.md
@@ -0,0 +1,16 @@
+# Memory cases for NightDriverStrip #565 (generic, reusable)
+
+Each row: situation, which quantity decides, and what the host model or source shows. Tags as in REPORT.md.
+Semantics cited from ESP-IDF v5.5.2 (`heap_caps.c`, `heap_caps_base.c:147`, `memory_layout.c:49-54`).
+
+| # | Situation | Deciding quantity | Status |
+|---|---|---|---|
+| 1 | 8-bit buffer on classic ESP32, IRAM heap holds most of the free memory | `INTERNAL|8BIT` largest block, not `INTERNAL` (IRAM has no 8BIT) | model case 3, hypothesized for the real issue |
+| 2 | Budget from `getFreeHeap` while allocating `INTERNAL|8BIT` | `INTERNAL|8BIT` free | model cases 1-2, fixed in the fork branch |
+| 3 | Plain `malloc` or `new` | `DEFAULT|INTERNAL` (IRAM excluded), or SPIRAM first above the extmem threshold then default (`heap_caps.c:107-131`) | observed in source |
+| 4 | DMA buffer | `DMA|INTERNAL|8BIT` (`interfaces.h:156`); DMA free/largest are logged by the web UI (`webserver.cpp:366-367`) | observed, no case run |
+| 5 | PSRAM buffer with internal fallback (`psram_allocator`) | `SPIRAM|8BIT` first, then `INTERNAL|8BIT`; a PSRAM-exhausted board silently spends internal memory | observed in source, no case run |
+| 6 | Executable memory | `EXEC` forces IRAM and cannot be combined with `8BIT` or `DMA` (`heap_caps_base.c` EXEC branch) | observed in source, not relevant to NightDriver |
+| 7 | Total free large, largest block small | one allocation needs a block, a set of N buffers needs N blocks; "block at least the size" is necessary, TLSF sufficiency not verified | not verified |
+| 8 | Reserve consumed at runtime (WiFi, stacks, web server) after a one-time budget | a one-time free-memory budget cannot see later consumers | observed in #562 numbers (180K free at boot, 47K later) |
+| 9 | Unsigned `free - reserve` wrap | saturate before dividing | observed, fixed upstream in `b13a22ec` |
diff --git a/docs/external/nightdriver/565/upstream-pr-draft.md b/docs/external/nightdriver/565/upstream-pr-draft.md
new file mode 100644
index 0000000..4c79a1b
--- /dev/null
+++ b/docs/external/nightdriver/565/upstream-pr-draft.md
@@ -0,0 +1,24 @@
+# Upstream PR draft (NOT SENT: Drake's button). Targets PlummersSoftwareLLC/NightDriverStrip main.
+
+Branch: aien-dev/NightDriverStrip `fix/565-buffer-budget-8bit` (8e3d3515), based on main `4d79c290`.
+CONTRIBUTING.md exists on main and has no AI-assistance disclosure requirement (grep for AI, LLM, assisted, generated: no hits). Disclosure is still recommended by courtesy: "Drafted with AI assistance (Claude); reviewed and tested by the submitter." Add only if Drake agrees.
+Nothing in this text may mention INTERPLANE or AIEN.
+
+## Title
+Size the LED buffer budget from 8-bit internal memory on boards without PSRAM
+
+## Body
+`SetupBufferManagers()` computes how many LED buffer sets to allocate from `ESP.getFreeHeap()` when there is no PSRAM. That is `heap_caps_get_free_size(MALLOC_CAP_INTERNAL)`, which on the original ESP32 also counts the IRAM heap. IRAM is 32-bit access only (no `MALLOC_CAP_8BIT`), and the buffers are allocated with `MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT` (`psram_allocator` fallback), so that memory can never serve them. The configured `RESERVE_MEMORY` can therefore end up smaller than intended.
+
+This adds `FreeInternalBytes8Bit()` (`heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)`) and uses it for the non-PSRAM budget. PSRAM builds are unchanged.
+
+What this is not: it does not claim to fix #565. That report has no failing call site or capability, and the numbers in #562 (largest block shrinking by exactly one 4 KiB stack allocation) suggest ordinary shortage there. This only removes one place where the budget was computed from a different kind of memory than the allocation uses.
+
+Behaviour change: on classic ESP32 without PSRAM the buffer count can drop by roughly (free IRAM / bytes per buffer set). Boards that now fall below `MIN_BUFFERS` will refuse at startup, as they would have had the memory really been short.
+
+Testing: not compiled for an ESP32 target and not run on hardware by the author. Logic checked on a host against a model of the documented ESP-IDF capability rules only. Needs a maintainer or tester with an M5StickC Plus (or any no-PSRAM ESP32) to confirm it builds and boots, and to compare the logged "Reserving N LED buffers" line before and after.
+
+References: ESP-IDF v5.5.2 `components/heap/heap_caps.c:277-286,367-389`, `components/heap/port/esp32/memory_layout.c:54`, `components/heap/heap_caps_base.c:147`; arduino-esp32 3.3.7 `cores/esp32/Esp.cpp:163-173`.
+
+## Suggested comment for #565 (separate, also unsent)
+A reproducer needs the failing allocation's size and caps. ESP-IDF can report them: `heap_caps_register_failed_alloc_callback` (heap_caps.c:62-70). Printing `heap_caps_get_largest_free_block` for `INTERNAL|8BIT` instead of `INTERNAL` would also show whether the "largest block" in the logs is actually usable for 8-bit allocations. Without those two numbers the "4K failed with 34K largest" case cannot be told apart from an IRAM-counted block, a DMA-capable requirement, or a measurement taken at a different moment than the failure.