From 214b02ed834875cc428d6ca34c0ff632b9dd9fc8 Mon Sep 17 00:00:00 2001 From: Fledgewing <8509633+Fledgewing@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:34:37 -0800 Subject: [PATCH 1/3] Keep refresh stacks flash-safe and break persistent refresh crashes Use an internal task stack for synchronous resolver NVS writes. Bound unfinished worker and early-boot retries with durable SD markers, preserving books, settings and catalog generations. Exercise the missing flash-stack constraint, large catalogs and cold-boot recovery in the simulator, and document recovery for installed firmware. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BLYjLJzEkmBRpMx6vsJ4xw --- docs/FEATURES.md | 2 +- docs/design/emulated-release-tests.md | 5 +- docs/design/full-refresh-crash-recovery.md | 101 ++++++++++++++++ shared/features.json | 4 +- xteink/orbify/BulkCatalog.cpp | 8 ++ xteink/orbify/RefreshRunner.cpp | 87 ++++++++++++-- xteink/orbify/RefreshRunner.h | 4 + xteink/orbify/ResumedWork.h | 40 +++++++ .../v2.0/0059-refresh-boot-breaker.patch | 20 ++++ xteink/tailnet/sim/sim_package.py | 53 ++++++++- xteink/test/e2e/run.py | 108 +++++++++++++++++- xteink/test/resumed_work_stubs/HalStorage.h | 26 +++++ xteink/test/resumed_work_test.cpp | 32 ++++++ xteink/test/run-host-tests.sh | 5 + 14 files changed, 482 insertions(+), 13 deletions(-) create mode 100644 docs/design/full-refresh-crash-recovery.md create mode 100644 xteink/orbify/ResumedWork.h create mode 100644 xteink/overlay/patches/v2.0/0059-refresh-boot-breaker.patch create mode 100644 xteink/test/resumed_work_stubs/HalStorage.h create mode 100644 xteink/test/resumed_work_test.cpp diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 198d5ba4..aa55560e 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -32,7 +32,7 @@ Counts include settings exposure as separate rows; they are not feature quality | Catalog lists, search and detail through the BookOrbit integration | ✅ (v0.11.3-rc.17) Cached catalog adapter. [android/koreader/orbit.koplugin/ko/cache.lua:24](../android/koreader/orbit.koplugin/ko/cache.lua#L24) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | 🟡 Online catalog; no BookSync offline cache; **hardware: cache uses PSRAM; X3 flash cuts**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Group every catalog list by series or author | ✅ (v0.11.3-rc.17) Series/author chips and grouped rows. [android/koreader/orbit.koplugin/ko/grouping.lua:40](../android/koreader/orbit.koplugin/ko/grouping.lua#L40) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ No grouping control; **hardware: current cached implementation excluded on X3; ROADMAP Next 6a**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Offline catalog pages and retained book details | ✅ (v0.11.3-rc.17) SQLite cache via companion; local window queries. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheStore.kt:15](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheStore.kt#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Ranked SD rows serve every refreshed list window without Wi-Fi, independent of source page size. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Ranked SD rows serve every refreshed list window without Wi-Fi, independent of source page size. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ❌ Online catalog; no refreshed SD windows; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | -| Explicit resumable Full refresh; monotone percentage | ✅ (v0.11.3-rc.17) Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure; explicit resumes show immediate startup feedback, missing acknowledgements warn once, and liveness queries back off; Full refresh joins an active incremental bulk run and displays its progress. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp; Android companion acknowledgement and startup-repair recovery do not apply to firmware**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | +| Explicit resumable Full refresh; monotone percentage | ✅ (v0.11.3-rc.17) Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure; explicit resumes show immediate startup feedback, missing acknowledgements warn once, and liveness queries back off; Full refresh joins an active incremental bulk run and displays its progress. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path; flash-safe internal worker stack; two unfinished attempts stop automatic resume, keeping books, settings and the published catalog; explicit Full refresh retries. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path; flash-safe internal worker stack; two unfinished attempts stop automatic resume, keeping books, settings and the published catalog; explicit Full refresh retries. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp; Android companion acknowledgement and startup-repair recovery do not apply to firmware**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Bulk manifest, derived lists and batched state reconciliation | ✅ (v0.11.3-rc.17) Bulk catalog plan. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt#L10) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Refresh continues away from the catalog; foreground remains usable | ✅ (v0.11.3-rc.17) Companion worker. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:17](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L17) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Separate refresh task. [xteink/orbify/RefreshRunner.cpp:38](../xteink/orbify/RefreshRunner.cpp#L38) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Separate refresh task. [xteink/orbify/RefreshRunner.cpp:38](../xteink/orbify/RefreshRunner.cpp#L38) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Saved pages retained indefinitely; silent incremental refresh | ✅ (v0.11.3-rc.17) Companion reconciliation. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60), [android/koreader/orbit.koplugin/ko/cache.lua:24](../android/koreader/orbit.koplugin/ko/cache.lua#L24) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | diff --git a/docs/design/emulated-release-tests.md b/docs/design/emulated-release-tests.md index 018ff644..5b38959c 100644 --- a/docs/design/emulated-release-tests.md +++ b/docs/design/emulated-release-tests.md @@ -474,7 +474,10 @@ series-card cover fetch and no lent connection, so it runs the three that apply | Scenario | Rows | Readers | |---|---|---| | `sync_through_proxy` | foundation | all | -| `mirror_urls` | X5 | X4s | +| `mirror_urls` | X5, flash-safe refresh task stack | X4s | +| `full_refresh_crash_breaker` | two unclean worker boots, durable quarantine, retained books/settings | X4s | +| `full_refresh_early_boot_breaker` | two setup crashes, disable suspect catalog before cache reads | X4s | +| `full_refresh_large_catalog` | 3,000-book full catalog with modeled flash-stack constraint | X4 Pro | | `copy_refresh_sleep_sync` | X6 | all | | `copy_refresh_tight_heap` | X6, shared-session heap floors | X4s | | `heap_floor_waits` | X3 | X4s | diff --git a/docs/design/full-refresh-crash-recovery.md b/docs/design/full-refresh-crash-recovery.md new file mode 100644 index 00000000..475cab1d --- /dev/null +++ b/docs/design/full-refresh-crash-recovery.md @@ -0,0 +1,101 @@ +# Full refresh crash recovery (0.11) + +Bug fix for X4 Pro and X4 Classic on main. Android owns its refresh in the +companion; X3 has no bulk catalog worker or PSRAM, so neither uses this task. + +## Cause and evidence + +The reported firmware is `xteink-v2.0.0.562+bookorbit.1-rc3`. There is no device +log. We can prove an unsafe call path and its boot-loop mechanism; we cannot +identify the exact instruction that panicked on that reader without its log. + +`RefreshRunner.cpp` allocated the `orb_catalog` task's 16 KB stack with +`MALLOC_CAP_SPIRAM`. Its `OrbifyBulk::refresh` network callback reaches the +catalog HTTP transport and Tailnet resolver. `TailnetResolver.cpp` calls +`tailnet_ensure_peer`; `Tailnet.cpp` calls `rememberServer` (changed server) or +`storePin` (unknown peer), which synchronously call NVS writes/commit on the +requesting task. These flash operations require an internal stack. ESP-IDF's +`components/spi_flash/cache_utils.c`, `esp_task_stack_is_sane_cache_disabled`, +asserts that the stack pointer is in internal DRAM before disabling the cache. +Ordinary visible-view Refresh uses the main task and avoids this worker-stack +mistake. Full refresh does not run the copy replacement queue; its only +`CopyRefresh` call reads the small library-version token. + +[Espressif's external-RAM constraints](https://docs.espressif.com/projects/esp-idf/en/release-v5.5/esp32s3/api-guides/external-ram.html) +explain why PSRAM is inaccessible with the flash cache disabled. The fix uses +an internal stack with the matching task creation/deletion APIs. JSON and numeric +catalog indexes retain their separate PSRAM allocator. Failure to allocate the +stack retains the request and backs off; it does not fall back to an unsafe stack. + +The ordinary SDL simulator omits Tailscale and flash-cache restrictions. A baseline +3,000-book run completed (533 requests, 187,801 bytes peak catalog PSRAM), so it +did not reproduce heap exhaustion. The added simulator model runs the synchronous +resolver flash-write constraint at the bulk transport callback. Restoring the old +external stack makes that run fail with exit 87; the internal stack passes. This +is a modeled hardware constraint, not an ESP32 CPU emulation or proof of the +maintainer's specific panic. The large-catalog emulated regression exercises the +actual worker, HTTP parsing and SD adapter with 3,000 books. + +## Persistent state and breaker + +`/.crosspoint/orbify/mirror.request` survives resets until Full refresh finishes. +The global worker sees it on every boot, without opening the catalog. Bulk staging +markers under `/.crosspoint/orbify-catalog/bulk/` resume the incomplete generation. +A deterministic panic was therefore retried indefinitely; a cold power cycle did +not clear it. Neither NVS nor a book's `.part` file is needed for this loop. + +The generic `ResumedWork` guard writes `refresh.inflight` durably before entering +the job and clears it only on ordinary return (success, offline, low heap or +cancellation). Its temporary marker is also checked after a reset during rename; +malformed markers fail closed. After two runs never return, the next boot blocks +a third. `mirror.request.crashed` blocks automatic incremental work across later +boots too. The request and bulk stage marker (including `.bak`/`.tmp`) are removed. +Published catalog generations, books, reading state and settings remain. Only an +explicit Full refresh or credential change clears the breaker; explicit refresh +starts a fresh staging generation. A storage failure that prevents recording an +attempt prevents starting the job. + +A second marker, `refresh-boot.inflight`, brackets setup while refresh state is +pending. After two incomplete setups the recovery hook runs immediately after SD +mount, before settings/catalog/activity restoration. It also quarantines the bulk +`active` pointer as `active.crashed` and removes its backup, preventing the suspect +catalog from being decoded on that boot. The generation bytes remain on SD. + +Host tests cover marker writes/renames, cold-boot instances, corrupt markers and +normal pauses. The emulated release scenario injects two abrupt process exits, +boots twice with the same fault still enabled, checks no network job runs and +verifies retained bytes, then retries through the real X4 Pro Home hold gesture. + +## Recover the already installed firmware + +1. Power the reader off/reset it as needed, then remove the SD card. In a card + reader, enable showing hidden files. From the **SD root**, delete only + `/.crosspoint/orbify/mirror.request`. +2. Reinsert the card and restart. This removes the automatic Full refresh request; + keep using ordinary Refresh and avoid Full refresh until installing a tested fix. + Do not delete `/.crosspoint`, `bookorbit.json`, `wifi.json`, books or reading + state, and do not erase NVS. The bulk stage files alone do not schedule work. +3. Once booting, OTA can install a subsequently published fixed firmware through + the normal update screen/channel. This change publishes no firmware. A test + artifact is not offered by OTA; install a matching X4 Pro test image through + SD firmware update or the maintainer-operated USB sideload workflow. + +There is no verified button-only way to cancel the persisted request in .562, and +no guaranteed interval in which Settings/OTA can be reached before the crash. +Booting without the SD card prevents this SD-backed request from running, but is +not a repair of the card and cannot supply the SD staging required for updates. +The existing **Down + Power** power-button-wake chord opens the SD `.bin` firmware +picker, but .562 still calls the global refresh scheduler in that mode. Do not +rely on that chord alone to outrun the worker: remove the request on the card first. +Afterward, a matching `.bin` already on the card can be selected there; USB is not +required when an SD card reader is available. + +Upstream recovery evidence at CrossInk commit +`87e2e1984481e8a3d996f12b34b50a383f9013b8`: +`src/main.cpp:1830-1837` selects Down on the S3 readers and requires a power-button +wake; `src/main.cpp:2128-2131` chooses `SdFirmwareUpdateActivity`; +`src/activities/settings/SdFirmwareUpdateActivity.cpp:26-30` opens the root picker +restricted to firmware. BookSync's patch 0053 adds the unconditional global +`OrbifyMirror::service()` call to `loop()`, explaining why recovery mode does not +cancel the request. These line references are for the unpatched pin; the overlay +moves the resulting source lines. diff --git a/shared/features.json b/shared/features.json index 55712d7e..c6a3873d 100644 --- a/shared/features.json +++ b/shared/features.json @@ -209,7 +209,7 @@ }, "x4_pro": { "status": "supported", - "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path", + "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path; flash-safe internal worker stack; two unfinished attempts stop automatic resume, keeping books, settings and the published catalog; explicit Full refresh retries", "reason": null, "evidence": [ { @@ -221,7 +221,7 @@ }, "x4": { "status": "supported", - "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path", + "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path; flash-safe internal worker stack; two unfinished attempts stop automatic resume, keeping books, settings and the published catalog; explicit Full refresh retries", "reason": null, "evidence": [ { diff --git a/xteink/orbify/BulkCatalog.cpp b/xteink/orbify/BulkCatalog.cpp index 8fcd31f9..7769521a 100644 --- a/xteink/orbify/BulkCatalog.cpp +++ b/xteink/orbify/BulkCatalog.cpp @@ -7,6 +7,9 @@ #include #include #include +#ifdef SIMULATOR +#include +#endif #include #include #include @@ -166,6 +169,11 @@ bool refresh(bool fresh,bool (*cancelled)(),const std::function& const auto start=millis(); const bool ok=catalog.refresh(owner(),[&](const std::string& path,JsonDocument& out){ if(!OrbifyHeap::roomForRequest("Full refresh"))return false; +#ifdef SIMULATOR + // The simulator omits Tailscale. Inject its synchronous resolver-side + // rememberServer/storePin NVS write, with ESP-IDF's cache-disabled stack rule. + orbify_sim_flash::write(); +#endif fetching.store(xTaskGetCurrentTaskHandle()); const bool result=BookOrbitCatalogClient::fetchBulk(path+(path.find("/manifest?")!=std::string::npos?"&deviceId="+orbify::bulk::encode(BookOrbitSyncClient::deviceId()):""),out); fetching.store(nullptr);return result; diff --git a/xteink/orbify/RefreshRunner.cpp b/xteink/orbify/RefreshRunner.cpp index 476fa9c8..67dd8afe 100644 --- a/xteink/orbify/RefreshRunner.cpp +++ b/xteink/orbify/RefreshRunner.cpp @@ -7,9 +7,10 @@ #include #include #include +#include +#include "ResumedWork.h" #ifndef SIMULATOR #include -#include #endif #include #include @@ -39,6 +40,29 @@ std::atomic retryAt{0}, requestCount{0}; std::atomic workerTask{nullptr}; std::mutex stateMutex; Snapshot state; +bool write(const char* path, const std::string& text); +ResumedWork attempt("/.crosspoint/orbify/refresh.inflight"); +ResumedWork bootAttempt("/.crosspoint/orbify/refresh-boot.inflight"); +constexpr const char* CRASHED = "/.crosspoint/orbify/mirror.request.crashed"; +void quarantine() { + // Disable every automatic entry point before touching the old checkpoint. + // Keep the published generation, books, credentials and reading state. + write(CRASHED, "Stopped at repeated refresh crash"); + Storage.remove(REQUEST); + Storage.remove(CHECKPOINT); + Storage.remove("/.crosspoint/orbify-catalog/bulk/stage"); + Storage.remove("/.crosspoint/orbify-catalog/bulk/stage.tmp"); + Storage.remove("/.crosspoint/orbify-catalog/bulk/stage.bak"); + terminalThisBoot.store(true); + incrementalRequested.store(false); + { + std::lock_guard lock(stateMutex); + state.active = true; state.finished = true; state.failures = 1; + state.result = "Stopped at repeated refresh crash"; + } + LOG_ERR("ORB", "Full refresh: crash breaker stopped automatic resume; saved catalog and books kept"); +} + #ifndef SIMULATOR TaskHandle_t taskHandle = nullptr; // owned/reaped only by the main task void reap() { @@ -66,6 +90,13 @@ std::string read(const char* path) { bool stop() { return stopping.load() || fresh.load() || OrbifyHeap::starved(); } void runTask() { const unsigned long began = millis(); + // Survives power loss and panics, unlike an in-memory running flag. An ordinary + // return (including offline, low heap or cancellation) is never a crash. + if (!attempt.begin()) { quarantine(); return; } + struct Completed { ~Completed() { attempt.complete(); } } completed; +#ifdef SIMULATOR + if (std::getenv("ORBIFY_SIM_CRASH_REFRESH")) { std::fflush(nullptr); std::_Exit(86); } +#endif workerTask.store(xTaskGetCurrentTaskHandle()); requestCount.store(0); const bool reset = fresh.exchange(false); @@ -122,7 +153,7 @@ void runTask() { } LOG_INF("ORB","Full refresh worker: ok=%d requests=%lu elapsedMs=%lu",ok,requestCount.load(),millis()-began); #ifdef SIMULATOR - if (std::getenv("ORBIFY_SIM_QUIT_BULK_DONE")) {std::fflush(nullptr);std::_Exit(ok ? 0 : 1); } + if (std::getenv("ORBIFY_SIM_QUIT_BULK_DONE")) {attempt.complete();std::fflush(nullptr);std::_Exit(ok ? 0 : 1); } #endif } workerTask.store(nullptr); @@ -141,11 +172,35 @@ void task(void*) { #endif } } // namespace +void bootBegin() { + // Before any saved catalog is decoded or the first activity is selected. + // A refresh can also leave a published cache that fails during setup, before + // service() has a chance to see the worker's in-flight marker. + if (!requested() && !Storage.exists(CRASHED) && !attempt.exhausted() && + !Storage.exists("/.crosspoint/orbify/refresh.inflight")) return; + if (bootAttempt.exhausted() || !bootAttempt.begin()) { + quarantine(); + // Disable the suspect cache by moving only its pointer, never the books or + // the catalog generation itself. Do not decode any of it during recovery. + constexpr const char* active = "/.crosspoint/orbify-catalog/bulk/active"; + if (Storage.exists(active)) { + Storage.remove("/.crosspoint/orbify-catalog/bulk/active.crashed"); + Storage.rename(active, "/.crosspoint/orbify-catalog/bulk/active.crashed"); + } + Storage.remove("/.crosspoint/orbify-catalog/bulk/active.bak"); + LOG_ERR("ORB", "Full refresh: early-boot breaker disabled saved catalog pointer"); + return; + } +#ifdef SIMULATOR + if (std::getenv("ORBIFY_SIM_CRASH_REFRESH_BOOT")) { std::fflush(nullptr); std::_Exit(88); } +#endif +} +void bootComplete() { bootAttempt.complete(); } Snapshot snapshot() { std::lock_guard lock(stateMutex); return state; } -bool busy() { return running.load() && !snapshot().finished; } +bool busy() { return running.load(); } void countCatalogRequest() { if (xTaskGetCurrentTaskHandle() == workerTask.load()) ++requestCount; } @@ -157,10 +212,12 @@ bool catalogTask() { return xTaskGetCurrentTaskHandle() == workerTask.load(); } bool cancelCatalogRequest() { return xTaskGetCurrentTaskHandle() == workerTask.load() && stop(); } void requestIncremental() { - if (!OrbifyBulk::active() || running.load() || requested() || WiFi.status()!=WL_CONNECTED) return; + if (Storage.exists(CRASHED) || !OrbifyBulk::active() || running.load() || requested() || WiFi.status()!=WL_CONNECTED) return; incrementalRequested.store(true);terminalThisBoot.store(false);retryAt.store(0);sleeping.store(false); } void freshRequest() { + attempt.complete(); + Storage.remove(CRASHED); fresh.store(true); terminalThisBoot.store(false); retryAt.store(0); @@ -174,6 +231,16 @@ void service() { reap(); if (taskHandle) return; #endif + static bool recoveryChecked = false; + if (!recoveryChecked && Storage.ready()) { + recoveryChecked = true; + if (Storage.exists(CRASHED) || attempt.exhausted()) { + if (!terminalThisBoot.load()) { + quarantine(); + } + return; + } + } const auto retry = retryAt.load(); if (sleeping.load() || terminalThisBoot.load() || running.load() || !Storage.ready() || (retry && static_cast(millis() - retry) < 0)) @@ -199,12 +266,16 @@ void service() { if (!OrbifyHeap::roomForRequest("Full refresh worker")) return; running.store(true); stopping.store(false); + // This task can reach flash writes (Wi-Fi PHY / Tailscale peer NVS). + // Its stack must remain accessible with the flash/PSRAM cache disabled. + // Library-sized JSON and indexes still use the separate PSRAM arena. + const auto created = xTaskCreateWithCaps(task, "orb_catalog", 16 * 1024, nullptr, 1, #ifdef SIMULATOR - const auto created = xTaskCreate(task, "orb_catalog", 16 * 1024, nullptr, 1, nullptr); + nullptr, #else - const auto created = xTaskCreateWithCaps(task, "orb_catalog", 16 * 1024, nullptr, 1, &taskHandle, - MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + &taskHandle, #endif + MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); if (created != pdPASS) { running.store(false); retryAt.store(millis() + 60000); @@ -215,6 +286,8 @@ void credentialsChanging() { stopForSleep(); // Quiesce the task before the settings callback mutates shared credentials. // An old account's queued inventory is never resumed on a different account. + attempt.complete(); + Storage.remove(CRASHED); Storage.remove(REQUEST); Storage.remove(CHECKPOINT); Storage.remove(RESULT); diff --git a/xteink/orbify/RefreshRunner.h b/xteink/orbify/RefreshRunner.h index 51febf3c..fc47665a 100644 --- a/xteink/orbify/RefreshRunner.h +++ b/xteink/orbify/RefreshRunner.h @@ -13,6 +13,8 @@ struct Snapshot { std::string result; }; #if CROSSINK_TAILNET_ORBIFY_MIRROR +void bootBegin(); +void bootComplete(); Snapshot snapshot(); void freshRequest(); void requestIncremental(); @@ -27,6 +29,8 @@ void catalogProgress(size_t done, size_t total, size_t books); bool cancelCatalogRequest(); bool catalogTask(); #else +inline void bootBegin() {} +inline void bootComplete() {} inline void service() {} inline void stopForSleep() {} inline bool busy() { return false; } diff --git a/xteink/orbify/ResumedWork.h b/xteink/orbify/ResumedWork.h new file mode 100644 index 00000000..9f4d76ba --- /dev/null +++ b/xteink/orbify/ResumedWork.h @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include +#include + +// A durable circuit breaker for resumable jobs. Two runs that never returned +// are enough: refuse a third, even after a cold power cycle. Expected pauses +// complete the attempt; no reset-reason or wall-clock assumptions are needed. +class ResumedWork { + public: + explicit ResumedWork(const char* file) : path(file), tmp(path + ".tmp") {} + bool exhausted() const { return count() >= 2; } + bool begin() { + const unsigned prior = count(); + if (prior >= 2) return false; + if (!Storage.mkdir(path.substr(0, path.find_last_of('/')).c_str())) return false; + HalFile file; + if (!Storage.openFileForWrite("ORB", tmp.c_str(), file)) return false; + const char next = '1' + prior; + const bool ok = file.write(reinterpret_cast(&next), 1) == 1 && file.sync(); + file.close(); + if (!ok) return false; + Storage.remove(path.c_str()); + return Storage.rename(tmp.c_str(), path.c_str()); + } + void complete() { Storage.remove(path.c_str()); Storage.remove(tmp.c_str()); } + private: + std::string path, tmp; + unsigned read(const std::string& p) const { + if (!Storage.exists(p.c_str())) return 0; + HalFile file; + if (!Storage.openFileForRead("ORB", p.c_str(), file)) return 2; + char value = 0; + // Truncated/corrupt state is unsafe to resume, not a fresh attempt. + if (file.fileSize() != 1 || file.read(reinterpret_cast(&value), 1) != 1) return 2; + return value == '1' ? 1 : 2; + } + unsigned count() const { return std::max(read(path), read(tmp)); } +}; diff --git a/xteink/overlay/patches/v2.0/0059-refresh-boot-breaker.patch b/xteink/overlay/patches/v2.0/0059-refresh-boot-breaker.patch new file mode 100644 index 00000000..83267776 --- /dev/null +++ b/xteink/overlay/patches/v2.0/0059-refresh-boot-breaker.patch @@ -0,0 +1,20 @@ +Subject: [PATCH] BookSync: break refresh crashes before saved catalog boot reads + +--- a/src/main.cpp ++++ b/src/main.cpp +@@ -2176,6 +2176,7 @@ + + HalSystem::checkPanic(); + orbifyBootStep(orbify::boottrail::Step::StorageReady); ++ OrbifyMirror::bootBegin(); + + if (!PluginBundle::recoverPending()) LOG_ERR("PLUG", "Plugin install recovery pending"); + // I2C light capabilities must be known before settings validate saved gestures. +@@ -2583,6 +2584,7 @@ + #if CROSSINK_TAILNET_FRONTLIGHT_REAPPLY + frontlightReapplyFrom = millis() + FRONTLIGHT_REAPPLY_AFTER_SETUP_MS; + #endif ++ OrbifyMirror::bootComplete(); + orbifyBootStep(orbify::boottrail::Step::SetupDone); + } + diff --git a/xteink/tailnet/sim/sim_package.py b/xteink/tailnet/sim/sim_package.py index 0b89b5c6..620b7928 100644 --- a/xteink/tailnet/sim/sim_package.py +++ b/xteink/tailnet/sim/sim_package.py @@ -64,6 +64,57 @@ def transform(text): _edit(Path(src_dir) / "HalGPIO.cpp", "orbify_sim_input::now", transform, changed, "input poll clock") return changed +# The host has no flash cache. Model the ESP-IDF cache_utils.c stack assertion +# explicitly, so simulator builds exercise the same caps API as the S3 build. +FLASH_MODEL = """\ +// SPDX-License-Identifier: MIT +#pragma once +#include +#include +#include +#include +namespace orbify_sim_flash { +inline thread_local uint32_t stackCaps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT; +inline void write() { + if (!std::getenv("ORBIFY_SIM_FLASH_ON_CONNECT")) return; + static thread_local bool done = false; + if (done) return; + done = true; + if (!(stackCaps & MALLOC_CAP_INTERNAL)) { + std::fprintf(stderr, "Flash cache disabled with external task stack\\n"); + std::fflush(nullptr); std::_Exit(87); + } + std::fprintf(stderr, "Flash write on internal task stack: %s\\n", pcTaskGetName(nullptr)); +} +} +""" +CAPS_TASK = """\ +// SPDX-License-Identifier: MIT +#pragma once +#include +#include +#include +struct OrbifySimCapsCall { void (*fn)(void*); void* arg; uint32_t caps; }; +inline BaseType_t xTaskCreateWithCaps(void (*fn)(void*), const char* name, + uint32_t bytes, void* arg, BaseType_t priority, TaskHandle_t* task, uint32_t caps) { + auto* call = new OrbifySimCapsCall{fn, arg, caps}; + return xTaskCreate([](void* p) { + std::unique_ptr call(static_cast(p)); + orbify_sim_flash::stackCaps = call->caps; + call->fn(call->arg); + }, name, bytes, call, priority, task); +} +""" + + +def patch_flash(src_dir): + src = Path(src_dir) + (src / "orbify_sim_flash.h").write_text(FLASH_MODEL) + (src / "freertos/idf_additions.h").write_text(CAPS_TASK) + changed = [] + return changed + + MIN_FREE = """\ inline size_t heap_caps_get_minimum_free_size(const uint32_t caps) { simulator_heap::initialize(); @@ -202,7 +253,7 @@ def _edit(path, marker, transform, changed, what): def patch(src_dir): """Patch the package sources in src_dir (.pio/libdeps//simulator/src). Returns what changed.""" heap = Path(src_dir) / "esp_heap_caps.h" - changed = patch_input(src_dir) + changed = patch_input(src_dir) + patch_flash(src_dir) clock = Path(src_dir) / WIFI_CLOCK_HEADER if not clock.exists() or clock.read_text() != WIFI_CLOCK: clock.write_text(WIFI_CLOCK) diff --git a/xteink/test/e2e/run.py b/xteink/test/e2e/run.py index 4d38ec3e..18288f1d 100644 --- a/xteink/test/e2e/run.py +++ b/xteink/test/e2e/run.py @@ -146,7 +146,9 @@ def mirror_urls(ctx: Context, tmp: Path) -> None: folder = card.crosspoint / "orbify" folder.mkdir(exist_ok=True) (folder / "mirror.request").write_text("1\n") - run = ctx.sim.run(card, "full-home", script="90000:QUIT", timeout_s=105) + run = ctx.sim.run(card, "full-home", script="90000:QUIT", timeout_s=105, + env={"ORBIFY_SIM_FLASH_ON_CONNECT": "1"}) + after(run.output, "Flash write on internal task stack: orb_catalog") after(run.output, "Full refresh: Done") assert not (folder / "mirror.request").exists() assert (folder / "walk.result").read_text() == "Done" @@ -165,6 +167,110 @@ def mirror_urls(ctx: Context, tmp: Path) -> None: +@scenario("x4-pro") +def full_refresh_large_catalog(ctx: Context, tmp: Path) -> None: + """Thousands of books through the real worker, HTTP parser and SD adapter. + The synthetic catalog is independent of the small live server library. + """ + import os + import subprocess + result = subprocess.run( + [sys.executable, str(ROOT / "xteink/test/bulk_bench.py"), "--checkout", + str(ctx.sim.program.parents[3]), "--out", str(tmp), "--books", "3000", + "--modes", "cold", "--timeout", "580"], + env={**os.environ, "ORBIFY_SIM_FLASH_ON_CONNECT": "1"}, + capture_output=True, text=True, timeout=600) + (ctx.artifacts / "large-catalog.log").write_text(result.stdout + result.stderr) + assert result.returncode == 0, result.stderr + stats = json.loads((tmp / "results.json").read_text())[0] + assert stats["rows"] == 3000 and stats["psramPeakBytes"] < 1024 * 1024 + after((tmp / "card/cold.log").read_text(), "Flash write on internal task stack: orb_catalog") + + +@scenario(*X4S) +def full_refresh_crash_breaker(ctx: Context, tmp: Path) -> None: + """Two unclean worker exits across cold boots must never start a third. + Keep settings, books and the published catalog; an explicit hold retries. + """ + card = ctx.card(tmp) + card.theme(UI_THEME_BOOKORBIT) + folder = card.crosspoint / "orbify" + folder.mkdir(exist_ok=True) + (folder / "mirror.request").write_text("1\n") + # No usable catalog is required for this safety boundary. Preserve arbitrary + # published bytes and books without parsing or deleting them in recovery. + published = card.crosspoint / "orbify-catalog" / "bulk" / "a" / "books" / "1.json" + published.parent.mkdir(parents=True) + published.write_text('{"id":1,"title":"kept"}') + (published.parents[2] / "stage").write_text("b") + path = card.add_book(ctx.source("Standalone 01")) + book_bytes = (card.fs / path.lstrip("/")).read_bytes() + credentials = (card.crosspoint / "bookorbit.json").read_bytes() + before = len(ctx.requests()) + for attempt in (1, 2): + run = ctx.sim.run(card, f"crash-{attempt}", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH": "1"}) + assert run.returncode == 86, f"worker did not reach injected crash: {run.returncode}" + assert (folder / "refresh.inflight").read_text() == str(attempt) + assert (folder / "mirror.request").exists() + # Leave the fault enabled: a third worker would immediately kill the process. + for name in ("recovered", "still-recovered"): + run = ctx.sim.run(card, name, script="6000:QUIT", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH": "1"}) + assert run.returncode == 0 + after(run.output, "crash breaker stopped automatic resume") + after(run.output, "Entering activity: Home") + assert not (folder / "mirror.request").exists() + assert (folder / "mirror.request.crashed").exists() + assert not (published.parents[2] / "stage").exists() + assert len(ctx.requests()) == before, "recovery restarted network work" + assert published.read_text() == '{"id":1,"title":"kept"}' + assert (card.fs / path.lstrip("/")).read_bytes() == book_bytes + assert (card.crosspoint / "bookorbit.json").read_bytes() == credentials + if ctx.profile == "x4-pro": + x, y = home_tile(run.output, "sync") + retry = ctx.sim.run(card, "explicit-retry", script=f"3000:TAP:{x},{y},1300", timeout_s=100, + env={"ORBIFY_SIM_QUIT_BULK_DONE": "1", "ORBIFY_SIM_FLASH_ON_CONNECT": "1"}) + after(retry.output, "Full refresh: Done") + assert retry.returncode == 0 + assert not (folder / "refresh.inflight").exists() + assert not (folder / "mirror.request.crashed").exists() + + +@scenario(*X4S) +def full_refresh_early_boot_breaker(ctx: Context, tmp: Path) -> None: + """A setup crash while refresh state exists must be broken before cache reads.""" + card = ctx.card(tmp) + folder = card.crosspoint / "orbify" + folder.mkdir(exist_ok=True) + (folder / "mirror.request").write_text("1\n") + bulk = card.crosspoint / "orbify-catalog" / "bulk" + bulk.mkdir(parents=True) + (bulk / "active").write_text("a") + (bulk / "active.bak").write_text("b") + saved = bulk / "a" / "books" / "1.json" + saved.parent.mkdir(parents=True) + saved.write_text("interrupted cache bytes") + credentials = (card.crosspoint / "bookorbit.json").read_bytes() + before = len(ctx.requests()) + for attempt in (1, 2): + run = ctx.sim.run(card, f"early-crash-{attempt}", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH_BOOT": "1"}) + assert run.returncode == 88 + assert (folder / "refresh-boot.inflight").read_text() == str(attempt) + run = ctx.sim.run(card, "early-recovered", script="6000:QUIT", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH_BOOT": "1"}) + assert run.returncode == 0 + after(run.output, "early-boot breaker disabled saved catalog pointer") + after(run.output, "Entering activity: Home") + assert not (bulk / "active").exists() and not (bulk / "active.bak").exists() + assert (bulk / "active.crashed").read_text() == "a" + assert saved.read_text() == "interrupted cache bytes" + assert not (folder / "refresh-boot.inflight").exists() + assert len(ctx.requests()) == before + assert (card.crosspoint / "bookorbit.json").read_bytes() == credentials + + @scenario("x4-pro") def full_refresh_offline_last_pages(ctx: Context, tmp: Path) -> None: """Full refresh on Home; SD-only facet page 2, book page 3 and lazy file information.""" diff --git a/xteink/test/resumed_work_stubs/HalStorage.h b/xteink/test/resumed_work_stubs/HalStorage.h new file mode 100644 index 00000000..bf0a31b3 --- /dev/null +++ b/xteink/test/resumed_work_stubs/HalStorage.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include +#include +#include +#include +#include +inline std::map files; +inline bool writable = true, synced = true; +struct HalFile { + std::string path; + size_t fileSize() const { return files[path].size(); } + size_t write(const uint8_t* p, size_t n) { files[path].assign(reinterpret_cast(p), n); return n; } + int read(uint8_t* p, size_t n) { n = std::min(n, files[path].size()); memcpy(p, files[path].data(), n); return n; } + bool sync() { return synced; } + void close() {} +}; +struct StorageStub { + bool mkdir(const char*) { return writable; } + bool exists(const char* p) { return files.count(p); } + bool openFileForRead(const char*, const char* p, HalFile& f) { f.path=p; return files.count(p); } + bool openFileForWrite(const char*, const char* p, HalFile& f) { if(!writable)return false;f.path=p;files[p].clear();return true; } + bool remove(const char* p) { return files.erase(p); } + bool rename(const char* a, const char* b) { if(!files.count(a))return false;files[b]=files[a];files.erase(a);return true; } +}; +inline StorageStub Storage; diff --git a/xteink/test/resumed_work_test.cpp b/xteink/test/resumed_work_test.cpp new file mode 100644 index 00000000..96f756b2 --- /dev/null +++ b/xteink/test/resumed_work_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "ResumedWork.h" +#include +#include +int main() { + files["settings"] = "kept"; files["book.epub"] = "book"; + ResumedWork first("/job"); + assert(!first.exhausted() && first.begin()); + assert(files["/job"] == "1"); + // New instances stand for cold boots; RTC and reset reason are irrelevant. + ResumedWork second("/job"); + assert(!second.exhausted() && second.begin()); + ResumedWork third("/job"); + assert(third.exhausted() && !third.begin()); + third.complete(); + for(int i=0;i<5;++i) { + assert(third.begin()); // normal pause/offline/cancellation never accumulates + third.complete(); + assert(!third.exhausted()); + } + files["/job.tmp"] = "2"; // reset between durable write and rename + assert(third.exhausted() && !third.begin()); + third.complete();files["/job"]="bad record"; + assert(third.exhausted() && !third.begin()); + third.complete();files["/job.tmp"]=""; + assert(third.exhausted()); // a partial write is never silently resumed + third.complete();writable=false; + assert(!third.begin());writable=true;synced=false; + assert(!third.begin());synced=true;third.complete(); + assert(files.size()==2 && files["settings"]=="kept" && files["book.epub"]=="book"); + puts("resumed-work: passed"); +} diff --git a/xteink/test/run-host-tests.sh b/xteink/test/run-host-tests.sh index 25199d87..bb5653ff 100755 --- a/xteink/test/run-host-tests.sh +++ b/xteink/test/run-host-tests.sh @@ -66,6 +66,11 @@ fi "$here/ota_return_test.cpp" "$repo/xteink/orbify/OtaReturn.cpp" -o "$out/ota_return_test" "$out/ota_return_test" +# Actual durable resumable-work breaker, including interrupted marker writes. +"${CXX:-c++}" -std=c++17 -Wall -Wextra -O1 -I"$here/resumed_work_stubs" -I"$repo/xteink/orbify" \ + "$here/resumed_work_test.cpp" -o "$out/resumed_work_test" +"$out/resumed_work_test" + # BookSync's own logic (xteink/orbify/core): pure C++, tested with ArduinoJson, the JSON library the # firmware links: the build fetches it, so CI runs these after the build. ajson="${ARDUINOJSON_DIR:-}" From 2bacf7ea86ff8aef5b5ae711948d7f307d340b45 Mon Sep 17 00:00:00 2001 From: Fledgewing <8509633+Fledgewing@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:34:54 -0800 Subject: [PATCH 2/3] Create large-catalog regression artifact directory Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BLYjLJzEkmBRpMx6vsJ4xw --- xteink/test/e2e/run.py | 1 + 1 file changed, 1 insertion(+) diff --git a/xteink/test/e2e/run.py b/xteink/test/e2e/run.py index 18288f1d..44707a31 100644 --- a/xteink/test/e2e/run.py +++ b/xteink/test/e2e/run.py @@ -180,6 +180,7 @@ def full_refresh_large_catalog(ctx: Context, tmp: Path) -> None: "--modes", "cold", "--timeout", "580"], env={**os.environ, "ORBIFY_SIM_FLASH_ON_CONNECT": "1"}, capture_output=True, text=True, timeout=600) + ctx.artifacts.mkdir(parents=True, exist_ok=True) (ctx.artifacts / "large-catalog.log").write_text(result.stdout + result.stderr) assert result.returncode == 0, result.stderr stats = json.loads((tmp / "results.json").read_text())[0] From 790cc76db5874e0ef2d641fa5165a008e7945746 Mon Sep 17 00:00:00 2001 From: Fledgewing <8509633+Fledgewing@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:37:25 -0800 Subject: [PATCH 3/3] Verify SD-only refresh recovery and retain catalog regression logs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BLYjLJzEkmBRpMx6vsJ4xw --- docs/design/emulated-release-tests.md | 1 + docs/design/full-refresh-crash-recovery.md | 4 ++++ xteink/test/e2e/run.py | 23 ++++++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/docs/design/emulated-release-tests.md b/docs/design/emulated-release-tests.md index 5b38959c..03847fda 100644 --- a/docs/design/emulated-release-tests.md +++ b/docs/design/emulated-release-tests.md @@ -476,6 +476,7 @@ series-card cover fetch and no lent connection, so it runs the three that apply | `sync_through_proxy` | foundation | all | | `mirror_urls` | X5, flash-safe refresh task stack | X4s | | `full_refresh_crash_breaker` | two unclean worker boots, durable quarantine, retained books/settings | X4s | +| `full_refresh_sd_card_recovery` | remove the single persisted request, boot without retrying | X4s | | `full_refresh_early_boot_breaker` | two setup crashes, disable suspect catalog before cache reads | X4s | | `full_refresh_large_catalog` | 3,000-book full catalog with modeled flash-stack constraint | X4 Pro | | `copy_refresh_sleep_sync` | X6 | all | diff --git a/docs/design/full-refresh-crash-recovery.md b/docs/design/full-refresh-crash-recovery.md index 475cab1d..b559bebf 100644 --- a/docs/design/full-refresh-crash-recovery.md +++ b/docs/design/full-refresh-crash-recovery.md @@ -75,6 +75,10 @@ verifies retained bytes, then retries through the real X4 Pro Home hold gesture. keep using ordinary Refresh and avoid Full refresh until installing a tested fix. Do not delete `/.crosspoint`, `bookorbit.json`, `wifi.json`, books or reading state, and do not erase NVS. The bulk stage files alone do not schedule work. + If it still fails while restoring the catalog, rename only the metadata folder + `/.crosspoint/orbify-catalog` to `/.crosspoint/orbify-catalog.recovery` on the card + and restart. This hides all bulk pointers/backups together and preserves their + bytes for inspection. Books and settings live elsewhere and remain intact. 3. Once booting, OTA can install a subsequently published fixed firmware through the normal update screen/channel. This change publishes no firmware. A test artifact is not offered by OTA; install a matching X4 Pro test image through diff --git a/xteink/test/e2e/run.py b/xteink/test/e2e/run.py index 44707a31..f08b1ad0 100644 --- a/xteink/test/e2e/run.py +++ b/xteink/test/e2e/run.py @@ -182,6 +182,9 @@ def full_refresh_large_catalog(ctx: Context, tmp: Path) -> None: capture_output=True, text=True, timeout=600) ctx.artifacts.mkdir(parents=True, exist_ok=True) (ctx.artifacts / "large-catalog.log").write_text(result.stdout + result.stderr) + import shutil + if (tmp / "card/cold.log").exists(): + shutil.copy2(tmp / "card/cold.log", ctx.artifacts / "large-catalog-firmware.log") assert result.returncode == 0, result.stderr stats = json.loads((tmp / "results.json").read_text())[0] assert stats["rows"] == 3000 and stats["psramPeakBytes"] < 1024 * 1024 @@ -238,6 +241,26 @@ def full_refresh_crash_breaker(ctx: Context, tmp: Path) -> None: assert not (folder / "mirror.request.crashed").exists() +@scenario(*X4S) +def full_refresh_sd_card_recovery(ctx: Context, tmp: Path) -> None: + """The recovery instruction cancels the persisted job without wiping settings.""" + card = ctx.card(tmp) + folder = card.crosspoint / "orbify" + folder.mkdir(exist_ok=True) + (folder / "mirror.request").write_text("1\n") + first = ctx.sim.run(card, "crashed", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH": "1"}) + assert first.returncode == 86 + # The sole card-reader operation prescribed for the installed firmware. + (folder / "mirror.request").unlink() + before = len(ctx.requests()) + recovered = ctx.sim.run(card, "sd-recovered", script="6000:QUIT", timeout_s=15, + env={"ORBIFY_SIM_CRASH_REFRESH": "1"}) + assert recovered.returncode == 0 + after(recovered.output, "Entering activity: Home") + assert len(ctx.requests()) == before + + @scenario(*X4S) def full_refresh_early_boot_breaker(ctx: Context, tmp: Path) -> None: """A setup crash while refresh state exists must be broken before cache reads."""