Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): discover and sync Firestore subcollections (#86024)

posthog[bot]bf82c5fb0819
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
index 3bfe6b361447..327d1e4e4ce5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
@@ -6,6 +6,8 @@ from collections.abc import Iterator
from typing import Any, Optional
from urllib.parse import quote, urlparse
+from django.core.cache import cache
+
import jwt
import requests
import structlog
@@ -13,6 +15,7 @@ from structlog.types import FilteringBoundLogger
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -28,16 +31,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.s
FIRESTORE_API_ROOT,
FIRESTORE_COLLECTION_IDS_PAGE_SIZE,
FIRESTORE_CREATE_TIME_COLUMN,
+ FIRESTORE_DISCOVERY_CACHE_TTL_SECONDS,
FIRESTORE_DOCUMENT_ID_FIELD,
FIRESTORE_ID_COLUMN,
FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT,
FIRESTORE_INCREMENTAL_VALUE_TYPES,
FIRESTORE_MAX_INTEGER,
+ FIRESTORE_MAX_SUBCOLLECTION_DEPTH,
FIRESTORE_MAX_TIMESTAMP,
FIRESTORE_METADATA_COLUMNS,
FIRESTORE_PAGE_SIZE,
FIRESTORE_PATH_COLUMN,
FIRESTORE_SCHEMA_SAMPLE_DOCUMENTS,
+ FIRESTORE_SUBCOLLECTION_SAMPLE_DOCUMENTS,
FIRESTORE_UPDATE_TIME_COLUMN,
GOOGLE_TOKEN_URI,
IDENTITY_TOOLKIT_API_ROOT,
@@ -57,6 +63,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.s
REQUEST_TIMEOUT_SECONDS,
RESPONSE_TOO_LARGE_ERROR,
TOKEN_EXPIRY_SKEW_SECONDS,
+ firestore_collection_group_table_name,
firestore_table_name,
is_supported_incremental_field_name,
realtime_database_table_name,
@@ -360,10 +367,14 @@ def _as_column(value: Any) -> Any:
return value
+def _relative_document_path(document_name: str) -> str:
+ """Turn a full document resource name into the path Firestore addresses it by (`rooms/room1`)."""
+ return document_name.split("/documents/", 1)[1] if "/documents/" in document_name else document_name
+
+
def flatten_firestore_document(document: dict[str, Any]) -> dict[str, Any]:
"""Turn one Firestore document into a flat row of top-level fields plus metadata columns."""
- name = str(document.get("name") or "")
- path = name.split("/documents/", 1)[1] if "/documents/" in name else name
+ path = _relative_document_path(str(document.get("name") or ""))
fields = document.get("fields")
if not isinstance(fields, dict):
fields = {}
@@ -400,10 +411,21 @@ def _firestore_documents_root(credentials: FirebaseCredentials) -> str:
def list_collection_ids(
- session: requests.Session, tokens: AccessTokenProvider, credentials: FirebaseCredentials
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ parent_document_path: Optional[str] = None,
) -> list[str]:
- """List the root-level Firestore collections in the project's database."""
- url = f"{_firestore_documents_root(credentials)}:listCollectionIds"
+ """List the Firestore collection ids directly under a parent.
+
+ With no parent this lists the root-level collections. With a document path (`rooms/room1`) it
+ lists that document's subcollection ids — the only way Firestore exposes subcollections.
+ """
+ root = _firestore_documents_root(credentials)
+ if parent_document_path:
+ url = f"{root}/{quote(parent_document_path, safe='/')}:listCollectionIds"
+ else:
+ url = f"{root}:listCollectionIds"
collection_ids: list[str] = []
page_token: Optional[str] = None
@@ -698,6 +720,60 @@ def iter_firestore_documents(
resumable_source_manager.clear_state()
+def _run_query_documents(results: Any) -> list[dict[str, Any]]:
+ """Pull the documents out of a `runQuery` response, skipping readTime-only entries."""
+ return [
+ result["document"]
+ for result in results
+ if isinstance(result, dict) and isinstance(result.get("document"), dict)
+ ]
+
+
+def iter_firestore_collection_group(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ collection_id: str,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Read every document in a Firestore subcollection.
+
+ `listDocuments` reads only a collection under a fixed path, so a subcollection like `messages`
+ that lives under many parent documents needs a collection-group query instead. `runQuery` with
+ `allDescendants=true` returns every document in any collection with this id, at any depth.
+ """
+ url = f"{_firestore_documents_root(credentials)}:runQuery"
+ # `runQuery` has no page token, so paging is done by ordering on the document name and resuming
+ # after the last one read. The cursor is that full document resource name.
+ cursor = _resume_cursor(resumable_source_manager, logger, f"Firestore collection group {collection_id}")
+
+ for _ in range(MAX_PAGES):
+ query: dict[str, Any] = {
+ "from": [{"collectionId": collection_id, "allDescendants": True}],
+ "orderBy": [{"field": {"fieldPath": "__name__"}, "direction": "ASCENDING"}],
+ "limit": FIRESTORE_PAGE_SIZE,
+ }
+ if cursor:
+ query["startAt"] = {"values": [{"referenceValue": cursor}], "before": False}
+ results = _request(session, tokens, "POST", url, json_body={"structuredQuery": query}) or []
+
+ documents = _run_query_documents(results)
+ if documents:
+ yield [flatten_firestore_document(document) for document in documents]
+
+ if len(documents) < FIRESTORE_PAGE_SIZE:
+ break
+ next_cursor = documents[-1].get("name")
+ if not next_cursor:
+ break
+ cursor = str(next_cursor)
+ # Saved after yielding so a crash re-yields the last page instead of skipping it.
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor=cursor))
+
+ resumable_source_manager.clear_state()
+
+
def iter_auth_users(
session: requests.Session,
tokens: AccessTokenProvider,
@@ -827,6 +903,15 @@ def get_rows(
api_session = _api_session(credentials)
+ # Incremental sync isn't supported for a collection group yet, so it always reads in full —
+ # `firebase_source` never resolves an incremental cursor for one either.
+ collection_group_id = _resolve_firestore_collection_group(table_name)
+ if collection_group_id is not None:
+ yield from iter_firestore_collection_group(
+ api_session, tokens, credentials, collection_group_id, resumable_source_manager, logger
+ )
+ return
+
collection_id = _resolve_firestore_collection(table_name)
if collection_id is not None:
if incremental_cursor is not None:
@@ -841,10 +926,10 @@ def get_rows(
resumable_source_manager,
logger,
)
- return
- yield from iter_firestore_documents(
- api_session, tokens, credentials, collection_id, resumable_source_manager, logger
- )
+ else:
+ yield from iter_firestore_documents(
+ api_session, tokens, credentials, collection_id, resumable_source_manager, logger
+ )
return
path = _resolve_realtime_database_path(credentials, table_name)
@@ -856,8 +941,20 @@ def get_rows(
def _resolve_firestore_collection(table_name: str) -> Optional[str]:
- """Recover the Firestore collection id a table name was built from."""
+ """Recover the root Firestore collection id a table name was built from (`rooms`)."""
prefix = firestore_table_name("")
+ if not table_name.startswith(prefix) or len(table_name) == len(prefix):
+ return None
+ collection_id = table_name[len(prefix) :]
+ # A root collection id can never contain `/`, so a remaining slash marks a collection-group table.
+ if "/" in collection_id:
+ return None
+ return collection_id
+
+
+def _resolve_firestore_collection_group(table_name: str) -> Optional[str]:
+ """Recover the collection-group id a subcollection table was built from (`messages`)."""
+ prefix = firestore_collection_group_table_name("")
if not table_name.startswith(prefix) or len(table_name) == len(prefix):
return None
return table_name[len(prefix) :]
@@ -870,15 +967,167 @@ def _resolve_realtime_database_path(credentials: FirebaseCredentials, table_name
return None
-def get_tables(credentials: FirebaseCredentials) -> list[str]:
+def _sample_firestore_document_paths(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ collection_id: str,
+ *,
+ as_collection_group: bool,
+ limit: int,
+) -> list[str]:
+ """Return the paths of a few documents in a collection, to probe them for subcollections."""
+ if as_collection_group:
+ # A subcollection spans many parents, so a collection-group query samples it. Only the
+ # document names are needed here, so `select` keeps the response small.
+ query = {
+ "from": [{"collectionId": collection_id, "allDescendants": True}],
+ "select": {"fields": [{"fieldPath": "__name__"}]},
+ "limit": limit,
+ }
+ results = (
+ _request(
+ session,
+ tokens,
+ "POST",
+ f"{_firestore_documents_root(credentials)}:runQuery",
+ json_body={"structuredQuery": query},
+ )
+ or []
+ )
+ documents = _run_query_documents(results)
+ else:
+ # `showMissing` surfaces parent documents that exist only to hold a subcollection. Without it
+ # `listDocuments` hides them, so a collection written only under `parent/{id}/child` is never
+ # sampled and stays invisible. A missing document returns a name and no fields, which is all
+ # this probe reads. The flag is incompatible with `where`/`orderBy`, which this call omits.
+ url = f"{_firestore_documents_root(credentials)}/{quote(collection_id, safe='')}"
+ payload = _request(session, tokens, "GET", url, params={"pageSize": limit, "showMissing": "true"}) or {}
+ documents = [doc for doc in payload.get("documents") or [] if isinstance(doc, dict)]
+
+ return [_relative_document_path(str(doc["name"])) for doc in documents if doc.get("name")]
+
+
+@frozen
+class FirestoreCollections:
+ """The Firestore collections a source can read: root collections and subcollection groups."""
+
+ root_ids: list[str]
+ subcollection_ids: list[str]
+
+
+def discover_firestore_collections(
+ session: requests.Session, tokens: AccessTokenProvider, credentials: FirebaseCredentials
+) -> FirestoreCollections:
+ """Return the Firestore collections this source can read.
+
+ Root collections come from `listCollectionIds`. Subcollections are found by sampling documents
+ and asking each for its child collection ids, following nesting down to the depth cap. A
+ subcollection reads as a collection group keyed by its id, so each subcollection id is surfaced
+ once even when it lives under more than one parent — but a subcollection is kept separate from a
+ root collection of the same id, because the two read through different queries.
+ """
+ root_ids: list[str] = []
+ seen_root_ids: set[str] = set()
+ for collection_id in list_collection_ids(session, tokens, credentials):
+ if collection_id not in seen_root_ids:
+ seen_root_ids.add(collection_id)
+ root_ids.append(collection_id)
+
+ subcollection_ids: list[str] = []
+ seen_subcollection_ids: set[str] = set()
+ # Each frontier entry is (collection id, whether it is sampled as a collection group).
+ frontier: list[tuple[str, bool]] = [(collection_id, False) for collection_id in root_ids]
+
+ for _ in range(FIRESTORE_MAX_SUBCOLLECTION_DEPTH):
+ next_frontier: list[tuple[str, bool]] = []
+ for collection_id, as_collection_group in frontier:
+ child_ids: set[str] = set()
+ for document_path in _sample_firestore_document_paths(
+ session,
+ tokens,
+ credentials,
+ collection_id,
+ as_collection_group=as_collection_group,
+ limit=FIRESTORE_SUBCOLLECTION_SAMPLE_DOCUMENTS,
+ ):
+ child_ids.update(list_collection_ids(session, tokens, credentials, parent_document_path=document_path))
+ for child_id in sorted(child_ids):
+ if child_id in seen_subcollection_ids:
+ continue
+ seen_subcollection_ids.add(child_id)
+ subcollection_ids.append(child_id)
+ next_frontier.append((child_id, True))
+ if not next_frontier:
+ break
+ frontier = next_frontier
+
+ return FirestoreCollections(root_ids=root_ids, subcollection_ids=subcollection_ids)
+
+
+def _firestore_discovery_cache_key(credentials: FirebaseCredentials) -> str:
+ # What discovery returns is fixed by the project, the database, and the service account's read
+ # scope, so those three identify the entry. All are non-secret identifiers.
+ return f"@dwh/firebase/{credentials.project_id}/{credentials.database_id}/{credentials.client_email}/collections"
+
+
+def _discover_firestore_collections_cached(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ force_refresh: bool = False,
+) -> FirestoreCollections:
+ """Cached wrapper around `discover_firestore_collections`.
+
+ Discovery fires many sequential requests on the synchronous schema-lookup path, so callers that
+ don't need fresh data read through this cache; the user-triggered refresh passes
+ `force_refresh=True`. A failed walk raises before the cache is written, so the previous value
+ survives. See `FIRESTORE_DISCOVERY_CACHE_TTL_SECONDS` for why this mirrors the Slack source's
+ channel-discovery cache.
+ """
+ cache_key = _firestore_discovery_cache_key(credentials)
+ if not force_refresh:
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+ discovered = discover_firestore_collections(session, tokens, credentials)
+ cache.set(cache_key, discovered, FIRESTORE_DISCOVERY_CACHE_TTL_SECONDS)
+ return discovered
+
+
+def _dedupe_by_storage_name(table_names: list[str]) -> list[str]:
+ """Drop any later table whose normalized storage name repeats an earlier one.
+
+ Downstream naming flattens distinct source names onto one warehouse table, and two schemas that
+ share a storage name would fight over one `DataWarehouseTable` row. Keeping the first occurrence
+ stops that silent overwrite.
+ """
+ seen: set[str] = set()
+ unique: list[str] = []
+ for name in table_names:
+ storage_name = NamingConvention.normalize_identifier(name)
+ if storage_name in seen:
+ LOGGER.warning(f"Skipping Firebase table {name}: storage name {storage_name} is already taken")
+ continue
+ seen.add(storage_name)
+ unique.append(name)
+ return unique
+
+
+def get_tables(credentials: FirebaseCredentials, force_refresh: bool = False) -> list[str]:
"""List every table this source can sync: Auth users, Firestore collections, configured paths."""
- tables: list[str] = [AUTH_USERS_TABLE]
+ firestore_tables: list[str] = []
tokens = AccessTokenProvider(_auth_session(credentials), credentials)
api_session = _api_session(credentials)
try:
- collection_ids = list_collection_ids(api_session, tokens, credentials)
- tables.extend(firestore_table_name(collection_id) for collection_id in collection_ids)
+ collections = _discover_firestore_collections_cached(
+ api_session, tokens, credentials, force_refresh=force_refresh
+ )
+ firestore_tables = [firestore_table_name(collection_id) for collection_id in collections.root_ids]
+ firestore_tables += [
+ firestore_collection_group_table_name(collection_id) for collection_id in collections.subcollection_ids
+ ]
except requests.HTTPError as e:
# A project with no Firestore database answers 404, a service account without the
# Datastore role answers 403, and a default database provisioned in Datastore mode
@@ -889,8 +1138,8 @@ def get_tables(credentials: FirebaseCredentials) -> list[str]:
raise
LOGGER.warning(f"Skipping Firestore collections for Firebase project {credentials.project_id}: {status}")
- tables.extend(realtime_database_table_name(path) for path in credentials.realtime_database_paths)
- return tables
+ rtdb_tables = [realtime_database_table_name(path) for path in credentials.realtime_database_paths]
+ return _dedupe_by_storage_name([AUTH_USERS_TABLE, *firestore_tables, *rtdb_tables])
def validate_credentials(credentials: FirebaseCredentials) -> tuple[bool, Optional[str]]:
@@ -957,7 +1206,13 @@ def firebase_source(
incremental_field_type: Optional[IncrementalFieldType] = None,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
- is_firestore = _resolve_firestore_collection(table_name) is not None
+ collection_group_id = _resolve_firestore_collection_group(table_name)
+ collection_id = _resolve_firestore_collection(table_name)
+ is_firestore = collection_group_id is not None or collection_id is not None
+ # `resolve_incremental_cursor` resolves a cursor only for a root collection: it recovers the
+ # collection id through `_resolve_firestore_collection`, which returns None for a collection
+ # group's own `firestore_collection_group/` prefix, and `get_rows` never takes a cursor down the
+ # collection-group path either — incremental sync isn't supported for a collection group yet.
incremental_cursor = resolve_incremental_cursor(
table_name,
should_use_incremental_field,
@@ -968,7 +1223,11 @@ def firebase_source(
if table_name == AUTH_USERS_TABLE:
primary_keys = AUTH_USERS_PRIMARY_KEY
- elif is_firestore:
+ elif collection_group_id is not None:
+ # A collection group can hold documents with the same id under different parents, so the
+ # full document path is the only unique key.
+ primary_keys = [FIRESTORE_PATH_COLUMN]
+ elif collection_id is not None:
primary_keys = [FIRESTORE_ID_COLUMN]
else:
primary_keys = [REALTIME_DATABASE_KEY_COLUMN]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
index f8ee803fd941..18092dcb4384 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
@@ -25,6 +25,10 @@ DEFAULT_DATABASE_ID: Final[str] = "(default)"
AUTH_USERS_TABLE: Final[str] = "auth_users"
FIRESTORE_TABLE_PREFIX: Final[str] = "firestore_"
+# A subcollection reads as a collection group (every collection with the id, under any parent). The
+# `/` in the prefix states that scope and cannot appear in a Firestore collection id, so no root
+# collection can ever produce this name and be routed to the wrong reader.
+FIRESTORE_COLLECTION_GROUP_TABLE_PREFIX: Final[str] = "firestore_collection_group/"
REALTIME_DATABASE_TABLE_PREFIX: Final[str] = "realtime_database_"
# Firestore caps a `listDocuments` page at 300 documents; Identity Platform caps `accounts:batchGet`
@@ -34,6 +38,19 @@ FIRESTORE_COLLECTION_IDS_PAGE_SIZE: Final[int] = 300
AUTH_USERS_PAGE_SIZE: Final[int] = 1000
REALTIME_DATABASE_PAGE_SIZE: Final[int] = 500
+# Firestore has no API to list a collection's subcollections, only a single document's. So table
+# discovery samples a few documents per collection and unions the subcollection ids they report.
+# A subcollection present on no sampled document is missed. `depth` bounds how far nesting is
+# followed below the root collections.
+FIRESTORE_SUBCOLLECTION_SAMPLE_DOCUMENTS: Final[int] = 10
+FIRESTORE_MAX_SUBCOLLECTION_DEPTH: Final[int] = 3
+
+# Discovery walks the project one document sample at a time, so it can fire ~11 sequential requests
+# per collection id — all on the synchronous schema-lookup path a user waits on. Cache the result so
+# repeated lookups don't repeat the walk; the user-triggered refresh bypasses it. Mirrors the Slack
+# source's channel-discovery cache, which caps the same cost for the same reason.
+FIRESTORE_DISCOVERY_CACHE_TTL_SECONDS: Final[int] = 300
+
# Hard stop so an endpoint that keeps handing back a page token can't page forever.
MAX_PAGES: Final[int] = 100_000
@@ -132,9 +149,15 @@ REALTIME_DATABASE_HOST_SUFFIXES: Final[tuple[str, ...]] = (".firebaseio.com", ".
def firestore_table_name(collection_id: str) -> str:
+ """Table name for one root-level Firestore collection (`rooms`)."""
return f"{FIRESTORE_TABLE_PREFIX}{collection_id}"
+def firestore_collection_group_table_name(collection_id: str) -> str:
+ """Table name for one Firestore subcollection, read as a collection group keyed by its id."""
+ return f"{FIRESTORE_COLLECTION_GROUP_TABLE_PREFIX}{collection_id}"
+
+
def is_supported_incremental_field_name(name: str) -> bool:
return bool(_UNQUOTED_FIELD_PATH.match(name))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
index dd9b09dba0ba..d64a4ead4bf7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
@@ -150,7 +150,7 @@ Create a service account key in the Firebase console under Project settings, Ser
# Firestore collections are created by the customer's app, so the table list can only come
# from the live project.
credentials = self._credentials(config)
- tables = get_tables(credentials)
+ tables = get_tables(credentials, force_refresh=force_refresh)
if names is not None:
wanted = set(names)
tables = [table for table in tables if table in wanted]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py
index b668a60313ce..7eed56ed1e35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py
@@ -1,10 +1,13 @@
import json
import datetime
+from collections.abc import Iterator
from typing import Any, Optional
import pytest
from unittest import mock
+from django.core.cache import cache as django_cache
+
import jwt
import requests
from structlog.types import FilteringBoundLogger
@@ -26,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.f
get_rows,
get_tables,
iter_auth_users,
+ iter_firestore_collection_group,
iter_firestore_documents,
iter_firestore_documents_incremental,
iter_realtime_database,
@@ -765,6 +769,69 @@ class TestFirestoreIncrementalFieldDiscovery:
assert list(found) == tables[:FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT]
+class TestFirestoreCollectionGroup:
+ @staticmethod
+ def _group_document(document_id: str) -> dict[str, Any]:
+ return {
+ "name": f"projects/demo-project/databases/(default)/documents/rooms/room1/messages/{document_id}",
+ "fields": {"body": {"stringValue": document_id}},
+ }
+
+ def test_reads_every_document_across_parents_and_pages_by_name(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(
+ payload=[{"document": self._group_document("m1")}, {"document": self._group_document("m2")}]
+ ),
+ FakeResponse(payload=[{"document": self._group_document("m3")}]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ manager = FakeResumeManager()
+
+ with mock.patch(f"{_FIREBASE_MODULE}.FIRESTORE_PAGE_SIZE", 2):
+ batches = list(
+ iter_firestore_collection_group(
+ session.as_session(), token_provider(session), credentials(), "messages", manager, logger
+ )
+ )
+
+ assert [row[FIRESTORE_ID_COLUMN] for batch in batches for row in batch] == ["m1", "m2", "m3"]
+ first_query = session.requests[0][2]["json"]["structuredQuery"]
+ assert first_query["from"] == [{"collectionId": "messages", "allDescendants": True}]
+ # The second page resumes after the last document of the first, and that name is checkpointed.
+ boundary = self._group_document("m2")["name"]
+ assert session.requests[1][2]["json"]["structuredQuery"]["startAt"]["values"] == [{"referenceValue": boundary}]
+ assert [state.cursor for state in manager.saved] == [boundary]
+ assert manager.cleared is True
+
+ def test_a_subcollection_table_reads_through_the_collection_group(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload=[{"document": self._group_document("m1")}])],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ batches = list(get_rows(credentials(), "firestore_collection_group/messages", FakeResumeManager(), logger))
+
+ assert session.requests[0][1] == f"{DOCUMENTS_ROOT}:runQuery"
+ assert [row[FIRESTORE_ID_COLUMN] for row in batches[0]] == ["m1"]
+
+ def test_a_root_collection_named_like_a_group_reads_as_a_root(self, logger: FilteringBoundLogger) -> None:
+ # A root collection whose id starts with `collection_group_` has no slash, so it must read
+ # through `listDocuments`, not be misrouted to a collection-group query.
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"documents": [firestore_document("a")]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ list(get_rows(credentials(), "firestore_collection_group_orders", FakeResumeManager(), logger))
+
+ assert session.requests[0][0] == "GET"
+ assert session.requests[0][1] == f"{DOCUMENTS_ROOT}/collection_group_orders"
+
+
class TestAuthUsersPagination:
def test_stops_when_google_returns_no_token(self, logger: FilteringBoundLogger) -> None:
session = FakeSession(
@@ -908,9 +975,21 @@ class TestRealtimeDatabase:
class TestTableDiscovery:
+ @pytest.fixture(autouse=True)
+ def _clear_discovery_cache(self) -> Iterator[None]:
+ # Discovery is cached per credentials, so isolate each test from the others' cached walk.
+ django_cache.clear()
+ yield
+ django_cache.clear()
+
def test_lists_auth_firestore_and_configured_paths(self) -> None:
session = FakeSession(
- request_responses=[FakeResponse(payload={"collectionIds": ["rooms", "users"]})],
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms", "users"]}),
+ # Neither root collection has documents to probe, so no subcollections are found.
+ FakeResponse(payload={"documents": []}),
+ FakeResponse(payload={"documents": []}),
+ ],
post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
)
@@ -930,6 +1009,113 @@ class TestTableDiscovery:
"realtime_database_messages_lobby",
]
+ def test_subcollections_are_discovered_by_sampling_documents(self) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms"]}),
+ # Sampling `rooms` returns one document to probe for subcollections.
+ FakeResponse(payload={"documents": [firestore_document("room1")]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ # Sampling the `messages` collection group finds no deeper subcollections.
+ FakeResponse(payload=[]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(credentials())
+
+ assert tables == [AUTH_USERS_TABLE, "firestore_rooms", "firestore_collection_group/messages"]
+ # The subcollection is discovered by asking a sampled document for its child collections.
+ assert session.requests[2][1] == f"{DOCUMENTS_ROOT}/rooms/room1:listCollectionIds"
+
+ def test_a_subcollection_id_is_listed_once_even_under_several_parents(self) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms", "chats"]}),
+ FakeResponse(payload={"documents": [firestore_document("room1")]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ FakeResponse(payload={"documents": [firestore_document("chat1")]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ # One collection-group sample for the single `messages` id, then nothing deeper.
+ FakeResponse(payload=[]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(credentials())
+
+ # `messages` under both parents is one collection group, so it becomes a single table.
+ assert tables == [AUTH_USERS_TABLE, "firestore_rooms", "firestore_chats", "firestore_collection_group/messages"]
+
+ def test_a_subcollection_sharing_an_id_with_a_root_collection_is_not_hidden(self) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["messages", "rooms"]}),
+ # Root `messages` has no documents; root `rooms` holds a `messages` subcollection.
+ FakeResponse(payload={"documents": []}),
+ FakeResponse(payload={"documents": [firestore_document("room1")]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ FakeResponse(payload=[]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(credentials())
+
+ # The root table reads root documents only, so the subcollection needs its own group table.
+ assert tables == [
+ AUTH_USERS_TABLE,
+ "firestore_messages",
+ "firestore_rooms",
+ "firestore_collection_group/messages",
+ ]
+
+ def test_a_table_whose_storage_name_collides_is_dropped(self) -> None:
+ session = FakeSession(
+ request_responses=[
+ # A root collection named `collection_group_messages` normalizes to the same storage
+ # name as the `messages` collection-group table.
+ FakeResponse(payload={"collectionIds": ["collection_group_messages", "rooms"]}),
+ FakeResponse(payload={"documents": []}),
+ FakeResponse(payload={"documents": [firestore_document("room1")]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ FakeResponse(payload=[]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(credentials())
+
+ # The root table is discovered first, so the colliding collection-group table is dropped.
+ assert tables == [AUTH_USERS_TABLE, "firestore_collection_group_messages", "firestore_rooms"]
+
+ def test_subcollections_below_missing_parent_documents_are_discovered(self) -> None:
+ # A parent that exists only to hold a subcollection is a "missing" document: `listDocuments`
+ # omits it unless `showMissing` is set, and it returns a name with no fields. Discovery must
+ # still sample and probe it, or a collection written only under such a parent is never found.
+ missing_parent = {"name": f"{DOCUMENTS_ROOT}/rooms/room1"}
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms"]}),
+ FakeResponse(payload={"documents": [missing_parent]}),
+ FakeResponse(payload={"collectionIds": ["messages"]}),
+ FakeResponse(payload=[]),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(credentials())
+
+ assert tables == [AUTH_USERS_TABLE, "firestore_rooms", "firestore_collection_group/messages"]
+ # Without `showMissing` on the root sample, the missing parent is dropped and its
+ # subcollection is never discovered.
+ assert session.requests[1][2]["params"]["showMissing"] == "true"
+
@pytest.mark.parametrize("status", [403, 404])
def test_unreachable_firestore_does_not_hide_the_other_tables(self, status: int) -> None:
session = FakeSession(
@@ -979,6 +1165,32 @@ class TestTableDiscovery:
with pytest.raises(requests.HTTPError):
get_tables(credentials())
+ def test_discovery_is_cached_and_force_refresh_rewalks(self) -> None:
+ # `rooms` has no documents to probe, so one discovery pass is two requests: the root
+ # `listCollectionIds` and the sample read that finds no subcollections.
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms"]}),
+ FakeResponse(payload={"documents": []}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD), FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ first = get_tables(credentials())
+ # The second lookup reuses the cached collections instead of walking the project again.
+ cached = get_tables(credentials())
+ assert len(session.requests) == 2
+
+ # A forced refresh walks again, so it needs a fresh set of discovery responses.
+ session.request_queue.extend(
+ [FakeResponse(payload={"collectionIds": ["rooms"]}), FakeResponse(payload={"documents": []})]
+ )
+ get_tables(credentials(), force_refresh=True)
+
+ assert first == cached == [AUTH_USERS_TABLE, "firestore_rooms"]
+ assert len(session.requests) == 4
+
class TestSampleCapture:
def test_auth_user_responses_never_reach_sample_capture(self, logger: FilteringBoundLogger) -> None:
@@ -1145,6 +1357,8 @@ class TestSourceResponseShape:
[
(AUTH_USERS_TABLE, ["localId"], False),
("firestore_rooms", [FIRESTORE_ID_COLUMN], True),
+ # A subcollection is a collection group, so its unique key is the full document path.
+ ("firestore_collection_group/messages", [FIRESTORE_PATH_COLUMN], True),
("realtime_database_rooms", [REALTIME_DATABASE_KEY_COLUMN], False),
],
)