Skip to main content

0002 — Offline training persistence & deferred upload

Status: Implemented · Decided: 2026-06-11 · Implemented: 2026-06-15

Context​

Strength facilities frequently have no internet. Two needs follow:

  1. Crash safety. Today the entire in-session training state — sessions, sets, reps, raw sensor data — lives only in React state (use-training-sessions.ts, useState<WorkoutSession[]>). An app crash, OS kill (common on backgrounded iOS apps), or refresh loses everything recorded so far.
  2. Deferred upload. use-finish-training.ts calls postWorkoutSessions (POST /workout_sessions) directly; on failure it only keeps the view open. There is no queue, so a finish with no connectivity has nowhere to go.

The only persistence primitives in use today are localStorage (auth token, device id, a few UI flags). Installed natively: just @capacitor/core — no Preferences/Filesystem/SQLite/Network plugin.

A second concern shapes the design: the workout being trained usually has no durable backend counterpart. Templates picked via the FAB are cloned with a fresh crypto.randomUUID() and never saved; recurring "today" instances are client-side projections; empty/on-the-fly workouts are client-only; and all mid-session edits (add athlete/exercise, edit block normatives) live solely in workout-draft-context.tsx with no save endpoint (block normatives are explicitly client-only — see dtos/workouts.ts). So the workout structure, not just the recorded data, is unrecoverable after a crash unless persisted locally.

