chore(memory): R3 stopped-state audit and fix recorded (BDR-055, BLK-011)

This commit is contained in:
bchanot committed 2026-10-16 18:27:58 +02:00
1 parent 6371523f8c
commit 9464651140
8 files changed
+228

No files matched your search

+1
View File
@@ -200,6 +200,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] R3 owner validation (LAN: TEST FONCTIONNEL + TEST GRAPHIQUE), then merge on the owner's go; R4 not started
- [x] R3 owner decisions 2026-10-15: unnamed trigger names per language (6882c6d, contract d8e9bd3); canvas engine failure (retry) vs view failure (no retry) (c0a5c8c)
- [x] R3 owner follow-up 2026-10-15: retry kept for `internal`; after the 3 recoveries a clear final state (`core.stopped`) in the canvas and the action alerts, no retry (BDR-054)
- [x] R3 owner-requested audit of 0279953 (2026-10-15/16): not satisfactory (unsaved draft promise, 4 dead retries, recovery dead end) → fixed 6371523 (BDR-055, BLK-011); verifier CONFORME 12/12, security PASS; residuals in BLK-011
- [ ] R3 follow-ups kept by the owner (2026-10-15): worker TLS exercised against a real HTTPS endpoint before the deployment that needs it; roxmltree limits + SVG prescan (pin the iterative release when published); Firefox/WebKit check; SVG references across drawings scoped per view before community uploads (Step 13); WASM size margin (396 of 600 KB) before R4; TypeScript PDF sanitiser still present until R4
- [ ] R4 pdf core: reader (Web Worker, BLK-009 browser measurements) + writer (`pdf-writer`, Std14 AFM, draw log; lines/rects/colours golden frozen with the TS engine first, D-R2) + `report-compare` tool; `packages/pdf` deleted; N-1 scanner reads R4 PDFs
- [ ] R5 curation pipeline + importer + upload tool: seed golden regenerated once (new `documentSha256`, D-R5), `packages/anatomy` + `packages/domain` deleted, docs map; all before Step 13
@@ -0,0 +1,68 @@
# CONTRACT — core-stopped-audit-fix
- date: 2026-10-15 | flow: bugfix | branch: feature/rust-r3-anatomy-core
- status: active
- plan: .claude/tasks/plans/2026-10-15-core-stopped-audit-fix-1830.md (rev 3, owner-approved 2026-10-15)
- base: 0279953 (run every CHECK from the repository root)
## REQUEST (verbatim — IMMUTABLE)
Je valide le comportement d'arrêt définitif du moteur WASM après trois reprises, ainsi que les messages FR/EN proposés.
La disparition du bouton « Réessayer » et la correction des huit alertes sont approuvées.
Effectue un dernier audit indépendant, ciblé uniquement sur cette correction : compteur de reprises, distinction erreur temporaire/arrêt définitif, réinitialisation après rechargement, cohérence des messages et conservation des données.
Vérifie particulièrement que le message annonçant la conservation du bilan ne soit pas trompeur si l'enregistrement du brouillon a échoué (quota ou autre erreur). Réutilise autant que possible les mécanismes de persistance et d'alerte déjà existants.
Si cet audit est satisfaisant, conserve les résultats dans le suivi. Ne recommence pas les audits complets de R3.
Les corrections UX et les formulations sont désormais acceptées.
R3 reste non fusionnée jusqu'à ma confirmation de la validation manuelle LAN. Ne commence pas R4.
## CLARIFICATIONS
Q: stopped + last save refused: what replaces « votre bilan est conservé » ? / A: variant `core.stopped_unsaved` + « Télécharger une copie » (in-memory report as JSON, no core). FR « Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger. » EN "Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading." [gated 2026-10-15]
Q: « plusieurs erreurs successives » inaccurate? / A: reword to « plusieurs erreurs » / "several errors", rest of `core.stopped` unchanged. [gated 2026-10-15]
Q: reload button on the stopped notice? / A: yes, `core.reload` « Recharger la page » / "Reload the page", only when the save is fine, never in the unsaved variant. [gated 2026-10-15]
Q: copy button on the existing storage-full banner (engine not stopped)? / A: yes, always; banner text (`editor.save_failed`) unchanged. [gated 2026-10-15]
Q: confirm reload / close while the report is not saved in the tab? / A: yes, native `beforeunload` while unsaved. [gated 2026-10-15]
Q: stopped notice placement on Home and New report? / A: top of the page content, below the header; in the editor, in place of the storage-full banner. [gated 2026-10-15]
Q: (internal, orchestrator) test helper extension in tests/helpers/core.ts outside the listed scope? / A: accepted: shared test seam, no product effect. [gated 2026-10-15]
Q: plan rev 3 approved, run on the branch, no merge, no R4? / A: yes. [gated 2026-10-15]
## ACCEPTANCE CRITERIA
1. A failed recovery below the cap is restarted by the next call or `ready()` (not counted as a recovery, compiled module reused); a failed first load is not; the default cap is 3; the third failed recovery or the fourth trap stops; listeners are notified after a microtask and a throwing listener changes nothing (core-wasm tests).
CHECK: cd packages/core-wasm && npx vitest run tests/runtime.test.ts > /tmp/cs-rt.log 2>&1 && grep -qi "restart" tests/runtime.test.ts && grep -qi "subscribe" tests/runtime.test.ts && echo RUNTIME_OK
EXPECT: RUNTIME_OK
EVIDENCE: MET exit=0 marker-found :: RUNTIME_OK
2. FR and EN dictionaries hold `core.stopped_unsaved` and `core.reload`, and `core.stopped` no longer says « successives » / "successive".
CHECK: f=apps/app/src/i18n/fr.ts; e=apps/app/src/i18n/en.ts; for k in core.stopped_unsaved core.reload core.stopped; do grep -q "'$k'" $f && grep -q "'$k'" $e || exit 1; done; grep -A2 "'core.stopped'" $f | grep -q successives && exit 1; grep -A2 "'core.stopped'" $e | grep -qi successive && exit 1; grep -A2 "'core.stopped'" $f | grep -q "plusieurs erreurs" && echo I18N_OK
EXPECT: I18N_OK
EVIDENCE: MET exit=0 marker-found :: I18N_OK
3. The ESLint census refuses a direct `t('core.action_failed')` outside src/core/failure.ts (positive control), and the tree lints clean.
CHECK: cd apps/app && echo "export const x = (t: (k: string) => string) => t('core.action_failed')" | npx eslint --stdin --stdin-filename src/app/routes/Probe.tsx > /dev/null 2>&1 && exit 1; echo "export const x = (t: (k: string) => string) => t('editor.export_failed')" | npx eslint --stdin --stdin-filename src/app/routes/Probe.tsx > /dev/null 2>&1 && exit 1; npx eslint . --max-warnings 0 > /dev/null 2>&1 && echo CENSUS_OK
EXPECT: CENSUS_OK
EVIDENCE: MET exit=0 marker-found :: CENSUS_OK
4. The whole app suite, typecheck and lint pass.
CHECK: ./node_modules/.bin/pnpm typecheck > /tmp/cs-tc.log 2>&1 && ./node_modules/.bin/pnpm test:run > /tmp/cs-test.log 2>&1 && ./node_modules/.bin/pnpm lint > /tmp/cs-lint.log 2>&1 && echo SUITES_OK
EXPECT: SUITES_OK
EVIDENCE: MET exit=0 marker-found :: SUITES_OK
5. No golden, oracle, seed, Rust crate or frozen package changed since the base.
CHECK: n=$(git status --porcelain -- apps/app/tests/fixtures crates supabase packages/domain packages/pdf packages/anatomy | wc -l); m=$(git diff --stat 0279953 -- apps/app/tests/fixtures crates supabase packages/domain packages/pdf packages/anatomy | wc -l); [ "$n" = 0 ] && [ "$m" = 0 ] && echo FROZEN_OK
EXPECT: FROZEN_OK
EVIDENCE: MET exit=0 marker-found :: FROZEN_OK
6. Stopped engine, save fine: every core page (Editor banner slot, Home, New report, the full-page CoreUnavailable) shows `core.stopped` with a « Recharger la page » button and no « Réessayer »; action / export / import / new-report failures say `core.stopped`. Tested.
7. Stopped engine, last save refused (`saveFailed` with a report in memory): the same surfaces show `core.stopped_unsaved` with « Télécharger une copie », never the reload button; the downloaded Blob content equals `JSON.stringify(report)` of the in-memory report; no message on any page names a button absent from that page. Tested.
8. Engine not stopped, save refused: the editor banner keeps the `editor.save_failed` text and gains the core-free « Télécharger une copie » button; a `beforeunload` handler is registered exactly while the report is unsaved. Tested.
9. Canvas: « Réessayer » (engine failure, not stopped) calls `coreRuntime().retry()` before rebuilding; a canvas engine failure shown while the engine becomes stopped switches to the stopped text with no button (derived at render, reactive to `saveFailed`). Tested.
10. A core failure while reading an unread draft makes `initReport` / `hydrateImport` return `{ ok: false }` without `reason: 'held'`, the draft untouched; New report and Home no longer say `session.held_blocked` for it (state.heldSession.test.ts inverted accordingly).
11. `HeldSessionPanel` download behaviour unchanged (shared helper); `core/sheetOps.ts` comment no longer names `core.action_failed` as the shown message; RUST.md §9.4 and the CHANGELOG R3 owner-decisions line describe the restart, the stopped notice placement and both variants.
12. No merge, no R4 work, no change outside the FILE SCOPE.
## FILE SCOPE
packages/core-wasm/src/runtime.ts, packages/core-wasm/tests/runtime.test.ts,
apps/app/src/core/{runtime,failure,sheetOps}.ts, apps/app/src/lib/download.ts (new),
apps/app/src/components/report/{CoreStoppedNotice.tsx (new),CoreUnavailable.tsx,HeldSessionPanel.tsx},
apps/app/src/components/canvas/AnatomyCanvas.tsx,
apps/app/src/app/routes/{EditorRoute,NewReportRoute,HomeRoute}.tsx, apps/app/src/state/reportStore.ts,
apps/app/src/i18n/{fr,en}.ts, apps/app/eslint.config.js, apps/app/tests/unit/** (new or updated tests), apps/app/tests/helpers/core.ts (test seam `controlStopped`; internal, added after verifier pass 1),
docs/development/RUST.md, CHANGELOG.md
@@ -0,0 +1,129 @@
# Plan — engine stopped: audit fixes on 0279953 (bugfix, branch feature/rust-r3-anatomy-core)
## Context
Commit 0279953 added `CoreRuntime.stopped` (recovery cap 3 spent), `coreStopped()`, `coreFailureMessage(t)`
(apps/app/src/core/failure.ts), canvas failure `engine_stopped`, key `core.stopped` ("reload the page, your
report is kept in this tab"). Independent audit found:
- A. `core.stopped` ignores `reportStore.saveFailed` (set by the draft mirror when sessionStorage refuses a write,
reportStore.ts:392-396, shown as banner `editor.save_failed` "Exportez le PDF pour les conserver",
EditorRoute.tsx:303). Once stopped, export needs the core (pdf/export.ts:37 `index.ops.snapshot`) → impossible.
Reload restores the last successful write → edits since the refused write lost, unannounced.
- B. Surfaces still offering a retry that cannot work once stopped: CoreUnavailable (EditorRoute.tsx:257,
`sheet.retry` → runtime.retry() returns false at cap), export catch (`editor.export_failed` "Réessayez"),
import (`home.import.error_core_unavailable` "Réessayez l'import"), NewReportRoute.tsx:55
(`sheet.core_unavailable`). Also `releaseUnreadSession` (reportStore.ts:248-262) returns false on a core
failure, so initReport / hydrateImport return HELD and the pages say `session.held_blocked` (wrong cause).
- C. Canvas "Réessayer" (AnatomyCanvas.tsx ~145) only bumps `attempt` (rebuild), never calls
`coreRuntime().retry()`: after a failed recovery below the cap (state unavailable, stopped false) it is a dead end.
- D. Stale comment core/sheetOps.ts:17; test gaps (default cap 3 unpinned, failed recovery below/at cap, no census
of call sites, no stopped+saveFailed test).
Owner choices (AskUserQuestion 2026-10-15):
1. stopped + save failed → variant message `core.stopped_unsaved` + "Télécharger une copie" button writing the
IN-MEMORY report as JSON, no core (rescue copy; not importable today, import reads PDFs only).
FR: « Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet
onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la
page. Téléchargez une copie avant de recharger. »
EN: "Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest
changes are not saved and would be lost if you reload the page. Download a copy before reloading."
2. `core.stopped` wording: "plusieurs erreurs successives" → "plusieurs erreurs" (EN "several successive errors"
→ "several errors"); rest unchanged.
3. "Recharger la page" button (new key `core.reload`, FR « Recharger la page », EN "Reload the page") on the
stopped notice ONLY when the save is fine; never in the unsaved variant.
## Fix plan (rev 2, after 3 challengers)
1. packages/core-wasm/src/runtime.ts —
a. Self-restart after a failed recovery (closes C everywhere, not only on the canvas): `restartable` =
`state === 'unavailable' && !stopped && generation > 0` (an instance ran before: a failed recovery or a
failed restart; a failed FIRST load stays on useSheet's explicit retry). `ready()` on a restartable runtime
returns `this.retry()` (awaits the restart); every CORE_UNAVAILABLE answer of `invoke()` and of
`SheetSession.current()` on a restartable runtime kicks `void this.retry()` and still answers
CORE_UNAVAILABLE (the next user action works: "Réessayez" becomes true). No counter change: a restart is
not a recovery; the cap still counts traps. A restart keeps `compiled` when `generation > 0` (the module
already ran; only a failed FIRST load clears it), so a restart fetches a glue record, never recompiles.
b. Status listeners: `subscribe(listener): () => void`. Notification is deferred (`queueMicrotask`) after the
transition, never inside the try blocks of load/recover, each listener wrapped in try/catch; a throwing or
re-entrant listener cannot change the state machine.
2. apps/app/src/core/runtime.ts — module-scope `subscribeCore(cb) = coreRuntime().subscribe(cb)` (stable
identity) and `useCoreStopped()` = `useSyncExternalStore(subscribeCore, coreStopped)`. Used on the three core
pages only (Editor, Home, New report); creating the runtime object loads nothing (lazy load stays on ready()).
3. apps/app/src/state/reportStore.ts —
a. exported selector `isUnsaved(s) = s.saveFailed && s.report !== null` (one rule, used by the notice and the
alerts).
b. `releaseUnreadSession` / `mayStartSession` return `ActionResult`: set-aside failure → HELD; core cannot read
the unread draft (any kind outside UNREADABLE_DRAFT_KINDS) → FAILED (never HELD); initReport / hydrateImport:
`const may = mayStartSession(index); if (!may.ok) return may`. Nothing written in either case (unchanged).
4. apps/app/src/core/failure.ts — `stoppedMessageKey()` = `isUnsaved(useReportStore.getState()) ?
'core.stopped_unsaved' : 'core.stopped'`; `coreFailureMessage(t, fallbackKey = 'core.action_failed')`:
stopped → `t(stoppedMessageKey())`, else `t(fallbackKey)`.
5. apps/app/src/lib/download.ts (new) — `downloadJson(raw, stem)`: body of HeldSessionPanel's `downloadCopy`
(Blob application/json, anchor attached while clicked, URL revoked after 30 s, `<stem>-<todayIso()>.json`).
HeldSessionPanel calls it (behaviour unchanged).
6. apps/app/src/components/report/CoreStoppedNotice.tsx (new) — the one host of the stopped buttons. Reads
`useReportStore(isUnsaved)` and `report`. unsaved → Notice error `core.stopped_unsaved` + Button
`session.held.download` (reused key) → `downloadJson(JSON.stringify(report), 'faunosteo-brouillon')`;
otherwise Notice error `core.stopped` + Button `core.reload` → `window.location.reload()`. Never a retry.
`CoreStoppedBanner` (same file or inline) = `useCoreStopped() ? <CoreStoppedNotice/> : null`.
7. Placement (persistent, whenever stopped, so alerts never name a button that is not on the page):
- EditorRoute banner slot: stopped → `<CoreStoppedNotice/>` (same margins as the save banner) INSTEAD of
`editor.save_failed`; not stopped + saveFailed → `editor.save_failed` text + the same core-free
"Télécharger une copie" button [rev 3, owner gate Q1]: the rescue exists in every engine state (a restart that
keeps failing offline never reaches `stopped`).
- [rev 3, owner gate Q2] `beforeunload` guard while `isUnsaved` (native browser confirm), registered in
EditorRoute; removed when the save recovers.
- HomeRoute and NewReportRoute: `<CoreStoppedBanner/>` at the top of the page content (below the header), so the
unsaved variant's download is on every page that can show its text.
- CoreUnavailable: `useCoreStopped()` → `<main><CoreStoppedNotice/></main>` instead of notice + retry.
8. apps/app/src/components/canvas/AnatomyCanvas.tsx — the engine variant is derived at render: a build failure
`engine` with `useCoreStopped()` true (or a build `engine_stopped`) → Notice with the stopped text chosen from
`useReportStore(isUnsaved)` (reactive), no button (the page banner holds the buttons; DetailModal never opens once stopped: a zone click is a core call).
"Réessayer" (engine only): `void coreRuntime().retry().finally(() => setAttempt(n => n + 1))`.
9. Alerts / error lines: EditorRoute export catch → `coreFailureMessage(t, 'editor.export_failed')`;
NewReportRoute:55 → `coreFailureMessage(t, 'sheet.core_unavailable')`; HomeRoute `importErrorMessage`
core_unavailable → `coreFailureMessage(t, 'home.import.error_core_unavailable')`; HomeRoute hydrateImport
`!ok`: `reason === 'held'` → held alert + navigate (unchanged), else throw `ImportError('core_unavailable')`.
10. apps/app/src/core/sheetOps.ts:17 comment → "shows `coreFailureMessage`".
11. i18n fr.ts / en.ts — `core.stopped` reworded (choice 2); new `core.stopped_unsaved`, `core.reload`.
12. ESLint (apps/app/eslint.config.js): `no-restricted-syntax` on `t('core.action_failed')`,
`t('editor.export_failed')`, `t('home.import.error_core_unavailable')`, `t('sheet.core_unavailable')` call
literals in src, except src/core/failure.ts, and for `sheet.core_unavailable` also CoreUnavailable.tsx and
AnatomyCanvas.tsx (the census, codebase idiom; dictionaries are not call sites).
13. docs/development/RUST.md §9.4 (+ §8 runtime note if it describes recovery) and the CHANGELOG R3 owner-decisions
line: restart on next action after a failed recovery; stopped notice on the core pages (reload, or unsaved
variant with copy); export / import / new report say the stopped message.
## Tests
- core-wasm runtime.test.ts: default cap = 3 (three recoveries succeed, fourth trap → stopped, retry false);
failed recovery below the cap → stopped false, then the next call kicks a restart and the call after it
succeeds; `ready()` after a failed recovery restarts and resolves true; third recovery fails → stopped true, no
restart kicked; a failed first load is NOT restarted by a call (only retry()); subscribe notified (after a
microtask) on the transition to stopped, a throwing listener does not change the state, unsubscribe stops it.
- AnatomyCanvas: engine retry calls `coreRuntime().retry()` (spy) then rebuilds; engine_stopped shows the stopped
text (unsaved variant when isUnsaved) and no button.
- CoreStoppedNotice: save fine → `core.stopped` + reload button, no retry; isUnsaved → `core.stopped_unsaved` +
download whose Blob content equals JSON.stringify(report).
- EditorRoute: stopped → banner notice replaces `editor.save_failed`; not stopped + saveFailed → save banner
with the copy button; beforeunload registered only while isUnsaved; export failure while stopped → stopped alert.
- runtime: a restart after a failed recovery reuses `compiled` (compile called once).
- HomeRoute / NewReportRoute: stopped → banner present; stopped + unsaved → download button on the page.
- state.heldSession.test.ts:268-280 inverted: core cannot read the draft → `{ ok: false }` without
`reason: 'held'`, draft untouched; same for hydrateImport.
- ESLint rule proven: lint fails on a sample `t('core.action_failed')` outside failure.ts (rule test via
`pnpm lint` on the tree + one RuleTester-free check: the tree lints clean).
- `pnpm typecheck && pnpm test:run && pnpm lint` green; core-wasm vitest green (TS-only runtime change, no wasm
rebuild; stamp unaffected).
## Known residuals (recorded, not fixed here)
- `saveFailed` also covers a refused archive write (BDR-052 banner semantics, pre-existing): the unsaved variant
over-warns then; the copy holds the report, the archive is the imported PDF still on disk.
- Kinds such as `rebase_failed` (sheet defect) answer FAILED → "Réessayez" (generic; near-unreachable).
- Home while not stopped but the engine cannot restart (offline) and saveFailed: no banner there; the editor
banner holds the copy.
- New report banner "Recharger la page" discards a typed form (shown from page entry, so usually before typing).
- New report / import while an open report has saveFailed replace it (pre-existing; deliberate user action).
- A draft that traps the core on every load → reload loop (pre-existing).
## Out of scope
R4, merge, the frozen PDF engine, Rust crates, goldens; making the JSON copy importable.