Skip to content

fix(cloud_firestore): chunk large Android query snapshots - #19005

Open
SelaseKay wants to merge 6 commits into
mainfrom
fix/firestore-chunk-android-query-snapshots
Open

SelaseKay wants to merge 6 commits into
mainfrom
fix/firestore-chunk-android-query-snapshots

Conversation

@SelaseKay

@SelaseKay SelaseKay commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Supersedes #18601 (preserving @ben-milanko's original commits in branch history because the source fork Railway-Engineering-Solutions/flutterfire is organization-owned and rejects maintainer pushes), merged with current main (including Gradle 9 / built-in Kotlin and Pigeon 30.0.4) and addressing review feedback.

Previously, QuerySnapshotsStreamHandler on Android converted an entire Firestore QuerySnapshot into one InternalQuerySnapshot and emitted it through a single EventChannel envelope (StandardMethodCodec.encodeSuccessEnvelope). On large query results, holding the converted Pigeon structures and the single encoded buffer in memory at once can exhaust the Android Java heap (OutOfMemoryError in StandardMessageCodec.writeValue).

This PR incrementally converts and chunks Android query snapshots across bounded EventChannel frames (start, documents, documentChanges, end) and reassembles them atomically in cloud_firestore_platform_interface:

  • Bounded envelope target (512 KiB): QuerySnapshotChunker packs documents and document changes up to 512 KiB per encoded StandardMethodCodec envelope. If a single Firestore document (bounded by Firestore's 1 MiB document size limit) exceeds 512 KiB on its own, it is emitted as a single-item chunk so delivery cannot stall.
  • Zero-allocation sizing: PigeonCodecSizer counts exact encoded bytes through a CountingByteArrayOutputStream against PigeonCodec.INSTANCE.writeValue instead of allocating temporary ByteBuffers per item/chunk.
  • Backwards-compatible opt-in negotiation: MethodChannelQuery passes {'firestoreQuerySnapshotChunked': true} as the EventChannel listen argument. QuerySnapshotsStreamHandler only emits chunked frames when that flag is present, falling back to legacy single-message InternalQuerySnapshot emission for older cloud_firestore_platform_interface versions (and Dart continues to accept legacy unchunked InternalQuerySnapshot events for iOS/macOS/Windows and older Android builds).
  • Stream lifecycle, snapshotsInSync ordering, and error handling:
    • Introduces SnapshotDeliveryExecutor wrapping each Firestore instance's single-thread delivery executor so chunked query snapshots non-blockingly hold their FIFO turn across start -> documents -> documentChanges -> end frames, preventing SnapshotsInSyncStreamHandler (and subsequent snapshots) from overtaking an in-flight chunked snapshot while releasing the turn on completion, cancel, re-listen, or error.
    • Uses a monotonic listener generation counter and explicit aborted state in QuerySnapshotsStreamHandler so stale queued chunks/registrations cannot leak across cancel/re-listen, native Firestore errors drain already-accepted snapshots before emitting the error, and internal sink/conversion failures suppress subsequent queued successes.
    • On protocol corruption in Dart (MethodChannelQuery), resets the assembler, emits the StateError once, and closes the transformed sink so the native listener cancels instead of flooding cascading errors for trailing chunks.
  • Tests & CI:
    • Runs :cloud_firestore:testDebugUnitTest from packages/cloud_firestore/cloud_firestore/example/android in .github/workflows/android_unit_tests.yaml without adding cloud_firestore to tests/.
    • Removes production test hooks (emitSnapshotForTesting) by driving QuerySnapshotsStreamHandlerTest through onListen/onCancel with testOptions { unitTests.returnDefaultValues = true }.
    • Adds Android unit tests (QuerySnapshotChunkProtocolTest, QuerySnapshotChunkerTest, QuerySnapshotsStreamHandlerTest, SnapshotDeliveryExecutorTest), Dart unit tests (query_snapshot_chunk_assembler_test.dart, method_channel_firestore_test.dart), and an Android/cross-platform e2e test in query_e2e.dart exercising >512 KiB snapshot delivery.

Related Issues

Supersedes #18601.

Checklist

Before you create this PR confirm that it meets all requirements listed below by checking the relevant checkboxes ([x]).
This will ensure a smooth and quick review process. Updating the pubspec.yaml and changelogs is not required.

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • My PR includes unit or integration tests for all changed/updated/fixed behaviors (See Contributor Guide).
  • All existing and new tests are passing.
  • I updated/added relevant documentation (doc comments with ///).
  • The analyzer (melos run analyze) does not report any problems on my PR.
  • I read and followed the Flutter Style Guide.
  • I signed the CLA.
  • I am willing to follow-up on review comments in a timely manner.

Breaking Change

Does your PR require plugin users to manually update their apps to accommodate your change?

  • Yes, this is a breaking change.
  • No, this is not a breaking change.

ben-milanko and others added 4 commits August 21, 2026 19:56
…pshot-transport-chunks-upstream

# Conflicts:
#	.github/workflows/android_unit_tests.yaml
#	tests/pubspec.yaml
…fecycle

Resolve Android unit-task and dependency updates without losing new upstream coverage. Scope chunk assembly to each query listener generation; cover cancellation, pending re-listens, complete event delivery, and native stream errors.

Co-authored-by: ben-milanko <20643387+ben-milanko@users.noreply.github.com>
…ssions

Resolve the two Dart formatting conflicts without changing upstream semantics or the chunk assembly and listener-cancellation coverage. Retain the current SDK floor and upstream changes.

Prepared on Ben Milanko's behalf by Alder, his AI assistant, with Codex assistance.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces chunked transport for Firestore query snapshots to prevent exceeding platform channel message size limits when transmitting large datasets. It implements a chunking protocol on the Android side and a reassembly mechanism on the Dart side, backed by comprehensive unit and integration tests. The review feedback suggests refactoring the Dart assembler's add method to comply with style guide rules (keeping functions under 20 lines and avoiding the ! operator), securing array bounds checks in PigeonCodecSizer.java against integer overflow, and caching the main thread executor in QuerySnapshotsStreamHandler.java to reduce garbage collection overhead.

Comment on lines +86 to +192
InternalQuerySnapshot? add(Object? event) {
if (event is InternalQuerySnapshot) {
if (_active != null) {
throw StateError(
'Received unchunked query snapshot while snapshot '
'${_active!.snapshotId} was incomplete.',
);
}
return event;
}

if (event is! Map<Object?, Object?> || event[_chunkMarkerKey] != true) {
throw StateError('Unexpected query snapshot event: ${event.runtimeType}');
}

final snapshotId = _requireInt(event, _snapshotIdKey);
final kind = _requireInt(event, _kindKey);

switch (kind) {
case _startKind:
if (_active != null) {
throw StateError(
'Received query snapshot $snapshotId start before snapshot '
'${_active!.snapshotId} completed.',
);
}
final metadata = event[_payloadKey];
if (metadata is! InternalSnapshotMetadata) {
throw StateError(
'Missing or invalid metadata for query snapshot $snapshotId.',
);
}
final documentCount = _requireNonNegativeInt(event, _documentCountKey);
final documentChangeCount = _requireNonNegativeInt(
event,
_documentChangeCountKey,
);
_active = _PendingQuerySnapshot(
snapshotId: snapshotId,
metadata: metadata,
expectedDocumentCount: documentCount,
expectedDocumentChangeCount: documentChangeCount,
);
return null;

case _documentsKind:
final active = _requireActiveSnapshot(snapshotId, 'document chunk');
final items = _requireList<InternalDocumentSnapshot>(
event,
_payloadKey,
'InternalDocumentSnapshot',
);
if (active.documents.length + items.length >
active.expectedDocumentCount) {
throw StateError(
'Query snapshot $snapshotId received more documents than '
'expected (${active.documents.length + items.length} > '
'${active.expectedDocumentCount}).',
);
}
active.documents.addAll(items);
return null;

case _documentChangesKind:
final active = _requireActiveSnapshot(
snapshotId,
'document change chunk',
);
final items = _requireList<InternalDocumentChange>(
event,
_payloadKey,
'InternalDocumentChange',
);
if (active.documentChanges.length + items.length >
active.expectedDocumentChangeCount) {
throw StateError(
'Query snapshot $snapshotId received more document changes than '
'expected (${active.documentChanges.length + items.length} > '
'${active.expectedDocumentChangeCount}).',
);
}
active.documentChanges.addAll(items);
return null;

case _endKind:
final active = _requireActiveSnapshot(snapshotId, 'end marker');
_active = null;
if (active.documents.length != active.expectedDocumentCount ||
active.documentChanges.length !=
active.expectedDocumentChangeCount) {
throw StateError(
'Query snapshot $snapshotId ended incomplete: expected '
'${active.expectedDocumentCount} documents and '
'${active.expectedDocumentChangeCount} document changes, got '
'${active.documents.length} and ${active.documentChanges.length}.',
);
}
return InternalQuerySnapshot(
documents: active.documents,
documentChanges: active.documentChanges,
metadata: active.metadata,
);

default:
throw StateError('Unknown query snapshot chunk kind: $kind');
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To adhere to the repository style guide rule regarding function conciseness (functions should be under 20 lines) and to avoid the use of the ! operator by leveraging Dart's flow analysis on local variables, we can refactor the add method. By extracting each switch case into its own private helper method, we keep the code highly modular, readable, and clean.

  InternalQuerySnapshot? add(Object? event) {
    if (event is InternalQuerySnapshot) {
      final active = _active;
      if (active != null) {
        throw StateError(
          'Received unchunked query snapshot while snapshot '
          '${active.snapshotId} was incomplete.',
        );
      }
      return event;
    }

    if (event is! Map<Object?, Object?> || event[_chunkMarkerKey] != true) {
      throw StateError('Unexpected query snapshot event: ${event.runtimeType}');
    }

    final snapshotId = _requireInt(event, _snapshotIdKey);
    final kind = _requireInt(event, _kindKey);

    switch (kind) {
      case _startKind:
        _handleStart(snapshotId, event);
        return null;
      case _documentsKind:
        _handleDocuments(snapshotId, event);
        return null;
      case _documentChangesKind:
        _handleDocumentChanges(snapshotId, event);
        return null;
      case _endKind:
        return _handleEnd(snapshotId);
      default:
        throw StateError('Unknown query snapshot chunk kind: $kind');
    }
  }

  void _handleStart(int snapshotId, Map<Object?, Object?> event) {
    final active = _active;
    if (active != null) {
      throw StateError(
        'Received query snapshot $snapshotId start before snapshot '
        '${active.snapshotId} completed.',
      );
    }
    final metadata = event[_payloadKey];
    if (metadata is! InternalSnapshotMetadata) {
      throw StateError(
        'Missing or invalid metadata for query snapshot $snapshotId.',
      );
    }
    _active = _PendingQuerySnapshot(
      snapshotId: snapshotId,
      metadata: metadata,
      expectedDocumentCount: _requireNonNegativeInt(event, _documentCountKey),
      expectedDocumentChangeCount: _requireNonNegativeInt(
        event,
        _documentChangeCountKey,
      ),
    );
  }

  void _handleDocuments(int snapshotId, Map<Object?, Object?> event) {
    final active = _requireActiveSnapshot(snapshotId, 'document chunk');
    final items = _requireList<InternalDocumentSnapshot>(
      event,
      _payloadKey,
      'InternalDocumentSnapshot',
    );
    if (active.documents.length + items.length >
        active.expectedDocumentCount) {
      throw StateError(
        'Query snapshot $snapshotId received more documents than '
        'expected (${active.documents.length + items.length} > '
        '${active.expectedDocumentCount}).',
      );
    }
    active.documents.addAll(items);
  }

  void _handleDocumentChanges(int snapshotId, Map<Object?, Object?> event) {
    final active = _requireActiveSnapshot(
      snapshotId,
      'document change chunk',
    );
    final items = _requireList<InternalDocumentChange>(
      event,
      _payloadKey,
      'InternalDocumentChange',
    );
    if (active.documentChanges.length + items.length >
        active.expectedDocumentChangeCount) {
      throw StateError(
        'Query snapshot $snapshotId received more document changes than '
        'expected (${active.documentChanges.length + items.length} > '
        '${active.expectedDocumentChangeCount}).',
      );
    }
    active.documentChanges.addAll(items);
  }

  InternalQuerySnapshot _handleEnd(int snapshotId) {
    final active = _requireActiveSnapshot(snapshotId, 'end marker');
    _active = null;
    if (active.documents.length != active.expectedDocumentCount ||
        active.documentChanges.length !=
            active.expectedDocumentChangeCount) {
      throw StateError(
        'Query snapshot $snapshotId ended incomplete: expected '
        '${active.expectedDocumentCount} documents and '
        '${active.expectedDocumentChangeCount} document changes, got '
        '${active.documents.length} and ${active.documentChanges.length}.',
      );
    }
    return InternalQuerySnapshot(
      documents: active.documents,
      documentChanges: active.documentChanges,
      metadata: active.metadata,
    );
  }
References
  1. Functions should be under 20 lines to maintain conciseness and readability. (link)
  2. Avoid using the ! operator; instead, use flow analysis (e.g., if (x != null)) on local variables. (link)

Comment on lines +44 to +49
public void write(byte[] b, int off, int len) {
if (len < 0 || off < 0 || off > b.length || off + len > b.length) {
throw new IndexOutOfBoundsException();
}
totalBytes += len;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent potential integer overflow when checking array bounds in write(byte[] b, int off, int len), it is safer to use subtraction instead of addition. For example, off + len > b.length can overflow if off and len are large, whereas len > b.length - off is safe from overflow.

Suggested change
public void write(byte[] b, int off, int len) {
if (len < 0 || off < 0 || off > b.length || off + len > b.length) {
throw new IndexOutOfBoundsException();
}
totalBytes += len;
}
@Override
public void write(byte[] b, int off, int len) {
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
totalBytes += len;
}

Comment on lines +370 to +373
Handler mainHandler = new Handler(Looper.getMainLooper());
return mainHandler::post;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

low

Instead of creating a new Handler and a new lambda instance every time mainThreadExecutor() is called, we can cache a single static final Executor instance. This improves efficiency and reduces garbage collection overhead.

  private static final Executor MAIN_THREAD_EXECUTOR = new Executor() {
    private final Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void execute(Runnable command) {
      handler.post(command);
    }
  };

  private static Executor mainThreadExecutor() {
    return MAIN_THREAD_EXECUTOR;
  }

@SelaseKay
SelaseKay force-pushed the fix/firestore-chunk-android-query-snapshots branch from 9d9cc20 to 941160f Compare November 24, 2026 11:39

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants