From d3e90d379091682625f83ec72315bc1687a37ca0 Mon Sep 17 00:00:00 2001 From: Ronald Dumeloo <47387042+KafuiDumeloo@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:34:12 -0500 Subject: [PATCH 1/2] fix(firestore,android): deliver query snapshots in order Since #18390, Android query listeners convert snapshots on the shared cachedThreadPool. The SDK submits one executor task per snapshot, so two snapshots of one query can convert at the same time and the older can reach Dart after the newer. If it arrives last, snapshots() keeps showing stale data until the query next changes. Give each listener its own sequential executor on the same pool. Conversion stays off the main thread, one listener can't hold up another, and it matches the serial queue each iOS listener already has. Fixes #18904 --- AUTHORS | 1 + .../FlutterFirebaseFirestorePlugin.java | 5 +- .../example/integration_test/query_e2e.dart | 115 ++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 0c0e6b091146..54a7b9184cb2 100644 --- a/AUTHORS +++ b/AUTHORS @@ -71,3 +71,4 @@ kfurue Max Wojczuk Julian Pscheid Artem Shevchenko +Ronald Dumeloo <47387042+KafuiDumeloo@users.noreply.github.com> diff --git a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java index e162e6530a52..c74ad9d5ce91 100644 --- a/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java +++ b/packages/cloud_firestore/cloud_firestore/android/src/main/java/io/flutter/plugins/firebase/firestore/FlutterFirebaseFirestorePlugin.java @@ -17,6 +17,7 @@ import com.google.android.gms.tasks.TaskCompletionSource; import com.google.android.gms.tasks.Tasks; import com.google.firebase.FirebaseApp; +import com.google.firebase.concurrent.FirebaseExecutors; import com.google.firebase.firestore.AggregateField; import com.google.firebase.firestore.AggregateQuery; import com.google.firebase.firestore.AggregateQuerySnapshot; @@ -1019,7 +1020,9 @@ public void querySnapshot( PigeonParser.parsePigeonServerTimestampBehavior( options.getServerTimestampBehavior()), PigeonParser.parseListenSource(source), - cachedThreadPool))); + // One queue per listener: on the shared pool, two snapshots of one query + // could convert at the same time and reach Dart out of order. + FirebaseExecutors.newSequentialExecutor(cachedThreadPool)))); } @Override diff --git a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart index 491b68bc2dc2..37721c67beef 100644 --- a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart +++ b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart @@ -3,6 +3,7 @@ // BSD-style license that can be found in the LICENSE file. import 'dart:async'; +import 'dart:convert'; import 'dart:math'; import 'package:collection/collection.dart' show IterableExtension; @@ -11,6 +12,37 @@ import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; + +/// Sets the document at the given URL to 1, 2, 3 and so on up to the given +/// count, each write awaited before the next. Run with [compute], so that +/// handling the listener's snapshots on the main isolate doesn't slow the +/// writes down. +Future _sendCounterUpdates((Uri, int) arguments) async { + final (Uri url, int updateCount) = arguments; + final http.Client client = http.Client(); + try { + for (int value = 1; value <= updateCount; value++) { + final http.Response response = await client.patch( + url, + headers: const { + 'Authorization': 'Bearer owner', + 'Content-Type': 'application/json', + }, + body: jsonEncode({ + 'fields': { + 'value': {'integerValue': '$value'}, + }, + }), + ); + if (response.statusCode != 200) { + throw StateError('Update $value failed: ${response.statusCode}'); + } + } + } finally { + client.close(); + } +} void runQueryTests() { group('$Query', () { @@ -516,6 +548,89 @@ void runQueryTests() { skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows, ); + test( + 'delivers snapshots of server updates in order', + () async { + final String path = (await initializeTest( + 'snapshot-delivery-order', + )).path; + // Its own instance, because saving every snapshot to the persistent + // cache the rest of the suite uses spaces them too far apart to overlap. + final FirebaseApp app = await Firebase.initializeApp( + name: 'snapshot-delivery-order', + options: firestore.app.options, + ); + final FirebaseFirestore instance = + FirebaseFirestore.instanceFor(app: app) + ..settings = const Settings(persistenceEnabled: false) + ..useFirestoreEmulator('localhost', 8080); + addTearDown(() async { + await instance.terminate(); + await app.delete(); + }); + final CollectionReference> collection = instance + .collection(path); + final DocumentReference> counter = collection + .doc('counter'); + const int updateCount = 300; + final String payload = List.filled(400, 'x').join(); + + final WriteBatch batch = instance.batch(); + for (int index = 0; index < 20; index++) { + batch.set(collection.doc('doc-$index'), { + 'index': index, + 'payload': payload, + }); + } + batch.set(counter, {'value': 0}); + await batch.commit(); + + final Completer initialSnapshot = Completer(); + final Completer lastUpdate = Completer(); + final List outOfOrder = []; + int newest = -1; + final StreamSubscription>> + subscription = collection.snapshots().listen((snapshot) { + final int value = snapshot.docs + .firstWhere((doc) => doc.id == 'counter') + .get('value'); + if (value < newest) { + outOfOrder.add('$value after $newest'); + } + newest = max(newest, value); + if (!initialSnapshot.isCompleted) { + initialSnapshot.complete(); + } + if (value == updateCount && !lastUpdate.isCompleted) { + lastUpdate.complete(); + } + }); + addTearDown(subscription.cancel); + await initialSnapshot.future.timeout(const Duration(seconds: 30)); + + // Each write is awaited, so the value only ever goes up. REST writes + // reach the listener over the watch stream in quick succession, which + // is when consecutive snapshots of one query can overlap. + await compute(_sendCounterUpdates, ( + Uri.parse( + 'http://10.0.2.2:8080/v1/projects/' + '${firestore.app.options.projectId}/databases/(default)/documents/' + '${counter.path}', + ), + updateCount, + )); + + await lastUpdate.future.timeout(const Duration(minutes: 4)); + // An older snapshot can still arrive after the newest one, which is + // what would leave a listener showing stale data. + await Future.delayed(const Duration(seconds: 2)); + expect(outOfOrder, isEmpty); + }, + timeout: const Timeout.factor(10), + // The URL uses the Android emulator's address for the host machine. + skip: kIsWeb || defaultTargetPlatform != TargetPlatform.android, + ); + test('listeners throws a [FirebaseException] with Query', () async { CollectionReference> collection = firestore .collection('not-allowed'); From 9a98bb2bb5309d7449dbd26bec718007e9acdd8b Mon Sep 17 00:00:00 2001 From: Ronald Dumeloo <47387042+KafuiDumeloo@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:22:04 -0500 Subject: [PATCH 2/2] test(firestore): simplify the snapshot order test --- .../example/integration_test/query_e2e.dart | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart index 37721c67beef..0424a218125b 100644 --- a/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart +++ b/packages/cloud_firestore/cloud_firestore/example/integration_test/query_e2e.dart @@ -20,18 +20,18 @@ import 'package:http/http.dart' as http; /// writes down. Future _sendCounterUpdates((Uri, int) arguments) async { final (Uri url, int updateCount) = arguments; - final http.Client client = http.Client(); + final client = http.Client(); try { for (int value = 1; value <= updateCount; value++) { - final http.Response response = await client.patch( + final response = await client.patch( url, - headers: const { + headers: const { 'Authorization': 'Bearer owner', 'Content-Type': 'application/json', }, - body: jsonEncode({ - 'fields': { - 'value': {'integerValue': '$value'}, + body: jsonEncode({ + 'fields': { + 'value': {'integerValue': '$value'}, }, }), ); @@ -573,7 +573,7 @@ void runQueryTests() { final DocumentReference> counter = collection .doc('counter'); const int updateCount = 300; - final String payload = List.filled(400, 'x').join(); + final String payload = 'x' * 400; final WriteBatch batch = instance.batch(); for (int index = 0; index < 20; index++) {