@davoodmehraban89 / LifeMate / commits / e5e161d
Fork 0

LifeMate — Personal, Family & Learning Companion

fix: retain uncertain local writes across Android engine recreation

Codex committed Oct 8, 2026 at 06:20 UTC e5e161d013915e43edc26356d52cbd06ba83c91f
9 files changed +307 -15
apps/lifemate/android/app/build.gradle.kts
+7
@@ -20,6 +20,7 @@ android {
20 // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
21 applicationId = if (localTestBuild) "com.example.lifemate.localtest" else "com.example.lifemate"
22 manifestPlaceholders["applicationLabel"] = if (localTestBuild) "آرام (محلی)" else "LifeMate"
23 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
24 // You can update the following values to match your application needs.
25 // For more information, see: https://flutter.dev/to/review-gradle-config.
26 minSdk = flutter.minSdkVersion
@@ -41,6 +42,12 @@ android {
42 }
43 }
44
45 +dependencies {
46 + androidTestImplementation("androidx.test:runner:1.7.0")
47 + androidTestImplementation("androidx.test:core:1.7.0")
48 + androidTestImplementation("androidx.test.ext:junit:1.3.0")
49 +}
50 +
51 kotlin {
52 compilerOptions {
53 jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
apps/lifemate/android/app/src/androidTest/kotlin/com/example/lifemate/LocalWriteGuardActivityTest.kt new
+65
@@ -0,0 +1,65 @@
1 +package com.example.lifemate
2 +
3 +import androidx.test.core.app.ActivityScenario
4 +import androidx.test.ext.junit.runners.AndroidJUnit4
5 +import io.flutter.embedding.android.FlutterActivity
6 +import io.flutter.embedding.engine.FlutterEngine
7 +import java.util.UUID
8 +import org.junit.Assert.assertFalse
9 +import org.junit.Assert.assertNotNull
10 +import org.junit.Assert.assertNotSame
11 +import org.junit.Assert.assertNull
12 +import org.junit.Assert.assertTrue
13 +import org.junit.Test
14 +import org.junit.runner.RunWith
15 +
16 +@RunWith(AndroidJUnit4::class)
17 +class LocalWriteGuardActivityTest {
18 + private fun engine(activity: MainActivity): FlutterEngine {
19 + // Observe embedding lifetime without adding a production test hook.
20 + val getter = FlutterActivity::class.java.getDeclaredMethod("getFlutterEngine")
21 + getter.isAccessible = true
22 + return getter.invoke(activity) as FlutterEngine
23 + }
24 +
25 + @Test
26 + fun pendingNativeWriteSurvivesActivityAndEngineRecreation() {
27 + assertFalse(LocalWriteGuard.getBlocked())
28 + val token = LocalWriteGuard.beginWrite()
29 + assertNotNull(token)
30 + try {
31 + ActivityScenario.launch(MainActivity::class.java).use { scenario ->
32 + lateinit var firstActivity: MainActivity
33 + lateinit var firstEngine: FlutterEngine
34 + var firstEngineDestroyed = false
35 + scenario.onActivity { activity ->
36 + firstActivity = activity
37 + firstEngine = engine(activity)
38 + firstEngine.addEngineLifecycleListener(object : FlutterEngine.EngineLifecycleListener {
39 + override fun onPreEngineRestart() {}
40 + override fun onEngineWillDestroy() {
41 + firstEngineDestroyed = true
42 + }
43 + })
44 + assertTrue(activity.shouldDestroyEngineWithHost())
45 + assertTrue(LocalWriteGuard.getBlocked())
46 + }
47 + scenario.recreate()
48 + scenario.onActivity { activity ->
49 + assertNotSame(firstActivity, activity)
50 + assertTrue(firstActivity.isDestroyed)
51 + assertTrue(firstEngineDestroyed)
52 + assertNotSame(firstEngine, engine(activity))
53 + assertTrue(LocalWriteGuard.getBlocked())
54 + assertNull(LocalWriteGuard.beginWrite())
55 + assertFalse(LocalWriteGuard.completeWrite(UUID.randomUUID().toString()))
56 + assertTrue(LocalWriteGuard.getBlocked())
57 + }
58 + }
59 + } finally {
60 + // This test owns only a synthetic marker, not any DataStore I/O.
61 + assertTrue(LocalWriteGuard.completeWrite(requireNotNull(token)))
62 + }
63 + assertFalse(LocalWriteGuard.getBlocked())
64 + }
65 +}
apps/lifemate/android/app/src/main/kotlin/com/example/lifemate/LocalWriteGuard.kt new
+26
@@ -0,0 +1,26 @@
1 +package com.example.lifemate
2 +
3 +import java.util.UUID
4 +
5 +/** Pending local write ownership lives for the whole Android process. */
6 +object LocalWriteGuard {
7 + private var pendingToken: String? = null
8 +
9 + @Synchronized
10 + fun getBlocked(): Boolean = pendingToken != null
11 +
12 + @Synchronized
13 + fun beginWrite(): String? {
14 + if (pendingToken != null) return null
15 + val token = UUID.randomUUID().toString()
16 + pendingToken = token
17 + return token
18 + }
19 +
20 + @Synchronized
21 + fun completeWrite(token: String): Boolean {
22 + if (pendingToken == null || pendingToken != token) return false
23 + pendingToken = null
24 + return true
25 + }
26 +}
apps/lifemate/android/app/src/main/kotlin/com/example/lifemate/MainActivity.kt
+30 -1
@@ -1,5 +1,34 @@
1 package com.example.lifemate
2
3 import io.flutter.embedding.android.FlutterActivity
4 +import io.flutter.embedding.engine.FlutterEngine
5 +import io.flutter.plugin.common.MethodChannel
6
5 -class MainActivity : FlutterActivity()
7 +class MainActivity : FlutterActivity() {
8 + override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
9 + super.configureFlutterEngine(flutterEngine)
10 + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_write_guard")
11 + .setMethodCallHandler { call, result ->
12 + when (call.method) {
13 + "getBlocked" -> result.success(LocalWriteGuard.getBlocked())
14 + "beginWrite" -> {
15 + val token = LocalWriteGuard.beginWrite()
16 + if (token == null) {
17 + result.error("local_storage_restart_required", null, null)
18 + } else {
19 + result.success(token)
20 + }
21 + }
22 + "completeWrite" -> {
23 + val token = call.arguments as? String
24 + if (token != null && LocalWriteGuard.completeWrite(token)) {
25 + result.success(true)
26 + } else {
27 + result.error("local_storage_restart_required", null, null)
28 + }
29 + }
30 + else -> result.notImplemented()
31 + }
32 + }
33 + }
34 +}
apps/lifemate/lib/local_data_store.dart
+31 -9
@@ -5,14 +5,29 @@ import 'dart:math';
5 import 'package:shared_preferences/shared_preferences.dart';
6
7 import 'api.dart';
8 +import 'local_write_guard.dart';
9
10 /// One local runtime session: shared by all production stores in this isolate.
10 -/// A failed native write leaves the session unavailable until a real app restart.
11 +/// Native pending-write state also survives replacement of this Dart session.
12 class LocalDataSession {
13 + final _guard = const LocalWriteGuard();
14 bool _uncertain = false;
15 // All instances share the writer lock: read/modify/write cannot lose a record.
16 Future<void>? _tail;
17
18 + Future<void> _ensureAvailable() async {
19 + if (!_uncertain) {
20 + try {
21 + _uncertain = await _guard.getBlocked();
22 + } catch (_) {
23 + _uncertain = true;
24 + }
25 + }
26 + if (_uncertain) {
27 + throw const ApiException(500, 'local_storage_restart_required');
28 + }
29 + }
30 +
31 Future<T> _run<T>(Future<T> Function() operation) {
32 final previous = _tail;
33 final release = Completer<void>();
@@ -20,9 +35,7 @@ class LocalDataSession {
35 Future<T> run() async {
36 if (previous != null) await previous;
37 try {
23 - if (_uncertain) {
24 - throw const ApiException(500, 'local_storage_restart_required');
25 - }
38 + await _ensureAvailable();
39 return await operation();
40 } finally {
41 // Don't retain a completed future and its caller's async zone forever.
@@ -138,12 +151,17 @@ class LocalDataStore {
151 }
152 }
153
141 - static Future<String?> _raw(SharedPreferencesAsync prefs) async {
154 + static Future<String?> _raw(
155 + SharedPreferencesAsync prefs, LocalDataSession session) async {
156 + final String? raw;
157 try {
143 - return await prefs.getString(key);
158 + raw = await prefs.getString(key);
159 } catch (_) {
160 throw const ApiException(500, 'local_storage_failed');
161 }
162 + // Another engine may begin/publish a native write while this read awaits.
163 + await session._ensureAvailable();
164 + return raw;
165 }
166
167 Future<void> _write(
@@ -154,7 +172,11 @@ class LocalDataStore {
172 throw const ApiException(500, 'local_storage_failed');
173 }
174 try {
175 + // Ownership is native and is granted before any DataStore write is sent.
176 + // Only this opaque token can clear the marker after confirmed success.
177 + final token = await session._guard.beginWrite();
178 await prefs.setString(key, raw);
179 + await session._guard.completeWrite(token);
180 } catch (_) {
181 // Even DataStore may have published a native cache before a rename error.
182 // Prevent later reads/writes from treating that uncertain value as durable.
@@ -166,7 +188,7 @@ class LocalDataStore {
188 static Future<Map<String, dynamic>?> readSavedProfile() =>
189 _processSession._run(() async {
190 final prefs = await _preferences();
169 - final raw = await _raw(prefs);
191 + final raw = await _raw(prefs, _processSession);
192 if (raw == null) return null;
193 return _copy(_decode(raw)['profile'] as Map<String, dynamic>);
194 });
@@ -196,7 +218,7 @@ class LocalDataStore {
218
219 Future<Map<String, dynamic>> read() => _locked(() async {
220 final prefs = await _preferences();
199 - final raw = await _raw(prefs);
221 + final raw = await _raw(prefs, session);
222 final missing = raw == null;
223 final data = await _load(raw);
224 if (missing) await _write(prefs, data);
@@ -206,7 +228,7 @@ class LocalDataStore {
228 Future<T> mutate<T>(T Function(Map<String, dynamic> data) change) =>
229 _locked(() async {
230 final prefs = await _preferences();
209 - final data = await _load(await _raw(prefs));
231 + final data = await _load(await _raw(prefs, session));
232 final result = change(data);
233 await _write(prefs, data);
234 return result;
apps/lifemate/lib/local_write_guard.dart new
+35
@@ -0,0 +1,35 @@
1 +import 'package:flutter/foundation.dart';
2 +import 'package:flutter/services.dart';
3 +
4 +/// Android process lifetime protection, independent of a Flutter engine/isolate.
5 +/// An unconfirmed write can only be recovered by killing the Android process.
6 +final class LocalWriteGuard {
7 + const LocalWriteGuard();
8 +
9 + static const _channel = MethodChannel('lifeguide/local_write_guard');
10 + bool get _native =>
11 + !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
12 +
13 + Future<bool> getBlocked() async {
14 + if (!_native) return false;
15 + // A missing/invalid native response must never grant access to cached data.
16 + return await _channel.invokeMethod<bool>('getBlocked') ?? true;
17 + }
18 +
19 + Future<String?> beginWrite() async {
20 + if (!_native) return null;
21 + final token = await _channel.invokeMethod<String>('beginWrite');
22 + if (token == null || token.isEmpty) {
23 + throw StateError('Native local write guard did not grant ownership');
24 + }
25 + return token;
26 + }
27 +
28 + Future<void> completeWrite(String? token) async {
29 + if (!_native) return;
30 + if (token == null ||
31 + await _channel.invokeMethod<bool>('completeWrite', token) != true) {
32 + throw StateError('Native local write guard did not confirm completion');
33 + }
34 + }
35 +}
apps/lifemate/test/local_persistence_test.dart
+56
@@ -19,6 +19,19 @@ final class FailedWrites extends InMemorySharedPreferencesAsync {
19 }
20 }
21
22 +final class NativeWriteDuringRead extends InMemorySharedPreferencesAsync {
23 + NativeWriteDuringRead(super.data, this.guard) : super.withData();
24 + final MockNativeLocalWriteGuard guard;
25 +
26 + @override
27 + Future<String?> getString(
28 + String key, SharedPreferencesOptions options) async {
29 + final raw = await super.getString(key, options);
30 + guard.beginWrite();
31 + return raw;
32 + }
33 +}
34 +
35 class FailedNativeCommit extends InMemorySharedPreferencesStore {
36 FailedNativeCommit(super.data) : super.withData();
37 @override
@@ -196,6 +209,16 @@ void main() {
209 final uncertain = jsonDecode(
210 (await SharedPreferencesAsync().getString(LocalDataStore.key))!) as Map;
211 expect((uncertain['items'] as List).first['title'], 'دوم');
212 + // Flutter engine recreation replaces Dart state, but retains native caches.
213 + session = LocalDataSession();
214 + await expectLater(
215 + open().listPlanItems(),
216 + throwsA(isA<ApiException>()
217 + .having((e) => e.code, 'code', 'local_storage_restart_required')));
218 + await expectLater(
219 + open().updatePlanItem(item['id'] as String, {'title': 'سوم'}),
220 + throwsA(isA<ApiException>()
221 + .having((e) => e.code, 'code', 'local_storage_restart_required')));
222 resetLocalPreferences({
223 LocalDataStore.key: raw
224 }); // simulate native process restart + disk read
@@ -220,6 +243,39 @@ void main() {
243 expect((await open().listPlanItems()).single['title'], 'اول');
244 });
245
246 + test('a native write beginning during a read blocks the returned snapshot',
247 + () async {
248 + await open().createPlanItem({'kind': 'task', 'title': 'ثبت‌شده'});
249 + final raw = (await SharedPreferencesAsync().getString(LocalDataStore.key))!;
250 + final guard = resetNativeLocalWriteGuard();
251 + SharedPreferencesAsyncPlatform.instance =
252 + NativeWriteDuringRead({LocalDataStore.key: raw}, guard);
253 + await expectLater(
254 + open().listPlanItems(),
255 + throwsA(isA<ApiException>()
256 + .having((e) => e.code, 'code', 'local_storage_restart_required')));
257 + });
258 +
259 + test('oversized mutation does not start a native write or replace saved data',
260 + () async {
261 + final item = await open().createPlanItem({'kind': 'task', 'title': 'اول'});
262 + final guard = resetNativeLocalWriteGuard();
263 + await expectLater(
264 + open().store.mutate((data) {
265 + data['items'] = List.generate(
266 + 200,
267 + (index) => {
268 + ...item,
269 + 'id': 'synthetic-capacity-item-$index',
270 + 'notes': 'x' * 6000,
271 + });
272 + }),
273 + throwsA(isA<ApiException>()
274 + .having((e) => e.code, 'code', 'local_storage_failed')));
275 + expect(guard.blocked, isFalse);
276 + expect((await open().listPlanItems()).single['title'], 'اول');
277 + });
278 +
279 test('unimplemented server features cannot fabricate success', () async {
280 expect(open().accessToken, isNull);
281 expect(
apps/lifemate/test/local_persistence_ui_test.dart
+16 -5
@@ -13,6 +13,7 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc
13 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
15 import 'app_test.dart' show FakeApi;
16 +import 'local_test_preferences.dart' show resetNativeLocalWriteGuard;
17
18 // This simulates the preferences plugin boundary, not Android process restart.
19 final class _ControlledWrites extends InMemorySharedPreferencesAsync {
@@ -49,6 +50,16 @@ Future<Map<String, dynamic>> _nativeSnapshot() async =>
50 jsonDecode((await SharedPreferencesAsync().getString(LocalDataStore.key))!)
51 as Map<String, dynamic>;
52
53 +Future<LocalOnlyApi> _restartProcessMock() async {
54 + // This plugin mock fails before publishing, so its snapshot is confirmed disk.
55 + // Replace both native process state and the preferences adapter explicitly.
56 + final raw = await SharedPreferencesAsync().getString(LocalDataStore.key);
57 + resetNativeLocalWriteGuard();
58 + SharedPreferencesAsyncPlatform.instance =
59 + _ControlledWrites({if (raw != null) LocalDataStore.key: raw});
60 + return _open(session: LocalDataSession());
61 +}
62 +
63 Future<void> _expectRestartRequired(Future<Object?> operation) async {
64 await expectLater(
65 operation,
@@ -116,6 +127,7 @@ void _localWidgetTest(String name, Future<void> Function(WidgetTester) body) {
127
128 void main() {
129 setUp(() {
130 + resetNativeLocalWriteGuard();
131 _testSession = LocalDataSession();
132 SharedPreferences.setMockInitialValues({});
133 SharedPreferencesAsyncPlatform.instance = _ControlledWrites({});
@@ -250,8 +262,7 @@ void main() {
262 expect((await _nativeSnapshot())['items'], isEmpty);
263 await _expectRestartRequired(api.listPlanItems());
264
253 - // A new coordinator represents a full process restart in this plugin mock.
254 - final restarted = _open(session: LocalDataSession());
265 + final restarted = await _restartProcessMock();
266 expect(await restarted.listPlanItems(), isEmpty);
267 await _planner(tester, restarted);
268 await _createForm(tester);
@@ -317,7 +328,7 @@ void main() {
328 expect(find.text('تمرین ریاضی'), findsOneWidget);
329 await _expectRestartRequired(api.listPlanItems());
330
320 - final restarted = _open(session: LocalDataSession());
331 + final restarted = await _restartProcessMock();
332 expect((await restarted.listPlanItems()).single['status'], 'planned');
333 await tester.pumpWidget(MaterialApp(
334 key: UniqueKey(),
@@ -360,7 +371,7 @@ void main() {
371 expect(find.text(_restartMessage), findsOneWidget);
372 await _expectRestartRequired(api.listPlanItems());
373
363 - final restarted = _open(session: LocalDataSession());
374 + final restarted = await _restartProcessMock();
375 expect((await restarted.listPlanItems()).single['starts_at'],
376 start.toUtc().toIso8601String());
377 await _planner(tester, restarted);
@@ -498,7 +509,7 @@ void main() {
509 expect(
510 (await _nativeSnapshot())['profile']['display_name'], 'آرام مهرآیین');
511
501 - final restarted = _open(session: LocalDataSession());
512 + final restarted = await _restartProcessMock();
513 expect((await restarted.getProfile())['display_name'], 'آرام مهرآیین');
514 });
515
apps/lifemate/test/local_test_preferences.dart
+41
@@ -1,9 +1,50 @@
1 +import 'package:flutter/services.dart';
2 +import 'package:flutter_test/flutter_test.dart';
3 import 'package:shared_preferences/shared_preferences.dart';
4 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
5 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
6
7 +/// Represents one native Android process, independent of Dart session instances.
8 +final class MockNativeLocalWriteGuard {
9 + String? _pending;
10 + int _sequence = 0;
11 +
12 + bool get blocked => _pending != null;
13 +
14 + String beginWrite() {
15 + if (blocked) {
16 + throw PlatformException(code: 'local_storage_restart_required');
17 + }
18 + return _pending = 'mock-owned-token-${++_sequence}';
19 + }
20 +
21 + bool completeWrite(String? token) {
22 + if (token == null || token != _pending) return false;
23 + _pending = null;
24 + return true;
25 + }
26 +
27 + Future<Object?> handle(MethodCall call) async => switch (call.method) {
28 + 'getBlocked' => blocked,
29 + 'beginWrite' => beginWrite(),
30 + 'completeWrite' => completeWrite(call.arguments as String?),
31 + _ => throw MissingPluginException(),
32 + };
33 +}
34 +
35 +/// Only tests can simulate killing the native process; the app has no reset API.
36 +MockNativeLocalWriteGuard resetNativeLocalWriteGuard() {
37 + TestWidgetsFlutterBinding.ensureInitialized();
38 + final native = MockNativeLocalWriteGuard();
39 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
40 + .setMockMethodCallHandler(
41 + const MethodChannel('lifeguide/local_write_guard'), native.handle);
42 + return native;
43 +}
44 +
45 /// Unit/widget plugin substitutes only. Real Android integration never calls this.
46 void resetLocalPreferences([Map<String, Object> values = const {}]) {
47 + resetNativeLocalWriteGuard();
48 SharedPreferences.setMockInitialValues(
49 values); // legacy profile/production cache
50 SharedPreferencesAsyncPlatform.instance =