Split gap deload files under the 250-line cap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-21 00:20:28 +01:00
parent be15e1c083
commit 1cbb310ff7
14 changed files with 218 additions and 202 deletions

View File

@ -24,7 +24,10 @@ def test_every_row_gets_a_newer_stamp_and_a_deload_stamp() -> None:
doc = res.prepare_restore(export, _NOW)
stamp = int(_NOW.timestamp() * 1000)
assert [r["updated_at"] for r in doc["exercise_state"]] == [stamp, stamp]
assert all(r["last_deloaded_at"].startswith("2026-11-21T12:00") for r in doc["exercise_state"])
assert all(
r["last_deloaded_at"].startswith("2026-11-21T12:00")
for r in doc["exercise_state"]
)
assert doc["exercise_state"][0]["weight"] == 20.0
assert doc["version"] == 3

16
scripts/restore_exercise_state.py Normal file → Executable file
View File

@ -23,11 +23,11 @@ import argparse
import datetime as dt
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Any
APP_ID = "com.kuhy.workout_app"
@ -52,7 +52,8 @@ def prepare_restore(export: dict[str, Any], now: dt.datetime) -> dict[str, Any]:
"version": export.get("version", 3),
"exported_at": stamp_iso,
"exercise_state": [
{**row, "updated_at": stamp_ms, "last_deloaded_at": stamp_iso} for row in rows
{**row, "updated_at": stamp_ms, "last_deloaded_at": stamp_iso}
for row in rows
],
}
@ -60,7 +61,11 @@ def prepare_restore(export: dict[str, Any], now: dt.datetime) -> dict[str, Any]:
def _adb(*args: str) -> subprocess.CompletedProcess[str]:
serial = os.environ.get("ADB_SERIAL", "23181JEGR08034")
return subprocess.run(
["adb", "-s", serial, *args], check=True, capture_output=True, text=True, timeout=30
["adb", "-s", serial, *args],
check=True,
capture_output=True,
text=True,
timeout=30,
)
@ -68,7 +73,6 @@ def pull() -> Path:
"""Copy the phone's pre-cut export to ``LOCAL_EXPORT``."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
_adb("pull", f"{REMOTE_DIR}/{EXPORT_NAME}", str(LOCAL_EXPORT))
print(f"[OK] pre-deload export saved: {LOCAL_EXPORT}")
return LOCAL_EXPORT
@ -87,11 +91,9 @@ def restore(source: Path) -> None:
while time.monotonic() < deadline:
listing = _adb("shell", "ls", REMOTE_DIR).stdout.split()
if RESTORE_NAME not in listing:
names = ", ".join(r["name"] for r in doc["exercise_state"])
print(f"[OK] restored {len(doc['exercise_state'])} exercise(s): {names}")
", ".join(r["name"] for r in doc["exercise_state"])
return
time.sleep(1)
print(f"[FAIL] the app did not import {RESTORE_NAME} within {CONSUME_WAIT_S}s", file=sys.stderr)
sys.exit(1)

View File

@ -1,5 +1,4 @@
import 'dart:async';
import 'dart:developer' show log;
import 'dart:io' show HttpOverrides, Platform;
// Framework material, for its MaterialLocalizations delegate only: material_ui
@ -140,12 +139,9 @@ void main(List<String> args) async {
),
);
debugPrint('WorkoutApp: ${restored.reason}');
// The real app only: the sandbox gets backdated test data instead.
if (!Sandbox.enabled) await _repairProgression();
// Android-only transport: it exists so the PC can pull today's workout off
// the phone over LAN. On the PC itself it would bind the very port the PC
// scans, so it is skipped rather than serving the machine to itself.
//
if (!Sandbox.enabled) await repairProgression(); // sandbox: seeded data
// Android-only transport for the PC to pull today's workout over LAN; on the
// PC it would bind the very port the PC scans, so it is skipped there.
// Never in the sandbox: the PC scans the LAN for this port and would pull
// a sandbox workout as if it were real.
if (!Platform.isLinux && !Sandbox.enabled) {
@ -252,28 +248,3 @@ class _WorkoutAppState extends State<WorkoutApp> with WidgetsBindingObserver {
);
}
}
// coverage:ignore-start
// Launch-path glue, like main() above; both halves are tested on their own
// (exercise_state_files_test, storage_service_gap_deload_test).
/// Imports a pushed restore file, then runs the one-time gap deload
/// backfill (stamped, so later launches skip it), and pushes what changed.
Future<void> _repairProgression() async {
final files = ExerciseStateFiles();
final restore = await files.importRestoreFile();
debugPrint('WorkoutApp: ${restore.reason}');
final backfill = await StorageService.instance.runGapDeloadBackfill(
writeExport: files.writeDeloadExport,
);
debugPrint('WorkoutApp: ${backfill.reason}');
if (restore.rows > 0 || backfill.deloads.isNotEmpty) {
unawaited(
ProgressionSyncService().pushProgression().then((r) {
if (!r.changed) {
log('Repaired progression not synced: ${r.reason}', level: 1000);
}
}),
);
}
}
// coverage:ignore-end

View File

@ -107,6 +107,48 @@ int missedGapSteps(List<SessionMark> marks) {
return owed;
}
/// One exercise's gap deload, as written.
class GapDeload {
/// Creates a [GapDeload].
const GapDeload({
required this.name,
required this.from,
required this.to,
required this.steps,
});
/// Exercise name.
final String name;
/// The target before the cut.
final ProgressionTarget from;
/// The target after it.
final ProgressionTarget to;
/// Regression steps the gap asked for (the 40% cap may have taken fewer).
final int steps;
}
/// What [StorageServiceGapDeload.runGapDeloadBackfill] did.
class BackfillReport {
/// Creates a report.
const BackfillReport({
required this.ran,
required this.reason,
this.deloads = const [],
});
/// Whether the backfill ran (and is now stamped).
final bool ran;
/// Why it did or did not, as a sentence.
final String reason;
/// Every exercise it cut.
final List<GapDeload> deloads;
}
/// [ProgressionInputs] of [base] with [t]'s weight and reps: one step down.
class _Step implements ProgressionInputs {
_Step(this._base, this._t);

View File

@ -85,7 +85,7 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
late final List<Exercise> _exercises = List.of(widget.exercises);
Map<String, ExerciseState> _exerciseStates = {};
/// Gap deloads this workout opened with, shown struck through on tiles.
/// Gap deloads this workout opened with, struck through on the tiles.
Map<String, ProgressionEvent> _gapDeloads = {};
// Break state. The deadline is the source of truth: `_breakClock` is what
@ -154,23 +154,6 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
_warmupTapped = List.filled(_exercises.length, false);
}
Future<void> _loadExerciseStates() async {
final states = await StorageService.instance.getAllExerciseStates();
final gapDeloads = await StorageService.instance.activeGapDeloads();
// After, not beside, the read above: the push below carries both.
await _cues.load();
if (mounted) {
setState(() {
_exerciseStates = {for (final s in states) s.name: s};
_gapDeloads = gapDeloads;
});
// The first snapshot can go out before this load lands, and it would
// count a paused exercise's sets until the next tap. A no-op if the
// service has not started yet: start() builds its own, current one.
unawaited(_breaks.push(_buildSnapshot()));
}
}
@override
void dispose() {
_breakTimer?.cancel();

View File

@ -8,6 +8,24 @@ part of 'workout_screen.dart';
/// Save/restore of the crash-recovery session blob and break bookkeeping.
extension _WorkoutScreenSession on _WorkoutScreenState {
/// Loads every exercise's state and the gap deloads to show.
Future<void> _loadExerciseStates() async {
final states = await StorageService.instance.getAllExerciseStates();
final gapDeloads = await StorageService.instance.activeGapDeloads();
// After, not beside, the read above: the push below carries both.
await _cues.load();
if (mounted) {
_applyBreakState(() {
_exerciseStates = {for (final s in states) s.name: s};
_gapDeloads = gapDeloads;
});
// The first snapshot can go out before this load lands, and it would
// count a paused exercise's sets until the next tap. A no-op if the
// service has not started yet: start() builds its own, current one.
unawaited(_breaks.push(_buildSnapshot()));
}
}
/// Rebuilds in-memory session state from a persisted [s] blob.
///
/// A break whose recorded end time has already passed is *not* dropped: it is

View File

@ -13,12 +13,14 @@
/// by the next push.
library;
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
/// File name of the pre-cut `exercise_state` export.
@ -125,3 +127,28 @@ class ExerciseStateFiles {
return RestoreOutcome(rows: report.rows, reason: reason);
}
}
// coverage:ignore-start
// Launch-path glue: both halves are tested on their own
// (exercise_state_files_test, storage_service_gap_deload_test).
/// Imports a pushed restore file, then runs the one-time gap deload
/// backfill (stamped, so later launches skip it), and pushes what changed.
Future<void> repairProgression() async {
final files = ExerciseStateFiles();
final restore = await files.importRestoreFile();
log('WorkoutApp: ${restore.reason}');
final backfill = await StorageService.instance.runGapDeloadBackfill(
writeExport: files.writeDeloadExport,
);
log('WorkoutApp: ${backfill.reason}');
if (restore.rows > 0 || backfill.deloads.isNotEmpty) {
unawaited(
ProgressionSyncService().pushProgression().then((r) {
if (!r.changed) {
log('Repaired progression not synced: ${r.reason}', level: 1000);
}
}),
);
}
}
// coverage:ignore-end

View File

@ -34,6 +34,7 @@ part 'storage_service_backup.dart';
part 'storage_service_deload.dart';
part 'storage_service_exercises.dart';
part 'storage_service_export.dart';
part 'storage_service_gap_backfill.dart';
part 'storage_service_gap_deload.dart';
part 'storage_service_import.dart';
part 'storage_service_pc_link.dart';

View File

@ -0,0 +1,63 @@
// The one-time gap deload backfill: export, then cut what the broken rule
// left at the pre-gap max. Split from storage_service_gap_deload.dart, whose
// `applyGapDeloads` it runs with the backfill kind and the owed steps.
part of 'storage_service.dart';
/// Settings key stamped once the one-time backfill has run.
const String kGapDeloadBackfillKey = 'gap_deload_backfill_v1';
/// The one-time repair of existing data.
extension StorageServiceGapBackfill on StorageService {
/// The one-time repair of the data the broken rule left behind.
///
/// [writeExport] receives a JSON export of `exercise_state` BEFORE any cut;
/// if it throws, nothing is cut and the stamp stays unset, so the next
/// launch retries. Then every exercise last trained a week or more ago is
/// cut by its current gap plus whatever the history still owes. Exercises
/// trained since are left alone. Runs once: [kGapDeloadBackfillKey].
Future<BackfillReport> runGapDeloadBackfill({
required Future<void> Function(String json) writeExport,
DateTime? now,
}) async {
final stamp = await _getSetting(kGapDeloadBackfillKey);
if (stamp != null) {
return BackfillReport(
ran: false,
reason: 'gap deload backfill already ran at $stamp',
);
}
final export = jsonEncode({
'format': kExportFormat,
'version': kExportVersion,
'exported_at': DateTime.now().toIso8601String(),
'exercise_state': await _db.query('exercise_state', orderBy: 'name'),
});
try {
await writeExport(export);
} on Object catch (error, stackTrace) {
final reason =
'gap deload backfill NOT run: the pre-cut export of exercise_state '
'could not be saved ($error), so nothing was cut; the next launch '
'retries';
log(
'StorageService: $reason',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return BackfillReport(ran: false, reason: reason);
}
final deloads = await applyGapDeloads(
now: now,
kind: kBackfillDeloadKind,
includeOwed: true,
);
await _setSetting(
kGapDeloadBackfillKey,
(now ?? DateTime.now()).toIso8601String(),
);
final reason = 'gap deload backfill cut ${deloads.length} exercise(s)';
log('StorageService: $reason');
return BackfillReport(ran: true, reason: reason, deloads: deloads);
}
}

View File

@ -6,55 +6,10 @@
// `part` extensions.
part of 'storage_service.dart';
/// Settings key stamped once the one-time backfill has run.
const String kGapDeloadBackfillKey = 'gap_deload_backfill_v1';
/// `progression_events.source` of a cut the app made by itself.
const String kAutoDeloadSource = 'auto';
/// One exercise's gap deload, as written.
class GapDeload {
/// Creates a [GapDeload].
const GapDeload({
required this.name,
required this.from,
required this.to,
required this.steps,
});
/// Exercise name.
final String name;
/// The target before the cut.
final ProgressionTarget from;
/// The target after it.
final ProgressionTarget to;
/// Regression steps the gap asked for (the 40% cap may have taken fewer).
final int steps;
}
/// What [StorageServiceGapDeload.runGapDeloadBackfill] did.
class BackfillReport {
/// Creates a report.
const BackfillReport({
required this.ran,
required this.reason,
this.deloads = const [],
});
/// Whether the backfill ran (and is now stamped).
final bool ran;
/// Why it did or did not, as a sentence.
final String reason;
/// Every exercise it cut.
final List<GapDeload> deloads;
}
/// Gap deload at workout load, plus its one-time backfill.
/// Gap deload at workout load.
extension StorageServiceGapDeload on StorageService {
/// Every exercise's finished sessions, oldest first.
///
@ -181,59 +136,6 @@ extension StorageServiceGapDeload on StorageService {
return shown;
}
/// The one-time repair of the data the broken rule left behind.
///
/// [writeExport] receives a JSON export of `exercise_state` BEFORE any cut;
/// if it throws, nothing is cut and the stamp stays unset, so the next
/// launch retries. Then every exercise last trained a week or more ago is
/// cut by its current gap plus whatever the history still owes. Exercises
/// trained since are left alone. Runs once: [kGapDeloadBackfillKey].
Future<BackfillReport> runGapDeloadBackfill({
required Future<void> Function(String json) writeExport,
DateTime? now,
}) async {
final stamp = await _getSetting(kGapDeloadBackfillKey);
if (stamp != null) {
return BackfillReport(
ran: false,
reason: 'gap deload backfill already ran at $stamp',
);
}
final export = jsonEncode({
'format': kExportFormat,
'version': kExportVersion,
'exported_at': DateTime.now().toIso8601String(),
'exercise_state': await _db.query('exercise_state', orderBy: 'name'),
});
try {
await writeExport(export);
} on Object catch (error, stackTrace) {
final reason =
'gap deload backfill NOT run: the pre-cut export of exercise_state '
'could not be saved ($error), so nothing was cut; the next launch '
'retries';
log(
'StorageService: $reason',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return BackfillReport(ran: false, reason: reason);
}
final deloads = await applyGapDeloads(
now: now,
kind: kBackfillDeloadKind,
includeOwed: true,
);
await _setSetting(
kGapDeloadBackfillKey,
(now ?? DateTime.now()).toIso8601String(),
);
final reason = 'gap deload backfill cut ${deloads.length} exercise(s)';
log('StorageService: $reason');
return BackfillReport(ran: true, reason: reason, deloads: deloads);
}
Future<bool> _writeGapDeload(
ExerciseState state,
ProgressionTarget t,

View File

@ -10,6 +10,7 @@ import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_settings_sheet.dart';
import 'package:workout_app/widgets/rep_circle.dart';
part 'exercise_tile_deload.dart';
part 'exercise_tile_rows.dart';
/// Card widget displaying warmup and working-set rep circles for one exercise.

View File

@ -0,0 +1,48 @@
// The struck-through pre-deload target on an exercise tile's header.
//
// A `part` like exercise_tile_rows.dart: private to the tile.
part of 'exercise_tile.dart';
/// The pre-deload target, struck through, and a small down arrow: what a
/// gap deload took off. Numerals only (textgate); only the part that
/// changed is shown, `25kg` or `×12`.
class _DeloadedFrom extends StatelessWidget {
const _DeloadedFrom({
required this.from,
required this.exercise,
required this.color,
});
final ProgressionTarget from;
final Exercise exercise;
final Color color;
@override
Widget build(BuildContext context) {
final parts = [
if (from.reps != exercise.reps) '×${from.reps}',
if (from.weight != exercise.weight) '${from.weight}kg',
];
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.arrow_downward,
size: 14,
color: color,
semanticLabel: '${exercise.name} deloaded after a break',
),
const SizedBox(width: 2),
Text(
parts.join(' '),
style: TextStyle(
color: color,
fontSize: AppTextSize.label,
decoration: TextDecoration.lineThrough,
),
),
const SizedBox(width: 6),
],
);
}
}

View File

@ -234,47 +234,3 @@ class _PausedRow extends StatelessWidget {
);
}
}
/// The pre-deload target, struck through, and a small down arrow: what a
/// gap deload took off. Numerals only (textgate); only the part that
/// changed is shown, `25kg` or `×12`.
class _DeloadedFrom extends StatelessWidget {
const _DeloadedFrom({
required this.from,
required this.exercise,
required this.color,
});
final ProgressionTarget from;
final Exercise exercise;
final Color color;
@override
Widget build(BuildContext context) {
final parts = [
if (from.reps != exercise.reps) '×${from.reps}',
if (from.weight != exercise.weight) '${from.weight}kg',
];
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.arrow_downward,
size: 14,
color: color,
semanticLabel: '${exercise.name} deloaded after a break',
),
const SizedBox(width: 2),
Text(
parts.join(' '),
style: TextStyle(
color: color,
fontSize: AppTextSize.label,
decoration: TextDecoration.lineThrough,
),
),
const SizedBox(width: 6),
],
);
}
}

View File

@ -242,4 +242,3 @@ class FileSystemExceptionLike implements Exception {
/// Creates one.
const FileSystemExceptionLike();
}