[cloud_firestore]: Query snapshot events take ~8x longer to encode on iOS/macOS since the Swift migration (7.2.0), blocking the main thread
メンテナーはふだん 4 日以内に返信
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 35/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 領域
- performance
調査の方向性
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.
索引モデルが issue の本文から書いたものです。
説明
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).
- 主要言語
- Dart
- スター
- 9.3k
- フォーク
- 4.1k
- 平均マージ
- 4日 17時間
- マージ済み PR(30日)
- 49
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
firebase/flutterfire のほかの issue
-
[cloud_functions]: Apple platforms ignore custom domains passed as region対応中かも @ragavendranbala-TSL が今日担当しました。 オープンNeeds Attention platform: ios platform: macos plugin: functions type: bug
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
firebase/flutterfire#19015 · コメント 2 件 ·
メンテナーはふだん 4 日以内に返信
-
Needs Attention platform: android plugin: messaging type: bug
難易度 4/5 3〜5日 初心者へのやさしさ 45/100
firebase/flutterfire#19017 ·
メンテナーはふだん 4 日以内に返信
-
Needs Attention platform: web plugin: crashlytics type: enhancement
難易度 5/5 1週間以上 初心者へのやさしさ 34/100
firebase/flutterfire#19014 · コメント 1 件 ·
メンテナーはふだん 4 日以内に返信
-
[firebase_messaging]: Android getToken() errors lose their cause since firebase-messaging 25.1.0 ("FCM Registration failed!")対応中かも @SelaseKay が 3 日前に担当しました。 オープンNeeds Attention platform: android plugin: messaging reproduced type: bug
難易度 4/5 3〜5日 初心者へのやさしさ 22/100
firebase/flutterfire#18997 · コメント 1 件 ·
メンテナーはふだん 4 日以内に返信
-
[firebase_storage]: Windows: getData() crashes with access violation (use-after-free of StorageReference in ReferenceGetData)対応中かも @SelaseKay が 4 日前に担当しました。 オープンblocked: customer-response platform: windows plugin: storage type: bug type: crash
難易度 4/5 3〜5日 初心者へのやさしさ 35/100
firebase/flutterfire#18994 · コメント 2 件 ·
メンテナーはふだん 4 日以内に返信
firebase/flutterfire の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
Anxcye/anx-reader#1024 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
RevenueCat/purchases-flutter#2048 ·
メンテナーはふだん 1 日以内に返信
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
hajisensai/Fushi#4543 · コメント 3 件 ·
メンテナーはふだん 1 日以内に返信
-
[video_player] _updatePosition sets isCompleted=true after 500ms when duration is Duration.zeroオープン
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 1 日以内に返信
-
fix(backup): decisions.jsonl is exported but never merged on restore対応中かも このイシューにリンクされたプルリクエストがオープン中、またはマージ済みです。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
laugustyniak/augustyniak-capture#477 ·
メンテナーはふだん 1 日以内に返信