Add configuration-preserving Waveshare observer partition migration

This commit is contained in:
mikecarper committed 2026-10-15 17:37:52 -07:00
1 parent eebba0cb9a
commit 9a451dc160
9 files changed
+712 -14

No files matched your search

@@ -0,0 +1,205 @@
"""Execute strict 4 MiB source/retention guards without hardware or PlatformIO."""
from pathlib import Path
import subprocess
import tempfile
import unittest
from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "examples/esp32_partition_migrator/main.cpp"
HARNESS = r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <helpers/ESP32PartitionMigrationPolicy.h>
namespace migration = mesh::esp32_partition_migration;
constexpr size_t kIdentityFileBytes=96;
char status_text[192]={};
struct Entry {std::string path;bool dir;size_t bytes;std::vector<std::string> children;};
struct File {
Entry* item=nullptr;size_t index=0;
explicit operator bool() const{return item!=nullptr;}
bool isDirectory()const{return item&&item->dir;}
const char* path()const{return item?item->path.c_str():nullptr;}
size_t size()const{return item?item->bytes:0;}
File openNextFile();
void close(){item=nullptr;}
};
struct Filesystem {
std::map<std::string,Entry> entries;
bool mounted=true;unsigned begins=0,ends=0;
bool begin(bool format){assert(!format);++begins;return mounted;}
void end(){++ends;}
bool exists(const char* path){return entries.count(path)!=0;}
File open(const char* path,const char* mode){
assert(!strcmp(mode,"r"));
auto it=entries.find(path);return {it==entries.end()?nullptr:&it->second,0};
}
void add(const char* path,size_t bytes,const char* parent="/") {
entries[path]={path,false,bytes,{}};entries[parent].children.push_back(path);
}
void base() {
*this=Filesystem();entries["/"]={"/",true,0,{}};
add("/identity/_main.id",96);
}
} SPIFFS;
File File::openNextFile(){
if(!item||index>=item->children.size())return {};
return SPIFFS.open(item->children[index++].c_str(),"r");
}
@CONFIG@
@METHODS@
int main(int argc,char**argv) {
assert(argc==2);int scenario=atoi(argv[1]);SPIFFS.base();
if(scenario==0) {
SPIFFS.add("/com_prefs",512);SPIFFS.add("/s_contacts",2048);
SPIFFS.add("/s_login_replay",256);SPIFFS.add("/radio_profiles",1024);
SPIFFS.add("/mqtt_prefs",2888);SPIFFS.add("/management",512);
assert(preflightStrictPreservation(migration::kTarget4MB));
assert(SPIFFS.begins==1&&SPIFFS.ends==1);
} else if(scenario==1) {
for(const char* path:{"/custom.ini","/mqtt_prefs.tmp","/identity/other.id","/logs.txt"}) {
SPIFFS.base();SPIFFS.add(path,10);
assert(!preflightStrictPreservation(migration::kTarget4MB));
assert(strstr(status_text,"unpreserved"));assert(SPIFFS.ends==1);
}
} else if(scenario==2) {
for(size_t bytes:{size_t(0),size_t(16385),size_t(UINT32_MAX)+1}) {
SPIFFS.base();SPIFFS.add("/radio_profiles",bytes);
assert(!preflightStrictPreservation(migration::kTarget4MB));
}
SPIFFS.base();SPIFFS.add("/s_contacts",12000);
SPIFFS.add("/radio_profiles",12000);SPIFFS.add("/mqtt_prefs",12000);
assert(!preflightStrictPreservation(migration::kTarget4MB));
assert(strstr(status_text,"budget"));
} else if(scenario==3) {
for(const auto& layout:{migration::kLegacyLayout,migration::kMinSpiffs4MBLayout,
migration::kExpanded4MBLayout}) {
assert(migration::isReviewed4MBSource(4U*1024U*1024U,layout));
assert(!migration::isReviewed4MBSource(8U*1024U*1024U,layout));
auto changed=layout;changed.spiffs_address+=4096;
assert(!migration::isReviewed4MBSource(4U*1024U*1024U,changed));
changed=layout;changed.nvs_address+=4096;
assert(!migration::isReviewed4MBSource(4U*1024U*1024U,changed));
changed=layout;changed.app1_address=changed.app0_address;
assert(!migration::isReviewed4MBSource(4U*1024U*1024U,changed));
}
auto target=migration::kTarget4MB;target.layout.spiffs_size=0x30000;
assert(!preflightStrictPreservation(target));assert(SPIFFS.begins==0);
assert(migration::kMinSpiffs4MBLayout.spiffs_address==0x3D0000);
assert(migration::kMinSpiffs4MBLayout.spiffs_size==0x20000);
// min_spiffs has a separate 64 KiB coredump after its 128 KiB filesystem;
// silently treating the coredump as filesystem capacity is not reviewed.
auto includes_coredump=migration::kMinSpiffs4MBLayout;
includes_coredump.spiffs_size=0x30000;
assert(!migration::isReviewed4MBSource(4U*1024U*1024U,includes_coredump));
assert(migration::kMinSpiffs4MBLayout.app0_address+migration::kMinSpiffs4MBLayout.app0_size
==migration::kMinSpiffs4MBLayout.app1_address);
// An old-B bridge can copy to A without erasing its currently running bytes.
assert(migration::kExpanded4MBLayout.app0_address+migration::kMinSpiffs4MBLayout.app1_size
<=migration::kMinSpiffs4MBLayout.app1_address);
} else if(scenario==4) {
SPIFFS.entries["/"].children.clear();
SPIFFS.entries["/"].children.push_back("/identity");
SPIFFS.entries["/identity"]={"/identity",true,0,{"/identity/_main.id"}};
assert(preflightStrictPreservation(migration::kTarget4MB));
SPIFFS.base();SPIFFS.entries["/"].children.push_back("/unknown");
SPIFFS.entries["/unknown"]={"/unknown",true,0,{}};
assert(!preflightStrictPreservation(migration::kTarget4MB));
SPIFFS.base();SPIFFS.entries["/"].children.clear();
assert(!preflightStrictPreservation(migration::kTarget4MB));
SPIFFS.base();SPIFFS.entries["/radio_profiles"]={"/radio_profiles",false,10,{}};
assert(!preflightStrictPreservation(migration::kTarget4MB));
assert(strstr(status_text,"incomplete"));
SPIFFS.base();SPIFFS.mounted=false;
assert(!preflightStrictPreservation(migration::kTarget4MB));
} else if(scenario==5) {
SPIFFS.entries["/identity/_main.id"].bytes=128;
assert(!preflightStrictPreservation(migration::kTarget4MB));
assert(strstr(status_text,"identity"));
SPIFFS.base();SPIFFS.entries["/"].children.push_back("/identity/_main.id");
assert(!preflightStrictPreservation(migration::kTarget4MB));
} else if(scenario==6) {
migration::PreservationBudget budget(65536);
for(unsigned i=0;i<33;++i)assert(budget.addFile(96));
assert(!budget.addFile(96));
migration::PreservationBudget large(65536);
assert(large.addFile(96)&&large.addFile(16384));
assert(large.requiredBytes()<=65536);
assert(!large.addFile(16384));
migration::PreservationBudget invalid(65536);
assert(!invalid.addFile(0)&&!invalid.addFile(UINT32_MAX));
} else return 2;
}
'''
class StrictPartitionPreservationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.directory = tempfile.TemporaryDirectory(prefix="strict-partition-preservation-")
source = SOURCE.read_text()
start = source.index("struct ConfigFile {")
end = source.index(";", source.index("constexpr size_t kConfigFileCount", start)) + 1
config = source[start:end]
methods = "\n".join(extract_braced(source, name) for name in (
"bool inventoryStrictDirectory(", "bool preflightStrictPreservation("))
path = Path(cls.directory.name) / "test.cpp"
cls.binary = Path(cls.directory.name) / "test"
path.write_text(HARNESS.replace("@CONFIG@", config).replace("@METHODS@", methods))
result = subprocess.run([
"g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie",
"-I", str(ROOT / "src"), str(path), "-o", str(cls.binary),
], text=True, capture_output=True)
if result.returncode:
cls.directory.cleanup()
raise AssertionError(result.stdout + result.stderr)
@classmethod
def tearDownClass(cls):
cls.directory.cleanup()
def test_saved_node_acl_radios_mqtt_fit(self):
subprocess.run([str(self.binary), "0"], check=True)
def test_unknown_files_are_not_silently_discarded(self):
subprocess.run([str(self.binary), "1"], check=True)
def test_empty_oversized_and_over_capacity_config_is_refused(self):
subprocess.run([str(self.binary), "2"], check=True)
def test_only_reviewed_source_maps_and_target_capacity_are_accepted(self):
subprocess.run([str(self.binary), "3"], check=True)
def test_nested_flat_missing_and_incomplete_inventory(self):
subprocess.run([str(self.binary), "4"], check=True)
def test_unpreserved_identity_metadata_and_duplicate_paths_are_refused(self):
subprocess.run([str(self.binary), "5"], check=True)
def test_budget_reserves_gc_and_an_atomic_largest_file_rewrite(self):
subprocess.run([str(self.binary), "6"], check=True)
def test_preflight_precedes_every_destructive_migration_step(self):
source = SOURCE.read_text()
body = extract_braced(source, "void runMigration()")
guard = body.index("preflightStrictPreservation(*plan)")
for operation in ("stageLegacyIdentity()", "stageLegacyConfig()", "copyAndVerify(*running",
"esp_ota_set_boot_partition(", "publishExpandedPartitionTable(*plan)"):
self.assertLess(guard, body.index(operation))
self.assertIn("MESHCORE_MIGRATION_STRICT_4MB", source)
# Existing boards keep their existing migration behavior unless a new,
# reviewed package explicitly opts into this narrower contract.
self.assertIn("#if defined(MESHCORE_MIGRATION_STRICT_4MB) && MESHCORE_MIGRATION_STRICT_4MB", body)
if __name__ == "__main__":
unittest.main()
+24 -2
View File
@@ -5,6 +5,7 @@ Resolve inheritance and interpolation without starting PlatformIO or a build.
The existing board recipes remain authoritative for hardware and OTA policy.
"""
import configparser
import csv
import fnmatch
from pathlib import Path
import re
@@ -22,6 +23,7 @@ BOARDS = {
"lilygo_teth_elite": ("LilyGo_TETH_Elite_sx1262",),
"meshnology_w12": ("meshnology_w12",),
"xiao_s3": ("Xiao_S3",),
"waveshare_esp32s3_lr1121": ("Waveshare_S3_LR1121",),
}
NAMES = tuple(
f"{board}_{role}_observer_mqtt"
@@ -72,8 +74,8 @@ class UpstreamObserverRecipeTests(unittest.TestCase):
def setUpClass(cls):
cls.recipes = Recipes()
def test_all_22_named_additions_exist_once(self):
self.assertEqual(len(NAMES), 22)
def test_all_24_named_additions_exist_once(self):
self.assertEqual(len(NAMES), 24)
for family, boards in BOARDS.items():
text = (ROOT / "variants" / family / "platformio.ini").read_text()
for board in boards:
@@ -137,6 +139,26 @@ class UpstreamObserverRecipeTests(unittest.TestCase):
section = f"env:{board}_{role}_observer_mqtt"
self.assertIn("MQTT_NEIGHBORS_WITHOUT_PSRAM=1", self.recipes.value(section, "build_flags"))
def test_waveshare_observers_have_two_larger_slots_and_64k_filesystem(self):
table = "variants/dual_ota_full_4MB.csv"
for role in ("repeater", "room_server"):
self.assertEqual(self.recipes.value(
f"env:Waveshare_S3_LR1121_{role}_observer_mqtt", "board_build.partitions"), table)
for role in ("repeater", "room_server", "companion_radio_usb", "companion_radio_ble", "kiss_modem"):
self.assertEqual(self.recipes.value(
f"env:Waveshare_S3_LR1121_{role}", "board_build.partitions"), "min_spiffs.csv")
rows = list(csv.reader(line for line in (ROOT / table).read_text().splitlines()
if line.strip() and not line.lstrip().startswith("#")))
parts = {row[0].strip(): (int(row[3], 0), int(row[4], 0)) for row in rows}
self.assertEqual(parts["app0"], (0x10000, 0x1F0000))
self.assertEqual(parts["app1"], (0x200000, 0x1F0000))
self.assertEqual(parts["spiffs"], (0x3F0000, 0x10000))
end = 0
for offset, size in sorted(parts.values()):
self.assertGreaterEqual(offset, end)
end = offset + size
self.assertEqual(end, 4 * 1024 * 1024)
def test_rc32_local_startup_platform_and_safety_remain_inherited(self):
for board in ("heltec_rc32", "heltec_rc32_without_display"):
for role in ("repeater", "room_server"):
+132
View File
@@ -0,0 +1,132 @@
"""No-hardware qualification of exact Waveshare observer migration recipes."""
import configparser
import json
from pathlib import Path
import re
import struct
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from build_esp32_partition_migration import build_steps
from package_esp32_partition_migration import BOARDS, package_board, readme
from motalib import hardware_id_for_env, target_id_for_env
KEYS = ("waveshare-s3-lr1121-observer-repeater",
"waveshare-s3-lr1121-observer-room-server")
class WaveshareMigrationRecipeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.config = configparser.ConfigParser(interpolation=None,
inline_comment_prefixes=(";",))
cls.config.read([ROOT / "platformio.ini", *sorted((ROOT / "variants").glob("*/platformio.ini"))],
encoding="utf-8")
def expanded(self, section, field):
config = self.config[section]
if field not in config and "extends" in config:
return self.expanded(config["extends"], field)
value = config.get(field, "")
return re.sub(r"\$\{([^}]+)\}",
lambda m: self.expanded(*m[1].rsplit(".", 1)), value)
def test_only_observer_roles_get_exact_self_hosted_routes(self):
waveshare = {key: spec for key, spec in BOARDS.items()
if spec["target"].startswith("Waveshare_")}
self.assertEqual(set(KEYS), set(waveshare))
for key, role in zip(KEYS, ("repeater", "room-server")):
with self.subTest(key=key):
spec = BOARDS[key]
self.assertEqual(role, spec["role"])
self.assertEqual(4 * 1024 * 1024, spec["flash_bytes"])
self.assertEqual(0x1F0000, spec["slot_bytes"])
self.assertEqual(0x200000, spec["slot1_address"])
self.assertEqual((0x3F0000, 0x10000),
(spec["spiffs_address"], spec["spiffs_bytes"]))
self.assertEqual("min_spiffs.csv", spec["source_partition_table"])
self.assertEqual(spec["wifi_bridge"], spec["expander_bridge"])
self.assertEqual(spec["lora_bridge"], spec["expander_bridge"])
self.assertEqual("esp32_s3_4mb_partition_migrator_usb", spec["usb_bridge"])
self.assertEqual(9, spec["usb_chip"])
self.assertEqual("Waveshare_S3_LR1121", hardware_id_for_env(spec["target"]))
self.assertEqual("variants/dual_ota_full_4MB.csv",
self.expanded("env:" + spec["target"], "board_build.partitions"))
for role in ("repeater", "room_server", "companion_radio_usb", "companion_radio_ble"):
self.assertEqual("min_spiffs.csv", self.expanded(
"env:Waveshare_S3_LR1121_" + role, "board_build.partitions"))
def test_expanders_reuse_real_lr1121_wiring_without_native_usb_or_legacy_handoff(self):
board = json.loads((ROOT / "boards/waveshare_s3_lr1121_migrator.json").read_text())
self.assertIn("-D ARDUINO_USB_CDC_ON_BOOT=0", board["build"]["extra_flags"])
self.assertEqual("dio", board["build"]["flash_mode"])
self.assertEqual("4MB", board["upload"]["flash_size"])
for key in KEYS:
spec = BOARDS[key]
section = "env:" + spec["expander_bridge"]
flags = self.expanded(section, "build_flags")
for name, value in (("P_LORA_NSS", 42), ("P_LORA_DIO_1", 38),
("P_LORA_RESET", 39), ("P_LORA_BUSY", 41),
("P_LORA_SCLK", 40), ("P_LORA_MISO", 46), ("P_LORA_MOSI", 45)):
self.assertIn(f"-D {name}={value}", flags)
for flag in ("RADIO_CLASS=CustomLR1121", "WRAPPER_CLASS=CustomLR1121Wrapper",
"LR11X0_DIO3_TCXO_VOLTAGE=1.8", "LR1121_FORCE_HP_PA",
"MESHCORE_MIGRATION_STRICT_4MB=1", "OTA_FETCH_PIPELINE=4"):
self.assertIn("-D " + flag, flags)
self.assertIn(f"-D MOTA_MIGRATION_TARGET_ID=0x{target_id_for_env(spec['target']):08x}", flags)
self.assertNotIn("MESHCORE_MIGRATION_RESUME_OTA", flags)
self.assertEqual("waveshare_s3_lr1121_migrator", self.expanded(section, "board"))
self.assertEqual("default.csv", self.expanded(section, "board_build.partitions"))
self.assertEqual("1310720", self.expanded(section, "board_upload.maximum_size"))
self.assertIn("../examples/partition_expander/*.cpp",
self.expanded(section, "build_src_filter"))
def test_builds_both_exact_full_apps_then_each_wireless_bridge_only_once(self):
steps = build_steps(list(KEYS), "v1.18.0-test", "usa-cascadia", "cascade", 2)
self.assertEqual([True, True, False, False, False], [full for _, full in steps])
self.assertEqual([BOARDS[key]["target"] for key in KEYS],
[command[3] for command, full in steps if full])
self.assertEqual({BOARDS[key]["expander_bridge"] for key in KEYS}
| {"esp32_s3_4mb_partition_migrator_usb"},
{command[3] for command, full in steps if not full})
for key in KEYS:
guide = readme(key, BOARDS[key], "v1.18.0-test", "01234567", full_mota_blocks=960)
self.assertIn("self-hosted, configuration-preserving", guide)
self.assertIn("either old OTA slot", guide)
self.assertIn("saved primary radio profile", guide)
self.assertIn("has not been physically qualified", guide)
self.assertIn("not power-loss atomic", guide)
self.assertNotIn("bridge must be installed in old slot B", guide)
def test_packager_rejects_a_wrong_final_filesystem_before_reading_bridges(self):
spec = BOARDS[KEYS[0]]
with tempfile.TemporaryDirectory(prefix="waveshare-migration-plan-") as temporary:
directory = Path(temporary)
stem = spec["target"] + "-full-usa-v1.18.0-test-01234567"
app = b"\xe9test-app"
(directory / (stem + ".bin")).write_bytes(app)
(directory / (stem + ".capabilities.json")).write_text(json.dumps({
"target": spec["target"], "build_profile": "full",
"platform": "ESP32_PLATFORM", "ota_update_verified": True,
}))
merged = bytearray(b"\xff" * 0x10000 + app)
for index, (name, ptype, subtype, address, size) in enumerate((
("nvs", 1, 2, 0x9000, 0x5000), ("otadata", 1, 0, 0xE000, 0x2000),
("app0", 0, 16, 0x10000, 0x1F0000), ("app1", 0, 17, 0x200000, 0x1F0000),
("spiffs", 1, 130, 0x3E0000, 0x20000),
)):
struct.pack_into("<HBBII16sI", merged, 0x8000 + 32 * index,
0x50AA, ptype, subtype, address, size, name.encode(), 0)
(directory / (stem + "-merged.bin")).write_bytes(merged)
with patch("package_esp32_partition_migration.validate_package"):
with self.assertRaisesRegex(ValueError, "SPIFFS differs"):
package_board(KEYS[0], spec, directory, directory / "output",
"v1.18.0-test", "01234567", directory / "utilities")
if __name__ == "__main__":
unittest.main()