[cloud_firestore]: Query snapshot events take ~8x longer to encode on iOS/macOS since the Swift migration (7.2.0), blocking the main thread
Los mantenedores suelen responder en 4 días
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Área
- performance
Línea de trabajo
Start with the two writers the report names: FirebaseFirestoreWriter.writeValue in FirebaseFirestoreWriter.swift and the generated FirestoreMessagesPigeonCodecWriter.writeValue in FirestoreMessages.g.swift. Run the gist's bench.sh to reproduce the 7.1.0 vs 7.2.0 timings before touching anything, and keep the Pigeon deep-equality check so the encoded output stays identical. The map fast path sits in generated code, so decide whether the real fix belongs upstream in Pigeon or in an override outside the generated file; done means timings close to 7.1.0.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Is there an existing issue for this?
- I have searched the existing issues.
Which plugins are affected?
Other
Which platforms are affected?
iOS, macOS
Description
After upgrading cloud_firestore from 7.1.0 to 7.2.0, a snapshots() listener on a collection of more than 10,000 documents makes our iOS app (release build, iPhone 12, iOS 27.2.1) stop responding. It happens on the first load and again each time a document in the collection is written, so the app stays frozen while uploads keep adding documents.
Every query snapshot event carries all documents of the query. QuerySnapshotStreamHandler.emit passes the event to FlutterEventSink on the main queue, and FlutterEventChannel encodes it there synchronously with FirestoreMessagesPigeonCodecWriter. Because the platform and UI threads are merged by default on iOS, the Dart isolate is blocked for the same time.
The encoding itself is what got slower. For the same payload, the Swift codec in 7.2.0 takes about 8x as long as the Objective-C codec in 7.1.0:
| Documents | 7.1.0 (Objective-C) | 7.2.0 (Swift) |
|---|---|---|
| 1,000 | 34 ms | 290 ms |
| 5,000 | 169 ms | 1,425 ms |
| 10,000 | 340 ms | 2,839 ms |
| 20,000 | 675 ms | 5,678 ms |
Apple M2 Pro, macOS 27.2.1, release engine, built with optimizations. Each document has 26 or 27 fields. See the reproduction below.
The first event of a listener also carries every document a second time in documentChanges (as noted in #18878), so it takes about twice as long as the table shows.
Expected: encoding a snapshot costs about the same as in 7.1.0.
Actual: about 8x the time, all of it on the main thread.
Where the time goes
Every string and number in every document goes through FirestoreMessagesPigeonCodecWriter.writeValue, which tries 24 as? casts before calling super, and then through FirebaseFirestoreWriter.writeValue, which tries 13 more before it reaches the NSNumber branch or super.writeValue. In 7.1.0 these were isKindOfClass: checks. In Swift, casting an NSString or NSNumber held in Any to a Swift struct, enum, or bridged type (DocumentChangeType, InternalDocumentSnapshot, Date, Data, [Any], [AnyHashable: Any], ...) goes through the runtime's dynamic cast path with a protocol conformance lookup each time. On top of that, each document's data ([String?: Any?]) is copied into a new [AnyHashable: Any] by the as? [AnyHashable: Any] cast before it is written.
A sample of the benchmark while encoding is dominated by tryCast, swift_conformsToProtocolMaybeInstantiateSuperclasses, conformance cache lookups, and findBridgeWitness (see the log output below).
Reproducing the issue
In an app
- Listen to
FirebaseFirestore.instance.collection('items').snapshots()where the collection holds about 10,000 documents with about 25 string, number, and boolean fields each. - Run a release build on an iOS device.
- Write one document to the collection. The UI stops responding while the event is encoded, about 2.8 s per event going by the Mac numbers above.
Codec benchmark (no Firebase project needed)
https://gist.github.com/prsh0525/58d316dae866ce9c786301af0d01686c
Run bash bench.sh. It copies the codec sources of 7.1.0 and 7.2.0 unmodified from the pub cache and replaces only the Firebase SDK types they reference with empty classes. It links them against the FlutterMacOS release engine and builds with -O / -O2. It then encodes the same InternalQuerySnapshot (N documents, each with 13 strings, 4 or 5 integers, 2 doubles, and 7 booleans, plus one document change) with the codec that the plugin gives every FlutterEventChannel.
Firebase Core version
5.2.0
Flutter Version
3.50.1
Relevant Log Output
# sample <pid> 4 while the 7.2.0 benchmark encodes, sorted by top of stack
tryCast(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, ...) (in libswiftCore.dylib) 301
__swift::__runtime::llvm::hashing::detail::hash_short(char const*, unsigned long, unsigned long long) (in libswiftCore.dylib) 225
swift_conformsToProtocolMaybeInstantiateSuperclasses(...) (in libswiftCore.dylib) 174
swift::ConcurrentReadableHashMap<(anonymous namespace)::ConformanceCacheEntry, swift::LazyMutex>::find<...>(...) (in libswiftCore.dylib) 108
object_getClass (in libobjc.A.dylib) 88
swift_dynamicCast (in libswiftCore.dylib) 80
_dyld_find_protocol_conformance_on_disk (in libdyld.dylib) 56
objc_opt_isKindOfClass (in libobjc.A.dylib) 56
findBridgeWitness(swift::TargetMetadata<swift::InProcess> const*) (in libswiftCore.dylib) 36
tryCastFromClassToObjCBridgeable(...) (in libswiftCore.dylib) 25
Flutter dependencies
Expand Flutter dependencies snippet
cloud_firestore: 7.2.0
cloud_firestore_platform_interface: 8.2.0
firebase_core: 5.2.0
# Firebase iOS SDK 13.2.0 through Swift Package Manager
Additional context and comments
Checking the common leaf types first in both writers, and writing the Pigeon [String?: Any?] maps directly instead of converting them to [AnyHashable: Any], recovers most of it:
| Documents | 7.1.0 (Objective-C) | 7.2.0 (Swift) | 7.2.0 + patch below |
|---|---|---|---|
| 1,000 | 34 ms | 290 ms | 64 ms |
| 10,000 | 340 ms | 2,839 ms | 634 ms |
The patched codec's output decodes to a message equal to the unpatched one (checked with the Pigeon-generated deep equality, which ignores map key order). It is still about 1.9x of 7.1.0, so the remaining collection casts may be worth a look as well. The second hunk is in generated code, so a real fix probably belongs in the Pigeon output or in an override outside the generated file.
Patch against cloud_firestore 7.2.0
--- a/FirebaseFirestoreWriter.swift
+++ b/FirebaseFirestoreWriter.swift
@@ -22,6 +22,35 @@
class FirebaseFirestoreWriter: FlutterStandardWriter {
override func writeValue(_ value: Any) {
+ if value is NSString || value is String {
+ super.writeValue(value)
+ return
+ }
+ if let number = value as? NSNumber {
+ if number == NSNumber(value: Double.infinity) {
+ writeByte(FirestoreDataType.infinity.rawValue)
+ return
+ }
+ if number == NSNumber(value: -Double.infinity) {
+ writeByte(FirestoreDataType.negativeInfinity.rawValue)
+ return
+ }
+ if number.description.lowercased() == "nan" {
+ writeByte(FirestoreDataType.nan.rawValue)
+ return
+ }
+ super.writeValue(value)
+ return
+ }
+ if let map = value as? [String?: Any?] {
+ writeByte(kStandardFieldMap)
+ writeSize(UInt32(map.count))
+ for (key, item) in map {
+ writeValue(key as Any)
+ writeValue(item as Any)
+ }
+ return
+ }
if let date = value as? Date {
writeByte(FirestoreDataType.dateTime.rawValue)
var ms = Int64(date.timeIntervalSince1970 * 1000.0)
--- a/FirestoreMessages.g.swift
+++ b/FirestoreMessages.g.swift
@@ -1129,6 +1129,10 @@
class FirestoreMessagesPigeonCodecWriter: FirebaseFirestoreWriter {
override func writeValue(_ value: Any) {
+ if value is NSString || value is NSNumber || value is String {
+ super.writeValue(value)
+ return
+ }
if let value = value as? DocumentChangeType {
super.writeByte(129)
super.writeValue(value.rawValue)
Related: #18607 (the Swift migration), #18878 (reuses converted documents in query snapshots; the codec still writes each changed document twice).
- Lenguaje dominante
- Dart
- Estrellas
- 9.3k
- Forks
- 4.1k
- Merge medio
- 4 d 17 h
- PR fusionados (30 d)
- 49
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de firebase/flutterfire
-
[cloud_functions]: Apple platforms ignore custom domains passed as regionPosiblemente ocupada @ragavendranbala-TSL la tomó hoy. AbiertoNeeds Attention platform: ios platform: macos plugin: functions type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
firebase/flutterfire#19015 · 2 comentarios ·
Los mantenedores suelen responder en 4 días
-
Needs Attention platform: android plugin: messaging type: bug
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
firebase/flutterfire#19017 ·
Los mantenedores suelen responder en 4 días
-
Needs Attention platform: web plugin: crashlytics type: enhancement
Dificultad 5/5 Más de una semana Aptitud para principiantes 34/100
firebase/flutterfire#19014 · 1 comentario ·
Los mantenedores suelen responder en 4 días
-
[firebase_messaging]: Android getToken() errors lose their cause since firebase-messaging 25.1.0 ("FCM Registration failed!")Posiblemente ocupada @SelaseKay la tomó hace 3 días. AbiertoNeeds Attention platform: android plugin: messaging reproduced type: bug
Dificultad 4/5 3-5 días Aptitud para principiantes 22/100
firebase/flutterfire#18997 · 1 comentario ·
Los mantenedores suelen responder en 4 días
-
[firebase_storage]: Windows: getData() crashes with access violation (use-after-free of StorageReference in ReferenceGetData)Posiblemente ocupada @SelaseKay la tomó hace 4 días. Abiertoblocked: customer-response platform: windows plugin: storage type: bug type: crash
Dificultad 4/5 3-5 días Aptitud para principiantes 35/100
firebase/flutterfire#18994 · 2 comentarios ·
Los mantenedores suelen responder en 4 días
Todos los issues de firebase/flutterfire
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Anxcye/anx-reader#1024 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
RevenueCat/purchases-flutter#2048 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
hajisensai/Fushi#4543 · 3 comentarios ·
Los mantenedores suelen responder en 1 día
-
[video_player] _updatePosition sets isCompleted=true after 500ms when duration is Duration.zeroAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
-
fix(backup): decisions.jsonl is exported but never merged on restorePosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
laugustyniak/augustyniak-capture#477 ·
Los mantenedores suelen responder en 1 día