This ADR covers Plan A (crash-safe local persistence + deferred upload) and Plan B (download-the-day's-workouts for fully offline use), which reuses the same storage layer. Plan A shipped first (2026-06-11); Plan B followed (2026-06-15) — see "Implementation notes" → "Plan B".

Concurrency note​

This work is being implemented alongside a separate effort on the BLE/sensor connection flow (packages/core/src/ble/*, native plugins, use-sensor-connection.ts, use-sensor-reps.ts, ConnectSensorSheet.tsx). Plan A deliberately sits downstream of all BLE code — it observes the WorkoutSession tree, never sensor events — so the two efforts share only one file (use-training-sessions.ts) and otherwise do not overlap. See "The seam".

Decision​

Storage engine: IndexedDB​

Use IndexedDB, wrapped in a thin packages/core/src/offline/db.ts. It works identically in web and the iOS/Android WebView with zero native code, is async, handles large blobs, and keeps everything in the shared pure-TS layer — off the native surface the BLE effort owns. SQLite (@capacitor-community/sqlite) was rejected: a new native plugin on both platforms (colliding with the BLE work) plus a wasm web fallback, for querying we don't need. localStorage is disqualified by raw-data volume; Filesystem-JSON by clumsy incremental writes.

db.ts is flexible storage infrastructure, not a data model. It owns the connection, versioning, a declarative store registry (names + keyPath + indices), and generic typed CRUD (get/getAll/getAllByIndex/put/ putMany/delete/deleteMany/tx). Record shapes live in the feature modules on top of it, so Plan B can later register more stores without touching db.ts, and BLE-driven changes to WorkoutSession never reach the storage layer.

Owning the connection includes surviving its loss (amendment 6): the handle reopens itself when the platform closes the connection underneath it, and a failed open is never cached.

Object stores​

StoreKeyHolds
inProgressSessionssession.id (index: workoutId, stationId)Live WorkoutSession tree (domain model), schemaVersion-stamped. Raw rep data stored as a gzipped encoded blob.
activeWorkoutsstationIdThe live draft WorkoutReturnDtoV2 (items, blocks/normatives, participants) — schemaVersion-stamped.
meta.activeWorkoutfixed keyStation roster + mode (which station UUIDs are active, single vs multi, sessionWeight, trackingDetailMode).
sensorAssignmentsstationIdPer-station sensor routing intent (deviceId, name, position, isSmartBar, unit pairing) — serializable fields only, no live adapter.
pendingUploadsbatchId (index: createdAt)Wire-format payload (mapped SessionCreateDto[], gzipped+base64 data inline).

What is persisted (and why these things specifically)​

  • Sessions/sets/reps/measurements — the recorded data; the core data-loss risk. Stored as the full WorkoutSession tree so it also carries userExercise (1RM history) and per-set normatives, making recovery network-free.
  • Raw sensor data — the bulk. Persisted as a gzipped JSON blob of the rep's SensorDataPoint[], computed once at set-completion (raw is immutable after capture). Deviation from the original plan (which stored the encodeRepData Float32 wire blob): the wire encoder is lossy — jump mode resamples time and offsets vertical position by the first sample — and has no inverse, so a stored wire blob could not faithfully restore a rep's rawData for the on-device chart after a crash. Gzipped JSON round-trips the exact in-app representation; the upload path re-encodes from the restored data at send time (cheap, deterministic). Storage cost is somewhat higher than the packed blob but still negligible against the native WebView quota.
  • The workout structure (draft) — because it often has no backend counterpart and reflects mid-session edits. Persisted as the draft-merged workout (not the original fetched DTO), on the same continuous cadence as sessions.
  • Station roster + sensor routing — to rebuild a multi-station screen and re-pair sensors after a crash.

Write strategy (A1)​

Hook persistence into use-training-sessions.ts (the one shared file). Write:

  • per rep-append (incremental, ~9 KB, reps land seconds apart) — crash granularity is one rep. As shipped (amendment 3): the committed session tree mirrors on set completion + edits (TrainingSession), and the not-yet-completed set's reps mirror per rep via the pending-rep buffer (pendingSensorReps store, written by use-station-reps).
  • on set-completion (the rep+raw burst, one putMany, ~40 KB gzipped);
  • on visibilitychange: hidden (force-flush dirty records — iOS kills backgrounded apps; this is a web-standard event, not BLE). Subsumed by amendment 3: both mirrors write on every change with no debounce, so there is never a dirty window for a hidden-flush to save; the onHide helper in connectivity.ts stays unused by design.

encodeRepData + gzip run at set boundaries, not per sample, so the BLE→state→disk path stays async and never blocks live recording.

Recovery (A2)​

Two stores, different authority:

  • inProgressSessions is authoritative for trained data — restore sessions directly from it. The hook's derive is an additive reconcile keyed on (workoutItemID, userID) (amended 2026-07-11): recovered pairs are found covered and left untouched; only genuinely missing pairs are created via createInitialSessions. A full rebuild over recovered data is structurally impossible.
  • activeWorkouts is authoritative for the shell — item ordering, block/superset grouping, header, not-yet-started items.

Hydrate shell from activeWorkouts, sessions from inProgressSessions, re-associate by stationId + workoutItemID, then hand sensorAssignments to the BLE reconnect flow. Recover with all drawers/sheets closed.

Deferred upload (A3)​

Rework use-finish-training.ts: enqueue the wire payload under a fresh batchId (persisted before any network call) → close the view (the user is never blocked by connectivity) → flush. Because uploads are idempotent on client-owned IDs and the server rolls back on any error/connection loss, flush is simple:

  • 2xx → delete the batch's pendingUploads entries and its inProgressSessions copies, in one transaction.
  • any error (network, 5xx, dropped connection) → the server wrote nothing; keep the batch and retry it verbatim.

Retry triggers: app launch (post-login), online event, visibility-regain, and a manual "Upload now" button. flush is guarded against concurrent runs. A persistent indicator surfaces pending count + manual retry.

Eviction & quota​

Call navigator.storage.persist() at boot to move storage out of evictable "best-effort" mode, and navigator.storage.estimate() to warn before a write fails. On Capacitor native (the primary platform) WebView storage is already durable, so these are hygiene rather than load-bearing; they matter more for the rarely-offline web case.

Schema drift​

pendingUploads stores wire format, so a future models.ts change cannot break a queued upload — immune by construction. inProgressSessions and activeWorkouts carry a schemaVersion stamp; on a mismatch at hydrate, the record is discarded with a logged warning rather than migrated — this data only lives for one training session, so migration code isn't worth it.

The seam (coordination with the BLE effort)​

  • Plan A touches no ble/ file, native plugin, or sensor hook. It reads the WorkoutSession tree only — the convergence point downstream of however a rep was produced.
  • Live BleConnection / SensorAdapter are not serialized. sensorAssignments persists only the routing table; the BLE flow re-establishes connections on recovery via its own assignSensor / assignUnit.
  • Single shared file: use-training-sessions.ts (persistence effect + hydrate path, distinct from the rep-intake region).

Sizing​

Driven entirely by raw data (everything else is kilobytes). Encoder: ~62.5 Hz; strength = 12 floats/sample (48 B packed), ~190 samples per rep.

FormatBytes/rep
Raw SensorDataPoint[] objects~55 KBrejected — ~6× larger
Encoded Float32 blob~9 KBupload-ready
Gzipped encoded blob~4–5 KBchosen — equals upload payload

Worst-case multi-station workout (4 athletes × 6 exercises, ~1150 reps): ~5 MB gzipped — negligible against native WebView quota. Writes are single-digit-ms putManys at set boundaries; hydration reads tens of ms; chart decode is lazy per set viewed.

Scope​

  • In: the workout-driven in-session flow (single- and multi-station), including the draft workout structure and raw sensor data.
  • Out: feedback-training mode — volatile by design, no recovery for now.
  • In (Plan B, shipped 2026-06-15): download-for-offline of the day's workouts + the per-athlete exercise instances, plus cold-start snapshots of the global reference catalogues — all reusing db.ts.

Consequences​

  • New module packages/core/src/offline/ (db.ts, session-store.ts, upload-queue.ts, connectivity.ts, co-located *.test.ts with fake-indexeddb). Plus thin wiring in use-training-sessions.ts, use-finish-training.ts, and a launch/online flush + pending indicator at the today-page level.
  • Data survives crash, OS kill, and offline finishes; uploads retry until they land.
  • Erase-on-logout is accepted: the offline stores join the logout wipeAll, so a coach cannot log out and still upload later. No per-user scoping needed. Revised by amendment 2 (2026-07-11): the database survives logout and is owner-scoped instead. Logout — explicit or the involuntary 401 (there is no token refresh, so an expired token while backgrounded lands here) — clears only in-memory state. The database is stamped with baseUrl::userId in the meta store (ensureOfflineOwner, applied by offline/owner.ts awaited in login/register and fired at boot by AuthGuard): the same account's next login resumes recovery + queued uploads; a different account's login wipes first (intended — account switch removes the previous account's local data; since 2026-10 the sign-in asks before a wipe that would delete unsynced uploads, videos or in-progress trainings, see OtherAccountOfflineDataError); an unstamped database is adopted (pre-amendment builds wiped on logout, so unstamped data can only belong to the signed-in account). Account deletion wipes explicitly. drainUploads/drainVideos additionally refuse to send when the stamped owner doesn't match the caller's account, so a stale queue can never upload under another account's token.
  • A future breaking change to models.ts mid-session discards in-progress recovery data (not queued uploads) — an accepted, narrow window.

Implementation notes (as shipped)​

  • Module packages/core/src/offline/: compression.ts (native gzip via CompressionStream), db.ts (generic IndexedDB engine — store registry, typed CRUD, atomic tx), stores.ts (the registry + singleton), plus session-store.ts, shell-store.ts, upload-queue.ts, connectivity.ts, and orchestrator.ts (the app-facing composition). All unit-tested with fake-indexeddb.
  • Persistence is wired in TrainingSession (it owns the live draft + the session tree) rather than only use-training-sessions.ts; it writes the draft shell + the session set on every change (skipped while the initial session reconcile is still loading). A clean finish/discard clears the station's recovery state; a crash leaves it for recovery.
  • Sessions reconcile, never rebuild (amended 2026-07-11). Sessions are owned local entities keyed by (workoutItemID, userID): the derive in use-training-sessions.ts is an additive reconcile (missingSessionPairs + mergeNewSessions in training/sessions.ts) that creates only missing pairs and never wipes or replaces existing ones. A workout reference that changes identity without changing content is a guaranteed no-op — the previous wipe-and-rebuild let a profile refetch on app resume destroy the live session state and (via the mirror) its recovery copy.
  • The disk mirror cannot destroy data. persistSessions still replaces a station's set per write (rows absent from a non-empty mirror are pruned — that is how an explicit in-state removal, e.g. a removed athlete, reaches disk), but it refuses an empty write: an empty list is indistinguishable from an unhydrated one. Destruction is explicit only — deleteSessions / deleteStationSessions / deleteStationSessionRows(stationId, ids) (the orchestrator's athlete-removal path).
  • Per-station write lane (orchestrator). All disk mutations of a station's recovery state (mirror writes, explicit row deletes, the final discard) run on a per-station promise chain in call order, with mirror writes coalesced latest-wins. Without it, overlapping fire-and-forget writes could commit out of order (an older snapshot clobbering a newer one), and a discard could lose to an in-flight write and resurrect a finished session.
  • Recovery is resume-in-place: on launch recoverStations pairs each saved shell with its sessions, rebuilds the station(s) and injects the recovered sessions. The reconcile then finds every recovered pair covered (no backend re-derive over them); pairs the recovery did not cover — an empty shell, a partially-persisted athlete — are healed by creating them fresh. (Amended 2026-11-20: recovery no longer asks "Resume interrupted training?" — it resumes at once, so the coach sees what is still running. Discarding happens from inside the training, which runs the same cleanup.)
  • Pending-upload indicator: a floating pill (sidebar bottom-left chip in multi-station; fixed bottom-left button in the single-station root) showing the queued-batch count with a manual "Upload now", plus a near-quota storage warning. navigator.storage.persist() is requested at boot.
  • Live in-progress reps — CLOSED (amendment 3, 2026-07-12). The not-yet-completed set's reps are durable per rep: use-station-reps mirrors its combined (restored + live) buffer to the pendingSensorReps store on every change, one record per (station, item, athlete) — reps belong to whoever was on the bar when they arrived, so an athlete switch PARKS the buffer instead of leaking it into the next athlete's set (the reset key includes the athlete), and switching back restores it. Recovery re-presents, never auto-commits: reopening the exercise/athlete shows the unsaved reps in the recording overlay; "Complete set" stays the commit point. Empty states are never written (hydration-gated, PR1 rule); emptying is explicit — save/dismiss (clearReps), athlete removal (deleteStationPendingRepsForUsers), and discardStation — all on the station write lane, including the hydrate READ (a restore must see a park still in flight). Raw data is gzipped WITHOUT session-store's identity-keyed memo: the continuation window mutates a pending rep's rawData in place. The feedback modes' scratchpad sets stay deliberately transient (no persistence passed). Remaining narrow window: the Set-Summary draft path (flag default-off) clears the parked buffer when the summary opens, so a kill while the summary is on screen loses that one candidate set.
  • Reps arriving while backgrounded are a separate platform-capture question (native BLE keeps delivering; the JS pipeline may be suspended) — see the open questions.

Plan B — "make the day offline-ready" (shipped 2026-06-15)​

  • New stores (DB_VERSION → 4, additive): cachedWorkouts (the day's WorkoutReturnDtoV2, indexed by dateKey), cachedUserExercises (the per-athlete ExerciseForChildUserReturnDto, keyed ${dateKey}|${defID}|${userID}), cachedExercises (per-exercise display metadata ExerciseMappedReturnDto by id — the workout view fetches this via getExercise and would otherwise error offline), cachedExerciseBases (per-exercise base by id — the displayBaseExerciseGroupID the block/normative editor filters its base picker on, fetched lazily via getExerciseBase; without it block editing is impossible offline), offlineDays (one manifest per ready day), and cachedReference (gzipped cold-start snapshots of the global catalogues — since 2026-09-07 including tracking-source-settings, the last catalogue without one: a device started offline had no sensor configuration at all, which the today page reports as "Tracking setup unavailable").
  • Per-id lazy fetches (getExercise, getExerciseBase) are the offline trap: they aren't part of any boot prefetch, so each needs both a download pre-warm AND a cache-on-load + offline-fallback in its store (exercise-bases/store.ts, use-workout-exercises.ts). The normatives themselves (bases/categories/metrics) ride the cached metrics snapshot.
  • The day key is always todayDateKey() (dateKeyFromMs(Date.now())), used identically by the chip and by session-start. Critically, it is never derived from workout.date: that field encodes a time-of-day on a templated date (often 1970 for recurring workouts — see workouts-today-list.tsx), so keying off it would never match the downloaded bundle.
  • day-bundle-store.ts owns the day records, the pure coverage helpers (requiredPairsForWorkout / missingPairs / uncoveredUserIDs), and a whole-day replace on re-download (prunes a dropped athlete/exercise). The one network dependency of session-start is getExercisesForWorkout; everything else createInitialSessions needs is global reference data.
  • reference-cache.ts snapshots each reference store's payload (gzipped JSON) on every successful boot load and serves it back when the fetch fails — so a launch with no network still resolves names / metrics / equipment. Wired into all six stores via loadWithCache (metrics, text-content, equipments, exercise-variations, tags, display-bases).
  • The chip (OfflineReadyChip + use-offline-day.ts) sits above the schedule list and bundles exactly the workouts shown. The schedule page falls back to loadDayWorkouts when the fetch fails offline.
  • Uncovered athletes (a roster the bundle doesn't cover) are flagged in the athlete picker and blocked with a banner at session start, and a workout with NO covered pair at all can't be started (the coversNoPair Start gate). Removed by amendment 7 (2026-10-05): sessions — and therefore every set — used to exist only for a covered (exercise × athlete) pair, so an uncovered pair recorded nothing and the gate was the honest answer. It also meant that without a same-day download nothing at all could be recorded offline, and an ad-hoc workout never could. An uncovered pair now starts as an unbound session — see "Implementation notes — unbound sessions". The bundle is what makes an offline start come with the athlete's history (1RM, velocity models); it is no longer what makes it possible.
  • Hygiene: past days' bundles are pruned on mount (pruneOfflineDaysBefore); the owner-mismatch wipe (wipeOfflineData via ensureOfflineOwner, see the amendment-2 consequence above — no longer run on logout) drops the whole DB, covering the new stores. Gated behind the reversible OFFLINE_READY_CHIP flag.

Implementation notes — unbound sessions (amendment 7, 2026-10-05)​

The rule: starting, recording and finishing never wait on the network. The one place that still did was the session itself. SessionCreateDto.exerciseID is the athlete's exercise instance, an id only the server issues (POST /exercises/exercise_for_user/workout), and a session could not be created without it. Offline the only source was the manually downloaded day bundle, so a coach who had not pressed "Load workouts" that same day — or who composed a workout on the spot — could record nothing.

A session can now exist without its instance:

  • Model. WorkoutSession.exerciseID and userExercise are nullable and null together — an unbound session (isUnboundSession, training/sessions.ts). exerciseDefinitionID + userID, which the session always carried, are what the instance is resolved from. Everything that reads the instance (userExercise.models / .measurements — 1RM baseline, velocity profile, load advice) already had a "no history" branch and takes it.
  • Creation. createInitialSessions(…, allowUnbound) creates an unbound session for a pair the lookup has no instance for. The flag is set from the resolve's source (resolve-user-exercises.ts): a pair is unknown when the server could not be asked (cache-offline, cache-after-error) and starts unbound; it is a verdict when the server answered without an instance (server) and still gets no session — recording into it would collect data that can never upload. A refused resolve (a deterministic 4xx) is the only thing that still rejects.
  • No placeholder 1RM. addFocusMetricIfMissing leaves an unbound session alone. The athlete's history is unknown, not absent, and the 100 kg fallback would be a made-up 1RM uploaded with the session. The coach can type one; an estimate from the session's own work sets is written as before. Until either exists the 1RM stat shows a dash rather than the view's 100 baseline (focusUnknown, ExerciseDetailView).
  • Exchange. An exercise swapped mid-training whose new instance cannot be resolved re-points the session at the new definition, unbound (applyUnboundExerciseExchange). Before, the session stayed on the previous instance and everything recorded afterwards was stored and uploaded under the old exercise — with a warning when truly offline, silently when the request merely failed. unresolvedExchangeIDs remains for the one case left: the server has no instance of the new exercise for that athlete.
  • Binding while training. TrainingSession probes the server while any session is unbound — immediately, on every retry opportunity, and every 30 s (UNBOUND_BIND_RETRY_MS; on a Wi-Fi without internet nothing else would notice the internet coming back). A resolved session is bound in place (bindSessionExercise): history seeded unless a value already exists, 1RM recomputed, scheme rebuilt. This only improves the running training. The probe is one request for every unbound pair; when the server refuses it, the request is repeated per athlete (fetchUserExercises), so one athlete the coach lost access to does not keep every other session unbound. A session the server was asked about and has no instance for is reported as unbindableSessionIDs: the view then says the exercise cannot be matched instead of promising an upload "once you're back online", and the 30 s probe stops for it (retry opportunities still ask again).
  • Roster edits mid-training. An athlete or exercise added while training goes through the same resolve as the start and gets an unbound session when the server cannot be asked. What is still missing is derived from the training as edited (useTrainingSessions' roster, the draft minus the items of an edit that is still open), never from the workout the training was started with. Three consequences: a retry — the coach's, or the unattended one on a retry opportunity — covers every pair without a session, however many adds failed before it (it used to remember only the last one, and for a pair the server had answered "no instance" for it retried nothing at all); a pair no pass has asked about is attempted once without waiting for a connectivity change; and a warning is shown only while its pair is still missing (pruneUnresolved), so it goes away when the session arrives or the athlete or exercise is removed again.
  • Binding at upload — the guarantee. Mirrors the data-package type repair below. toSessionCreateDto writes the nil UUID (UNBOUND_EXERCISE_ID) for an unbound session; finishAndUpload records session.id → { definition, athlete } beside the payload (PendingUpload.unboundSessions, in the same transaction as the batch); postSessionBatch resolves the instances — one request per athlete, since the route checks access to every requested user up front — and sends a patched copy. The placeholder is never sent: a session the server has no instance for raises UnboundSessionError, which the queue treats as a deterministic rejection (kept, counted, the batches behind it still upload). A resolve that cannot reach the server is transient like any other. Recording the refs is not best-effort, unlike the package keys: without them the batch could never be sent.
  • Deadlines are enforced in the transport seam (httpFetch, api/transport.ts). With CapacitorHttp enabled Capacitor's patched fetch routes every POST / PUT / PATCH / DELETE to the native plugin and never reads the abort signal, so on a device a write to an unreachable server ignored its deadline (native default: 600 s on iOS, none on Android). The resolve is a POST; without this an unbound start would still hang.
  • "Reachable" means the reachability store, not navigator.onLine, for the start-time resolve: when the backend is known not to answer, the cache is read without spending a request deadline.

Backend: no change needed. The requests that would make a stuck upload impossible are in handoffs/OFFLINE_SYNC_BACKEND_HANDOFF.md. The contract this relies on — the resolve mints a missing instance at upload time, the session is stored under it for the athlete, a resend stores nothing twice — is pinned by the live probe tests/live/offline/10-unbound-session-upload.live.test.ts (npm run test:live:auth, backdev only).

A batch being all-or-nothing — one unbindable or rejected session keeping the rest of its training queued — was the gap this left; amendment 9 closes it.

Implementation notes — offline cold start (amendment 8, 2026-10-05)​

Amendment 7 made a training startable without the server; this one makes sure there is something to start after a launch with no connection. Before it, such a launch showed an empty schedule and two empty pickers unless the coach had pressed "Load workouts" earlier that same day.

  • The schedule copies itself. Every schedule load that both requests answered hands its workouts to refreshOfflineDayInBackground (use-offline-day.ts), which runs the existing downloadDayBundle in the background — unless today's copy is younger than 15 minutes and still holds exactly those workouts and athlete × exercise pairs. A failure is logged and leaves the previous copy; an empty schedule clears the copies, so the fallback cannot resurrect a list the server no longer has. "Load workouts" stays as the manual refresh and still reports its own failures.

  • One request per roster. downloadDayBundle used to ask exercise_for_user/workout once for the union of all definitions and all athletes. The route answers — and creates — the full cross product, so that minted an instance for every athlete × every exercise on the schedule. Fine for an occasional button, not for an automatic download: requests are now grouped by roster, where the cross product is exactly what the sessions need.

  • A copy outlives its day. The bundle was readable only on the day it was downloaded and pruned the next morning — a device that was online in the evening came up empty in the gym. pickBundleDateKey now serves today's bundle, else the newest earlier one up to BUNDLE_MAX_AGE_DAYS (7) old; the readers (resolve-user-exercises.ts, use-workout-exercises.ts, the schedule fallback, the sidebar status) go through latestBundleDateKey, and pruneOfflineDaysBefore keeps the bundle still in use.

  • The fallback fills gaps instead of all-or-nothing. The schedule used the copy only when the load returned nothing at all, so a partial failure (one of the two requests) showed half the week as if it were complete. Now whatever failed is filled from the copy, fresh rows winning. When nothing can be shown the list says the schedule could not be loaded rather than "No workouts scheduled this week".

  • Exercise catalogue and roster have a snapshot. Both stores (exercises/store.ts, users/store.ts) were memory-only, so after an offline launch a workout could not even be composed. Each successful load is now snapshotted per account (offline/account-snapshot.ts, keys exercises / users), and an EMPTY store takes its snapshot while the first load is still running — not after it failed, which on a network that swallows requests would be a full deadline later. markCached() on the store status reports that as stale-but-usable (hasData, no lastLoadedAt), which is what the pickers already render a "showing your saved list" hint for.

  • The copy reaches seven days ahead. The schedule on screen ends with the current week, so a copy of just that, made on a Sunday, held nothing scheduled for Monday. The automatic refresh adds the scheduled workouts between the end of the list and seven days from now (one extra request, best-effort); "is the copy current" therefore checks that it includes the list, not that it equals it.

  • Templates and UI translations have a snapshot too. The template library (workouts/store.ts) falls back to the account's last loaded list when the server cannot be reached, so a workout can be started from a template; the UI-string catalogue (ui-text-content/store.ts) applies its last successful load while the first one is still running, so an offline launch keeps the user's language instead of the bundled English baseline.

Still open: media / Lottie — unchanged, see below.

Implementation notes — no silent loss (amendment 9, 2026-10-05)​

Five places where recorded data could be lost, stuck, or put out of reach without the coach being told:

  • A rejected training is split per session (flushUploads). The server validates POST /workout_sessions as a whole, so one stale session — an athlete removed from the coach (403), a deleted exercise (404), an unbindable session — rejected the training of every athlete travelling with it, on every retry. A deterministic rejection of a multi-session batch now replaces it, in one transaction, with one batch per session (same place in the queue, each with its own session's repair data, failure counters restarted), and those are sent in the same drain. The healthy sessions upload; the rejected one stays, counted, like any poison batch. The backend handoff asks for this to become unnecessary.
  • A batch the server keeps failing on no longer blocks the queue. A 5xx is transient and stops the drain — right while the server is down. A payload that trips a server bug (e.g. an unknown catalogue id surfacing as a constraint violation) fails the same way every time, though, and held up everything behind it. After SERVER_FAULT_SKIP_AFTER (3) such failures of the same batch (serverFaults; gateway statuses 502/503/504 never count) a further one skips it instead. It is kept, retried once per drain, and counted as stuck for the indicator.
  • The finish asks before it discards unsaved reps. The atomic finish deletes the station's parked rep buffers with the rest of its recovery state and uploads completed sets only — so reps that were recorded but never saved as a set (typically after a crash recovery, or an exercise left with the rep overlay open) vanished without a word. requestFinish reads unsavedStationReps first and names what would be lost; "Keep training" leaves everything in place.
  • A device that cannot store is no longer silent — or a dead end. The mirror writes are fire-and-forget, so a failing database went unnoticed until the finish could not be queued, and then offered only "retry" (into the same failure) or "discard". The orchestrator now keeps the outcome of the latest station write (isRecoveryStorageFailing), which the training view shows as a warning; and a finish that cannot be queued hands the batch to the server directly (FinishOutcome.sentDirectly) — the fallback amendment 6 left open. Only a confirmed upload counts as safe.
  • A 401 no longer ends a running training. There is no token refresh, so a refused session means sign-in — which needs a connection and an emailed code. AuthGuard now goes through auth/unauthorized-hold.ts: while a TrainingSession is open the logout is postponed, the view says so, and everything recorded stays on the device (a 401 is transient for the queue); the logout runs when the training is finished or discarded, and the queue drains after the same account signs in again.

Also: the pre-start licence re-check (verifyRecordingSlotAvailable) is skipped when the server is known not to answer and otherwise capped at 4 s — it used to hold the Start button for a full request deadline before falling back to the last known weight anyway. And uploads the server keeps refusing read as "can't be sent — retrying" in the sidebar instead of "pending"; that copy had only existed in an unused component.

Implementation notes — a finish you can see (amendment 10, 2026-10-05)​

"Finish training" closed the view and returned to a schedule that looked exactly as before. The upload carries no workout id, so nothing the server returns marks a workout as done, and a training still waiting in the queue was visible only as a count in the sidebar — out of sight where the sidebar is not pinned. A coach had every reason to doubt it was saved, and to record it again.

  • The finish says what happened (use-finish-training.ts): a toast — saved and uploading, saved on this device and uploading once back online, or (the direct-send fallback) saved and uploaded.
  • The schedule marks what was recorded today (offline/finished-workouts.ts, use-finished-workouts.ts): the device notes each finished workout with its session ids, for the day; the list renders it with the card's completed status and "Recorded today", or "Recorded today — upload pending" while any of its sessions is still in the queue. Local on purpose — it is a note of what THIS device did today, reset the next day (a recurring workout keeps its id from week to week).
  • Pending uploads are visible without the sidebar: where the spine is not pinned, the station header's sidebar button carries the count.

Implementation notes — questionnaire answers (amendment 11, 2026-10-06)​

The wellness check-in and the session RPE are drawn by the embedded questionnaire service (questionnaire-service.md), which also stored the answers — from inside its frame, in that frame's localStorage. For answers given without a working connection that meant: a cap of ten entries with the oldest dropped, a drain that only ran while the frame was open for the same athlete, storage in a third-party frame that the OS partitions and may evict, and a check-in silently discarded when the metric catalogue could not be loaded at that moment. A session RPE given after an offline finish was sent before its training and attached to nothing.

  • The app sends the answers (offline/questionnaire-queue.ts, store pendingQuestionnaires, DB_VERSION 7). The answer is stored on the device before anything is sent and removed only by a successful send; a refusal is recorded on the entry and retried, never dropped. It drains on the upload queue's opportunities, after the sessions (use-upload-drain.ts), under the same owner guard, and counts toward the sidebar's pending row and the sign-out / account-switch prompts (UnsyncedOfflineData.questionnaires).
  • Answers, not request bodies. A check-in is stored by metric key; the metric id is resolved when the entry is sent, so one given while the catalogue was unavailable waits instead of being lost. The measurement ids — the endpoint's idempotency keys — are minted once, at enqueue.
  • A session RPE waits for its training. It is held while a finished training is still waiting to upload (trainingUploadPending), and keeps the moment it was given. A batch the server has refused does not hold it back.
  • A coach's rating names its sessions (2026-10-06, backend request 5). Right after a finish the device knows which sessions each athlete recorded; the rating is queued with them (PendingSessionRpe.sessionIDs) and sent with sessionIDs plus the entry's id as measurementID, so it is stored for exactly that training and a replay updates it. The server answers 409 sessions_not_uploaded until those sessions exist; the queue treats that as waiting — not counted as a refusal, not blocking the entries behind it. A rating given without session context (the athlete's own, from the push) carries neither field and is matched by time, as before.
  • Negotiated per frame. The service is deployed on its own schedule, so the host offers delivery: "host" with the auth command and takes over only when the service echoes it on authenticated (questionnaire-delivery.ts, host-auth.ts). An older service keeps sending itself, exactly as before; a newer service in an older app does too.

Verified against the backend by tests/live/offline/11-questionnaire-queue.live.test.ts: both endpoints accept the tracking client's request for a managed athlete, a replayed check-in stores nothing twice, and a held rating reaches its training once that has uploaded.

Still open: the questionnaire itself is a remote page. A device that was offline when the app started cannot load it, so no answer can be given — the check-in then fails open (the workout starts) and the rating is not asked for.

Implementation notes — retrospective drafts (amendment 12, 2026-10-06)​

"Log past workout" was the one place left where entered data existed only in memory: every rep, load and note of the log lived in the fill view's component state until Upload. An OS kill, a reload or a crash before that took the whole hand-typed session.

  • A draft per log (offline/retrospective-drafts.ts, store retrospectiveDrafts, DB_VERSION 9), keyed by the log's own workout id. It holds the workout being logged and what has been entered (per-athlete rows, start date and time).
  • Written while typing (RetrospectiveFillView): 300 ms after the last edit and when the app is backgrounded. Nothing is written for a log nobody has edited — that is just the prescription again.
  • Restored at launch without asking (page.tsx, placeRestoredLogs): each draft reopens in a station that is doing nothing, or in a new one — never in place of a training. A draft whose shape is not recognised (parseRetroDraftState) is ignored rather than half-rendered. A restored log counts as edited, so leaving it asks before discarding.
  • Removed when the upload was queued or sent, and on Discard. A draft counts as work in progress for the sign-out and account-switch prompts (UnsyncedOfflineData.activeTrainings).

Known gap: the draft is deleted after the batch is queued, not in the same transaction. A kill in between restores a log that is already queued, and uploading it again would store the session twice (its set ids are minted at upload). The window is a single write.

Implementation notes — per-session upload outcomes (amendment 13, 2026-10-06)​

The backend answered the offline-sync handoff (handoffs/OFFLINE_SYNC_BACKEND_HANDOFF.md): POST /workout_sessions now returns one outcome per session (created / alreadyPresent / rejected + reason) and, with ?partial=true, stores the valid sessions of a request instead of refusing all of them. The client below works against a backend with and without it; verified on backdev by tests/live/offline/13-per-session-outcomes.live.test.ts.

  • The queue uploads with ?partial=true (postSessionBatch) and reads the list (api/mappers/session-upload-outcomes.ts). This is what makes the opt-in safe: a 2xx no longer means "everything is stored", so the sessions reported rejected — and any the list does not mention — stay on the device, each as its own batch carrying the reason (lastFailure.reason), in the same transaction that removes the stored ones (settleRejectedSessions).
  • No list means everything is stored. A backend that predates the change ignores the parameter and answers a bare 201; the queue then behaves exactly as before, including the split-and-resend of amendment 9 after a 4xx.
  • A fully rejected batch arrives as 422 with the list in the error body and is split from it directly, without sending each session again.
  • Rejected sessions are still retried on later opportunities. The backend suggested not to; the causes it names (access to an athlete, a deleted exercise) can be undone, and nothing else would ever deliver the session.
  • The direct send of a finish that could not be queued (amendment 9) does not count as safe when the server left a session out: nothing could keep it, so the training view stays open.
  • postWorkoutSessions does not opt in — its callers treat a resolved call as "all stored".

Testing on the device (2026-10-05)​

Everything in amendments 7–10 was verified in a browser; what differs on a device — the native HTTP stack, WebView storage — can only be answered there. /debug/selftest runs the same situations on the device with one button, using a switchable fault layer at the transport seam (api/fault-injection.ts, debug builds only), and writes a protocol. See the offline self-test.

Implementation notes — set video upload (deferred outbox)​

Recorded set videos upload through a second, parallel outbox that reuses this ADR's "persist before network, drain on connectivity" model. Videos are large binary and can't ride inside the JSON session payload, so they get their own store and a two-step gate:

  • pendingVideos (IndexedDB store, schema v5) — one entry per completed set with a videoID, keyed by video id and carrying its owning sessionId. The entries are derived from the finished sessions and enqueued by finishAndUpload before any network call, so an offline finish leaves them for the next drain (the trimmed .mp4 already sits on disk — the only copy).
  • video-queue.ts — enqueueVideos / flushVideos / drainVideos. The backend creates the video record from the session POST (the set carries videoID), so a video is only eligible once its sessionId is no longer in pendingUploads (its session has uploaded). Eligible videos then: request a presigned Cloudflare URL (GET /videos/upload_url/{id}), stream the bytes natively (EnodeVideo.uploadVideo), and on a confirmed 200 move the file to the persistent directory (moveVideoToUploaded) and drop the entry. Mirrors iOS ENVideoService.upload.
  • Unlike the session queue (strictly ordered — one failure stops the drain), a failed video doesn't block the others: each is an independent file, so the flush records the attempt and moves on. One exception, added 2026-09-08: a deterministic rejection of the upload-URL request (a 4xx other than 401/408/429, classified by the session queue's isTransientUploadError) drops the outbox entry — no retry can deliver it, and keeping it made the pending indicator warn forever. Live-verified on backdev with a freshly registered Enode Pro (free) account (license.totalVideoStorage: 0, no writeCloudStorage): POST /workout_sessions with a set video → 201 (the session upload is never blocked by its video; the server keeps a pending video record), GET /videos/upload_url/{id} → 403. The local file is kept — the cleanup invariant below is about files, not outbox rows.
  • Cleanup invariant: a local video file is deleted at exactly three points, never otherwise — (1) a confirmed upload (the local copy is dropped after a 200; reviewing an uploaded video re-fetches from the server), (2) the user deletes its set (handleDeleteSet → deleteLocalVideos), (3) the user discards the session (TrainingSession discard + recovered-session discard → deleteLocalVideos(videoIdsInSessions(...))). So a recorded video can never be lost without either a successful upload or an explicit user delete. Finish shares stopAndCleanup with discard but must NOT delete — only the discard call sites do. removeVideoEntries drops the outbox row for the user-initiated cases. Removing an athlete (applyAthleteChange → removeSessionsForUsers) likewise deletes that athlete's sessions' videos, since their sets are dropped.
  • Triggers — the same launch / online / foreground opportunities (useUploadDrain) drain sessions first, then videos, so a now-eligible video goes on the very same connectivity event. The Cloudflare upload bytes never pass through apiRequest (it's JSON-only); the file→URL transfer is a native plugin method (EnodeVideo.uploadVideo), and the one place the upload HTTP contract lives is packages/core/src/video/upload.ts.

Implementation notes — data package type repair (offline finish)​

Every rep's raw sensor stream travels as a data package: the Float32 blob, gzipped and base64-encoded, tagged with the DataPackageType that describes its column layout. The tag is a UUID resolved from a catalogue prefetched at app start (GET /data_package_types).

The tag matters more than it looks, in two escalating ways. The blob carries no type marker of its own, and jump and flywheel share a four-column layout, so the mode cannot be recovered from the bytes (decodeRepData takes it as a parameter for exactly this reason) — an untagged package that lands is unreadable for good, and the read path drops it outright (api/mappers/session-from-dto.ts).

Worse, it does not land at all. The backend decodes dataPackageTypeID as a required uuid, so an explicit null fails the decode of the entire request with a 400 (Swift valueNotFound, not keyNotFound — the key is present, the value is null). Since a batch carries the whole session, ONE untypeable package rejects every set, rep and measurement travelling with it; and a 400 is deterministic, so flushUploads keeps retrying it forever. An untagged package therefore does not cost a blob — it costs the training. (Confirmed in production against the iOS 3.0.1 client; the web mapper writes the same null.)

That collides with A3. The finish maps to the wire shape before queueing, so the tag is resolved at finish time — and an offline finish is precisely the case where the catalogue was never fetched. The queue then replays the stored payload verbatim, so the null would be frozen and shipped once connectivity returns. The same gap opens whenever the startup prefetch failed for any other reason: it is fire-and-forget and never retried within an app run.

The prevention comes first. This catalogue was the only reference store without a cold-start snapshot — metrics, text-content, equipment, exercise-variations, tags, display-bases and feedback-modes all go through loadWithCache, it alone did a bare fetch. It now has one (REFERENCE_KEY.dataPackageTypes), so any device that has loaded it once keeps tagging correctly with no connectivity, and the situation below stops arising for everybody except a fresh install that has never been online.

The repair defers the resolution to the send, which is by definition a moment with connectivity, and covers what prevention cannot — that fresh install, plus every batch queued before either shipped:

  • api/mappers/untagged-packages.ts — two pure functions. untaggedPackageKeys(sessions, payload) runs right after the mapping, while the domain sessions are still in hand, and records dataPackage.id → type KEY for every package that went out untagged. The key is the one piece of information the wire payload does not preserve. retagDataPackages applies the repair at send time against an injected lookup, returning a patched copy so a failed send still retries the untouched original.
  • The key rides beside the payload, never inside it — PendingUpload.packageTypeKeys, optional so batches queued before the field read as "nothing to repair". This keeps the queue's founding invariant intact: the payload stays a pure wire format, immune to model changes.
  • The resolution happens in the injected UploadFn, not in the queue, so upload-queue.ts stays network-free and unit-testable. postSessionBatch (api/sessions.ts) is that function: it loads the catalogue, retags, and POSTs. It throws when the catalogue is unreachable — deliberately, because the queue reads a NetworkError as transient and keeps the batch. A repairable upload is retried rather than shipped unreadable.
  • A package that still cannot be tagged is dropped, not sent. Given the 400 above, uploading it untagged does not preserve the blob — it destroys the session around it. Dropping loses a trajectory that was already unreadable and delivers the measurements, which are the actual record of the training. This is also the rescue path for batches queued before the keys existed: they carry no keys, so everything untagged is dropped and a session that had been stuck in a 400 retry loop finally uploads.
  • The catalogue is only read when the batch has keys worth resolving, so a legacy batch is repaired without touching the network.
  • Recording the keys is isolated from the finish (try/catch in finishAndUpload, like enqueueVideos): it is bookkeeping that makes sensor data readable later, never a precondition for the data being safe. A failure degrades to "no keys recorded", not to a finish the coach cannot close.

Open / deferred questions​

  • Background rep capture. Persistence (amendment 3) makes every rep the JS pipeline processes durable — but while the app is backgrounded, whether raw samples still reach JS is a platform question: iOS keeps native CoreBluetooth alive (bluetooth-central) while the WebView may suspend (bridge events queued or dropped — unverified on device); Android has no foreground service, so JS runs until the cached process is frozen/killed. To measure: mid-set, background for 60 s with the sensor streaming, foreground, inspect what arrived. If capture must be guaranteed: native ring-buffer + replay-on-resume in the BLE plugins (rep detection stays in shared TS) and an Android foreground service.
  • Set-Summary draft durability. With showSetSummary on (default off), opening the summary clears the parked pending-rep buffer while the candidate set exists only in memory — a kill during review loses it. Persist the draft set (or defer the buffer delete to accept/dismiss) if the flag ships on.
  • Set-video privilege/setting gate. iOS gates upload on the writeCloudStorage privilege + an automaticVideoUpload user setting; the web outbox always tries. Since 2026-09-08 the server's 403 on the upload URL drops the entry (see the video outbox notes above), so a licence without cloud storage costs one round trip per video instead of a permanent warning. A pre-flight gate on writeCloudStorage (useHasPrivilege) would also skip the request or the recording affordance; the automaticVideoUpload setting has no client counterpart yet. The never-uploadable local files are only reclaimed by the reconciliation sweep (open item in docs/video-recording.md).
  • Android video upload. Recording + the native EnodeVideo plugin are iOS-only today, so the upload/move methods exist only on iOS. Mirror them in the Android plugin when Android recording ships (the TS outbox is already cross-platform).
  • At-rest encryption (GDPR). IndexedDB is unencrypted; this is personal training data and the entity is EU-based. Device-level encryption is assumed sufficient for now — revisit if a stricter requirement lands.
  • Retention of failed uploads — resolved as policy: never auto-delete an unsendable batch (it is the only copy), but the indicator warns once the oldest batch is > 7 days old or the queue exceeds ~50 MB (uploadQueueHealth). Tune freely.
  • Poison-batch isolation — shipped 2026-07-12 (amendment 4). flushUploads classifies failures (isTransientUploadError): transient (network / timeout / 5xx / 401 / 408 / 429 / a cancelled 310–312 dialog — and any unrecognized shape) stops the drain and retries later, exactly as before; a DETERMINISTIC 4xx rejection is logged, counted on the batch (failedAttempts / lastFailure), and SKIPPED so the healthy batches behind it still upload — no head-of-line blocking. The batch is never deleted and is re-attempted once per drain, so a server-side fix heals it with no client action. Batches rejected ≥ STUCK_AFTER_FAILURES surface as stuckCount in the queue health and get truthful pill copy ("can't be sent — retrying"). The session-upload POST carries its own 240 s deadline (SESSION_UPLOAD_TIMEOUT_MS, api/sessions.ts) — the default 15 s would systematically abort large raw-data batches on slow connections, which presents exactly like a poison batch. finishAndUpload no longer awaits the flush: the batch is durable before it returns; the detached send (sessions, then their now-eligible videos) is exposed as FinishOutcome.flushed for deterministic tests. Open with the backend: idempotency of POST /workout_sessions on client ids (re-send after a lost 2xx), and that cross-batch arrival order carries no meaning (a skipped batch delivers late).
  • Atomic finish + launch reconciliation — shipped 2026-07-16 (amendment 5). Field report: after "Finish training" a coach could still edit the workout (edits were silently dropped — the upload snapshots the sessions at button press), and killing the app right after the view closed re-presented a "resume training" prompt for a workout already on the server (the fire-and-forget discardStation lost the race with the kill; a shell can also outlive its uploaded sessions because the flush deletes rows but not shells). Three changes, each behind a reversible flag:
    1. Atomic finish (ATOMIC_FINISH, orchestrator): a finish with a stationId stages the upload batch AND deletes the station's shell, session rows, and pending-rep buffers in ONE IndexedDB transaction (stagePendingUpload + the stageDelete* helpers), lane-ordered after in-flight mirror writes. At every kill point the DB holds either the full recovery state and no batch, or the batch and no recovery trace — never both, never neither. A failed transaction rolls back completely and the finish reports not-queued (the view stays open with Retry).
    2. Launch reconciliation (RECOVERY_RECONCILE, recoverStations): queue-covered sessions are hidden from the resume prompt (the queue owns them; their rows are deleted by the flush on upload success, never here); a shell with no session rows and no pending reps is a stale finish artifact and is deleted. Sessions are mirrored from training start, so a bare shell cannot be a legitimate crash remnant. This heals databases written before the atomic finish existed.
    3. Finish interaction lock (FINISH_LOCK, TrainingSession): while the finish maps/queues (seconds on Android), a full-station overlay blocks every interaction — set edits, Discard, sheet dismissal — so nothing can mutate state that the upload snapshot no longer contains.
  • Surviving a connection the platform closes — shipped 2026-09-08 (amendment 6). Field report from an iOS coach: every "Finish training" ended in "Something went wrong. Please try again.", forever, with the workout never reaching "uploads pending". The diagnostics report named it exactly — InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing — and the breadcrumbs dated it to the app returning from seven minutes in the background. WebKit force-closes a WebView's IndexedDB connections while iOS holds the app suspended; nothing in the app closes the database itself. getDb() cached the connection as a process-wide singleton with no way back, so from that moment every offline write failed and each retry ran into the same dead handle. The finish was simply the first place the failure was fatal rather than swallowed: the recovery mirrors write fire-and-forget, so the whole session had been failing silently. Two changes:
    1. A self-healing handle (Database.run, db.ts): a lost connection is reopened ONCE and the unit of work re-run. Safe by construction — a closed connection throws at transaction(), before any request reaches a store, so the failed attempt provably wrote nothing. Only InvalidStateError (the closing/closed connection) is retried; NotFoundError and an aborted transaction still surface as themselves. An explicit close() is final, so the account-switch wipe cannot be blocked by a silent reopen.
    2. No cached rejection (getDb(), stores.ts): a failed open forgets the promise instead of replaying its rejection to every later caller, so one transient failure at boot no longer costs the app its offline storage for the rest of its life. Still open: a failure to queue locally is presented as a generic "Something went wrong" with the real cause only in the console, and it leaves the coach with no option other than retry or discard — a direct-to-server fallback for a finish that cannot be queued is not built.
  • Plan B — shipped 2026-06-15 (see "Implementation notes" → "Plan B"). Covers the day's workouts, per-athlete exercise instances, and the global reference catalogues. Since amendment 7 a pair the bundle does not cover starts unbound instead of being blocked. Still open: media/Lottie assets are not yet cached (the lazy useMedia path 404s offline), and exercise-detail charts for an athlete with no prior local history remain blank offline.