: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): sync Firestore collections incrementally (#92446)
Tom Owers02afa83ebe25
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.pyindex 1b09c35baf4a..3bfe6b361447 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@@ -1,5 +1,6 @@import jsonimport time+import datetimeimport dataclassesfrom collections.abc import Iteratorfrom typing import Any, Optional@@ -12,8 +13,13 @@ from structlog.types import FilteringBoundLoggerfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ incremental_field,+ rank_incremental_fields,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (AUTH_USERS_PAGE_SIZE,@@ -22,9 +28,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.sFIRESTORE_API_ROOT,FIRESTORE_COLLECTION_IDS_PAGE_SIZE,FIRESTORE_CREATE_TIME_COLUMN,+ FIRESTORE_DOCUMENT_ID_FIELD,FIRESTORE_ID_COLUMN,+ FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT,+ FIRESTORE_INCREMENTAL_VALUE_TYPES,+ FIRESTORE_MAX_INTEGER,+ FIRESTORE_MAX_TIMESTAMP,+ FIRESTORE_METADATA_COLUMNS,FIRESTORE_PAGE_SIZE,FIRESTORE_PATH_COLUMN,+ FIRESTORE_SCHEMA_SAMPLE_DOCUMENTS,FIRESTORE_UPDATE_TIME_COLUMN,GOOGLE_TOKEN_URI,IDENTITY_TOOLKIT_API_ROOT,@@ -45,8 +58,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.sRESPONSE_TOO_LARGE_ERROR,TOKEN_EXPIRY_SKEW_SECONDS,firestore_table_name,+ is_supported_incremental_field_name,realtime_database_table_name,)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldTypeLOGGER: FilteringBoundLogger = structlog.get_logger(__name__)@@ -68,6 +83,21 @@ class FirebaseResumeConfig:"""Resume cursor: a Firestore/Identity Platform page token, or a Realtime Database key."""cursor: str+ # An incremental Firestore read has no page token. It pages on the last row's position instead,+ # which is the ordered pair (cursor field value, document name), so `cursor` holds the document+ # name and this holds the JSON-encoded Firestore value beside it. Every other surface pages on a+ # single opaque token and leaves this unset, which is also what a cursor saved before this field+ # existed decodes to.+ incremental_value: Optional[str] = None+++@frozen+class FirestoreIncrementalCursor:+ """The cursor field the user picked for one collection, and the watermark to read past."""++ field_name: str+ field_type: IncrementalFieldType+ last_value: Any@dataclasses.dataclass(frozen=True, kw_only=True)@@ -390,6 +420,254 @@ def list_collection_ids(return collection_ids+def sample_firestore_incremental_fields(+ session: requests.Session,+ tokens: AccessTokenProvider,+ credentials: FirebaseCredentials,+ collection_id: str,+) -> list[IncrementalField]:+ """Find the fields of one collection that can carry an incremental sync's cursor.++ Firestore holds no schema to read, so the candidates come from a sample of real documents. A+ field qualifies only when every sampled document carries it with the same orderable type:+ Firestore drops a document from an ordered read when the ordered field is missing, so a field+ that only part of the collection sets would strand the rest of it permanently.+ """+ url = f"{_firestore_documents_root(credentials)}/{quote(collection_id, safe='')}"+ payload = _request(session, tokens, "GET", url, params={"pageSize": FIRESTORE_SCHEMA_SAMPLE_DOCUMENTS}) or {}+ documents = [document for document in payload.get("documents") or [] if isinstance(document, dict)]+ if not documents:+ return []++ shared = _orderable_field_types(documents[0])+ for document in documents[1:]:+ present = _orderable_field_types(document)+ shared = {name: field_type for name, field_type in shared.items() if present.get(name) == field_type}++ return rank_incremental_fields([incremental_field(name, field_type) for name, field_type in sorted(shared.items())])+++def _orderable_field_types(document: dict[str, Any]) -> dict[str, IncrementalFieldType]:+ """Map the document's top-level fields to the cursor type each one could drive."""+ fields = document.get("fields")+ if not isinstance(fields, dict):+ return {}++ types: dict[str, IncrementalFieldType] = {}+ for name, value in fields.items():+ if not isinstance(value, dict) or not is_supported_incremental_field_name(name):+ continue+ # `flatten_firestore_document` writes the metadata columns last, so a document field of the+ # same name never reaches the row. The query would filter on the document field while the+ # watermark tracked the metadata column, and the two would drift apart.+ if name in FIRESTORE_METADATA_COLUMNS:+ continue+ for value_type, field_type in FIRESTORE_INCREMENTAL_VALUE_TYPES.items():+ if value_type in value:+ types[name] = field_type+ break+ return types+++def get_incremental_fields(+ credentials: FirebaseCredentials, table_names: list[str]+) -> dict[str, list[IncrementalField]]:+ """Candidate cursor fields for each Firestore collection among `table_names`.++ Auth users and Realtime Database paths never appear: Identity Platform's `accounts:batchGet` and+ the Realtime Database REST API both page on a key and expose no timestamp filter to sync against.+ """+ collections = [+ (table, collection_id)+ for table, collection_id in ((table, _resolve_firestore_collection(table)) for table in table_names)+ if collection_id is not None+ ]+ if not collections:+ return {}++ if len(collections) > FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT:+ # A specific sync-settings request already narrows `table_names` to the one table it's asking+ # about, so this only fires for a "list every table" request against a project with an unusually+ # large number of collections. Sampling every one of them, one synchronous request at a time,+ # would tie up a worker for the length of the request; the tables past the limit still appear in+ # the schema list, just without incremental candidates, and get sampled if a later request asks+ # about one of them by name.+ LOGGER.warning(+ f"Sampling incremental fields for the first {FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT} of "+ f"{len(collections)} Firestore collections; the rest offer full refresh only until asked "+ "about individually."+ )+ collections = collections[:FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT]++ tokens = AccessTokenProvider(_auth_session(credentials), credentials)+ api_session = _api_session(credentials)++ fields: dict[str, list[IncrementalField]] = {}+ for table, collection_id in collections:+ try:+ candidates = sample_firestore_incremental_fields(api_session, tokens, credentials, collection_id)+ except requests.HTTPError as e:+ # One unreadable collection must not empty the whole schema picker. That table offers+ # full refresh, and the sync itself still reports the failure.+ LOGGER.warning(f"Skipping incremental field discovery for Firestore collection {collection_id}: {e}")+ continue+ if candidates:+ fields[table] = candidates+ return fields+++def _rfc3339(value: Any) -> str:+ """Render a watermark the way Firestore renders its own timestamps: UTC, `Z`-suffixed.++ The stored watermark is normally a datetime, but `process_incremental_value` passes a number+ through unchanged for a datetime cursor, so a numeric watermark is read as a Unix epoch.+ """+ if isinstance(value, datetime.datetime):+ moment = value if value.tzinfo is not None else value.replace(tzinfo=datetime.UTC)+ elif isinstance(value, int | float) and not isinstance(value, bool):+ moment = datetime.datetime.fromtimestamp(value, tz=datetime.UTC)+ else:+ raise FirebaseConfigError(+ "PostHog couldn't read the last value this table synced up to. Reset the table's sync to "+ "start it again from the beginning."+ )+ return moment.astimezone(datetime.UTC).isoformat().replace("+00:00", "Z")+++def _firestore_cursor_value(field_type: IncrementalFieldType, value: Any) -> dict[str, Any]:+ if field_type == IncrementalFieldType.Integer:+ # Firestore orders integers and doubles together, so a field sampled as an integer can still+ # carry a fractional value on some document. Truncating that watermark with int() would send+ # a lower bound the fractional row is still above, importing it again on every later run.+ if isinstance(value, float) and not value.is_integer():+ return {"doubleValue": value}+ # The REST API carries int64 as a JSON string so the value survives a JavaScript parser.+ return {"integerValue": str(int(value))}+ return {"timestampValue": _rfc3339(value)}+++def _firestore_type_ceiling(field_type: IncrementalFieldType) -> dict[str, Any]:+ if field_type == IncrementalFieldType.Integer:+ return {"integerValue": str(FIRESTORE_MAX_INTEGER)}+ return {"timestampValue": FIRESTORE_MAX_TIMESTAMP}+++def _incremental_filter(field_name: str, field_type: IncrementalFieldType, last_value: Any) -> dict[str, Any]:+ """Bound a read to the rows after the watermark, and to the cursor field's own type.++ Both bounds are needed. See `FIRESTORE_MAX_TIMESTAMP` for what a lone lower bound would match.+ """+ field = {"fieldPath": field_name}+ return {+ "compositeFilter": {+ "op": "AND",+ "filters": [+ {+ "fieldFilter": {+ "field": field,+ "op": "GREATER_THAN",+ "value": _firestore_cursor_value(field_type, last_value),+ }+ },+ {+ "fieldFilter": {+ "field": field,+ "op": "LESS_THAN_OR_EQUAL",+ "value": _firestore_type_ceiling(field_type),+ }+ },+ ],+ }+ }+++def _document_cursor(document: dict[str, Any], field_name: str) -> Optional[tuple[dict[str, Any], str]]:+ """Position of one row in the ordered read: its cursor field value, then its document name."""+ fields = document.get("fields")+ value = fields.get(field_name) if isinstance(fields, dict) else None+ name = document.get("name")+ if not isinstance(value, dict) or not isinstance(name, str):+ return None+ return value, name+++def iter_firestore_documents_incremental(+ session: requests.Session,+ tokens: AccessTokenProvider,+ credentials: FirebaseCredentials,+ collection_id: str,+ field_name: str,+ field_type: IncrementalFieldType,+ last_value: Any,+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Read the documents of one collection that changed after the watermark, oldest first.++ `runQuery` is the only Firestore read that filters, and it answers with no page token, so each+ page starts after the position of the previous page's last row. Ordering by the cursor field and+ then the document id keeps that position unambiguous when documents share a cursor value.+ """+ url = f"{_firestore_documents_root(credentials)}:runQuery"+ query: dict[str, Any] = {+ "from": [{"collectionId": collection_id}],+ "where": _incremental_filter(field_name, field_type, last_value),+ "orderBy": [+ {"field": {"fieldPath": field_name}, "direction": "ASCENDING"},+ {"field": {"fieldPath": FIRESTORE_DOCUMENT_ID_FIELD}, "direction": "ASCENDING"},+ ],+ "limit": FIRESTORE_PAGE_SIZE,+ }+ cursor = _resume_incremental_cursor(resumable_source_manager, logger, collection_id)++ for _ in range(MAX_PAGES):+ page_query = dict(query)+ if cursor is not None:+ value, name = cursor+ page_query["startAt"] = {"values": [value, {"referenceValue": name}], "before": False}+ payload = _request(session, tokens, "POST", url, json_body={"structuredQuery": page_query}) or []++ # A `runQuery` stream also carries entries that only report read progress and hold no document.+ documents = [+ entry["document"]+ for entry in payload+ if isinstance(entry, dict) and isinstance(entry.get("document"), dict)+ ]+ if documents:+ yield [flatten_firestore_document(document) for document in documents]++ if len(documents) < FIRESTORE_PAGE_SIZE:+ break++ cursor = _document_cursor(documents[-1], field_name)+ if cursor is None:+ # The query orders on this field, so Firestore cannot return a document without it.+ logger.warning(f"Stopping Firestore collection {collection_id}: last document has no {field_name}")+ break+ # Saved after yielding so a crash re-yields the last page instead of skipping it.+ resumable_source_manager.save_state(+ FirebaseResumeConfig(cursor=cursor[1], incremental_value=json.dumps(cursor[0]))+ )++ resumable_source_manager.clear_state()+++def _resume_incremental_cursor(+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],+ logger: FilteringBoundLogger,+ collection_id: str,+) -> Optional[tuple[dict[str, Any], str]]:+ if not resumable_source_manager.can_resume():+ return None+ resume = resumable_source_manager.load_state()+ # A cursor saved with no field value beside it came from a full-refresh read and names a page+ # token rather than a document, so it cannot position an ordered query.+ if resume is None or resume.incremental_value is None:+ return None+ logger.debug(f"Resuming incremental Firestore collection {collection_id} from cursor={resume.cursor}")+ return json.loads(resume.incremental_value), resume.cursor++def iter_firestore_documents(session: requests.Session,tokens: AccessTokenProvider,@@ -521,6 +799,11 @@ def _resume_cursor(resume = resumable_source_manager.load_state()if resume is None:return None+ # A checkpoint carrying a field value came from an ordered incremental read, so its cursor names+ # a document rather than a page token. Every surface here pages on a token, which Firestore and+ # Identity Platform would both reject.+ if resume.incremental_value is not None:+ return Nonelogger.debug(f"Resuming {label} from cursor={resume.cursor}")return resume.cursor@@ -530,6 +813,7 @@ def get_rows(table_name: str,resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],logger: FilteringBoundLogger,+ incremental_cursor: Optional[FirestoreIncrementalCursor] = None,) -> Iterator[list[dict[str, Any]]]:tokens = AccessTokenProvider(_auth_session(credentials), credentials)@@ -545,6 +829,19 @@ def get_rows(collection_id = _resolve_firestore_collection(table_name)if collection_id is not None:+ if incremental_cursor is not None:+ yield from iter_firestore_documents_incremental(+ api_session,+ tokens,+ credentials,+ collection_id,+ incremental_cursor.field_name,+ incremental_cursor.field_type,+ incremental_cursor.last_value,+ resumable_source_manager,+ logger,+ )+ returnyield from iter_firestore_documents(api_session, tokens, credentials, collection_id, resumable_source_manager, logger)@@ -615,13 +912,59 @@ def validate_credentials(credentials: FirebaseCredentials) -> tuple[bool, Optionreturn True, None+def resolve_incremental_cursor(+ table_name: str,+ should_use_incremental_field: bool,+ field_name: Optional[str],+ field_type: Optional[IncrementalFieldType],+ last_value: Any,+) -> Optional[FirestoreIncrementalCursor]:+ """The cursor to read this table with, or None to read all of it.++ Only Firestore collections filter server-side. An incremental setting on any other table would+ otherwise read every row while the pipeline merged the result as if it were a delta.+ """+ if not should_use_incremental_field or _resolve_firestore_collection(table_name) is None:+ return None+ if not field_name or field_type is None:+ raise FirebaseConfigError(+ f"The table {table_name} is set to sync incrementally but has no field to sync on. "+ "Pick one in the table's sync settings, or switch the table to full refresh."+ )+ if field_type not in FIRESTORE_INCREMENTAL_VALUE_TYPES.values():+ raise FirebaseConfigError(+ f"Firestore can't sync on {field_name} because it isn't a timestamp or a number. "+ "Pick a different field in the table's sync settings, or switch the table to full refresh."+ )+ if not is_supported_incremental_field_name(field_name):+ raise FirebaseConfigError(+ f"Firestore can't sort on a field named {field_name}. It reads the dots and other punctuation "+ "in a field name as a path into a nested field. Pick a different field in the table's sync "+ "settings, or switch the table to full refresh."+ )+ if last_value is None:+ last_value = incremental_type_to_initial_value(field_type)+ return FirestoreIncrementalCursor(field_name=field_name, field_type=field_type, last_value=last_value)++def firebase_source(credentials: FirebaseCredentials,table_name: str,resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ incremental_field_name: Optional[str] = None,+ 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+ incremental_cursor = resolve_incremental_cursor(+ table_name,+ should_use_incremental_field,+ incremental_field_name,+ incremental_field_type,+ db_incremental_field_last_value,+ )if table_name == AUTH_USERS_TABLE:primary_keys = AUTH_USERS_PRIMARY_KEY@@ -637,11 +980,13 @@ def firebase_source(table_name=table_name,resumable_source_manager=resumable_source_manager,logger=logger,+ incremental_cursor=incremental_cursor,),primary_keys=primary_keys,- # Rows arrive ordered by document key, not by time, and no surface here filters on a- # timestamp, so there is no ascending watermark to declare.- sort_mode=None,+ # An incremental read is ordered by the cursor field, so the pipeline can advance the+ # watermark after every page. Every other read arrives ordered by document key, which is no+ # watermark at all, and declaring one would freeze the sync at the highest key it had seen.+ sort_mode="asc" if incremental_cursor is not None else None,# Firestore documents run to 1 MiB each, so chunks are capped tighter than the default.chunk_size=2000,chunk_size_bytes=100 * 1024 * 1024,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.pyindex e723df6ef42e..f8ee803fd941 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@@ -1,5 +1,8 @@+import refrom typing import Final+from products.warehouse_sources.backend.types import IncrementalFieldType+# Firestore and Identity Platform both expose a `v1` REST surface alongside older `v1beta*`# channels; `v1` is the generally available one.API_VERSION: Final[str] = "v1"@@ -34,6 +37,14 @@ REALTIME_DATABASE_PAGE_SIZE: Final[int] = 500# Hard stop so an endpoint that keeps handing back a page token can't page forever.MAX_PAGES: Final[int] = 100_000+# `get_incremental_fields` samples one collection at a time, synchronously, to build the cursor-field+# picker. The `names` filter already bounds this to the handful of tables a sync-settings request asks+# about, but a first-time "list every table" request passes every collection in the project, and+# `MAX_PAGES` lets that list run into the hundreds of thousands. Past this many collections, the+# remainder still gets listed as a table but is offered full refresh only, rather than tying up a+# worker sampling collections one HTTP request at a time.+FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT: Final[int] = 200+REQUEST_TIMEOUT_SECONDS: Final[int] = 120# Byte caps on response bodies. The page sizes above bound the row count but not the byte count —@@ -64,6 +75,9 @@ FIRESTORE_ID_COLUMN: Final[str] = "_firestore_id"FIRESTORE_PATH_COLUMN: Final[str] = "_firestore_path"FIRESTORE_CREATE_TIME_COLUMN: Final[str] = "_firestore_create_time"FIRESTORE_UPDATE_TIME_COLUMN: Final[str] = "_firestore_update_time"+FIRESTORE_METADATA_COLUMNS: Final[frozenset[str]] = frozenset(+ {FIRESTORE_ID_COLUMN, FIRESTORE_PATH_COLUMN, FIRESTORE_CREATE_TIME_COLUMN, FIRESTORE_UPDATE_TIME_COLUMN}+)REALTIME_DATABASE_KEY_COLUMN: Final[str] = "_realtime_database_key"REALTIME_DATABASE_PATH_COLUMN: Final[str] = "_realtime_database_path"@@ -72,6 +86,42 @@ REALTIME_DATABASE_VALUE_COLUMN: Final[str] = "value"AUTH_USERS_PRIMARY_KEY: Final[list[str]] = ["localId"]+# Firestore stores no schema, so the cursor fields a collection can offer are read off a sample of+# real documents. Ten is enough to reject a field that only some documents carry, while keeping+# discovery to one extra request per collection.+FIRESTORE_SCHEMA_SAMPLE_DOCUMENTS: Final[int] = 10++# Value types a Firestore field can hold and still order a collection, mapped to the cursor type the+# pipeline tracks. A field holding an ISO-8601 *string* is deliberately absent: Firestore compares+# strings byte by byte, and Firestore's own timestamps render with a variable number of fractional+# digits, so `2026-01-01T00:00:00Z` sorts after `2026-01-01T00:00:00.5Z` and rows get skipped.+FIRESTORE_INCREMENTAL_VALUE_TYPES: Final[dict[str, IncrementalFieldType]] = {+ "timestampValue": IncrementalFieldType.DateTime,+ "integerValue": IncrementalFieldType.Integer,+}++# Firestore orders values by type before value, so a lone `field > cursor` bound also matches every+# value that sorts above the cursor's type: strings, arrays, maps. An upper bound of the cursor's own+# type confines the read to one type band. Without it a collection whose field is a timestamp in most+# documents and a string in one would return that string on every run, and it would then become the+# watermark, which no later timestamp can beat.+# https://firebase.google.com/docs/firestore/manage-data/data-types+FIRESTORE_MAX_TIMESTAMP: Final[str] = "9999-12-31T23:59:59.999999999Z"+FIRESTORE_MAX_INTEGER: Final[int] = 2**63 - 1++# The reserved field path for a document's own id. Ordering by it after the cursor field keeps paging+# stable when several documents share one cursor value.+FIRESTORE_DOCUMENT_ID_FIELD: Final[str] = "__name__"++# A field path segment Firestore reads without backtick quoting. A document field name may hold dots+# and other punctuation, which a field path would read as a path into a nested map, so a field whose+# name needs quoting is never offered as a cursor rather than risking a read of the wrong field.+_UNQUOTED_FIELD_PATH = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")++# Firestore answers a query it holds no index for with FAILED_PRECONDITION and a console URL that+# builds the index in one click. Building it takes minutes, so no retry recovers within a job.+FIRESTORE_INDEX_REQUIRED_ERROR: Final[str] = "The query requires an index"+# Password material Identity Platform returns to sufficiently privileged callers. Warehousing a# password hash serves no analytics purpose, so it never leaves the source.REDACTED_AUTH_USER_FIELDS: Final[frozenset[str]] = frozenset({"passwordHash", "salt", "rawPassword"})@@ -85,6 +135,10 @@ def firestore_table_name(collection_id: str) -> str:return f"{FIRESTORE_TABLE_PREFIX}{collection_id}"+def is_supported_incremental_field_name(name: str) -> bool:+ return bool(_UNQUOTED_FIELD_PATH.match(name))++def realtime_database_table_name(path: str) -> str:"""Table name for one Realtime Database path. `rooms/lobby` becomes `..._rooms_lobby`."""return f"{REALTIME_DATABASE_TABLE_PREFIX}{path.strip('/').replace('/', '_')}"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.pyindex 22bf5243badf..dd9b09dba0ba 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@@ -23,12 +23,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.fFirebaseCredentials,FirebaseResumeConfig,firebase_source,+ get_incremental_fields,get_tables,validate_credentials as validate_firebase_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (API_VERSION,DEFAULT_DATABASE_ID,+ FIRESTORE_INDEX_REQUIRED_ERROR,RESPONSE_TOO_LARGE_ERROR,parse_realtime_database_paths,)@@ -66,6 +68,11 @@ class FirebaseSource(ResumableSource[FirebaseSourceConfig, FirebaseResumeConfig]"401 Client Error: Unauthorized": "Firebase rejected the access token. The service account key may have been revoked — please reconnect.","403 Client Error: Forbidden": "This service account cannot read the requested Firebase data. Grant it the Firebase Viewer, Cloud Datastore Viewer, or Firebase Realtime Database Viewer role.",RESPONSE_TOO_LARGE_ERROR: "Firebase returned a page too large to process. Reduce the size of the documents in this collection or path, then re-run the sync.",+ # Firestore indexes every field on its own by default, so this only appears once someone+ # exempts the chosen field from indexing. Google's message carries a console link that+ # builds the index in one click, and no message of ours beats that, so it passes through+ # unchanged. Building the index takes minutes, which outlasts every retry.+ FIRESTORE_INDEX_REQUIRED_ERROR: None,# Identity Toolkit's `accounts:batchGet` rejects every request this way when the project# has no Firebase Authentication configuration at all — retrying can't create one."message=CONFIGURATION_NOT_FOUND": "This Firebase project doesn't have Firebase Authentication enabled, so PostHog can't read its Auth users. Enable Firebase Authentication in the Firebase console, or remove the Auth users table from this source.",@@ -141,13 +148,25 @@ Create a service account key in the Firebase console under Project settings, Serapi_version: str | None = None,) -> list[SourceSchema]:# Firestore collections are created by the customer's app, so the table list can only come- # from the live project. Nothing here supports a server-side timestamp filter, so every- # table is full refresh.- tables = get_tables(self._credentials(config))+ # from the live project.+ credentials = self._credentials(config)+ tables = get_tables(credentials)if names is not None:wanted = set(names)tables = [table for table in tables if table in wanted]- return [SourceSchema(name=table, supports_incremental=False, supports_append=False) for table in tables]++ # Costs one request per Firestore collection, so it stays behind the `names` filter above:+ # the sync settings for one table ask for that table alone.+ incremental_fields = get_incremental_fields(credentials, tables)+ return [+ SourceSchema(+ name=table,+ supports_incremental=bool(incremental_fields.get(table)),+ supports_append=bool(incremental_fields.get(table)),+ incremental_fields=incremental_fields.get(table, []),+ )+ for table in tables+ ]def _credentials(self, config: FirebaseSourceConfig) -> FirebaseCredentials:database_id = (config.database_id or "").strip() or DEFAULT_DATABASE_ID@@ -185,4 +204,8 @@ Create a service account key in the Firebase console under Project settings, Sertable_name=inputs.schema_name,resumable_source_manager=resumable_source_manager,logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ incremental_field_name=inputs.incremental_field,+ incremental_field_type=inputs.incremental_field_type,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)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.pyindex c26c7c17ae58..b668a60313ce 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,4 +1,5 @@import json+import datetimefrom typing import Any, Optionalimport pytest@@ -14,26 +15,35 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.fFirebaseConfigError,FirebaseResponseTooLargeError,FirebaseResumeConfig,+ FirestoreIncrementalCursor,build_jwt_assertion,decode_firestore_value,firebase_source,flatten_auth_user,flatten_firestore_document,flatten_realtime_database_child,+ get_incremental_fields,get_rows,get_tables,iter_auth_users,iter_firestore_documents,+ iter_firestore_documents_incremental,iter_realtime_database,list_collection_ids,mint_access_token,+ resolve_incremental_cursor,+ sample_firestore_incremental_fields,validate_credentials,validate_realtime_database_url,)from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (AUTH_USERS_TABLE,FIRESTORE_CREATE_TIME_COLUMN,+ FIRESTORE_DOCUMENT_ID_FIELD,FIRESTORE_ID_COLUMN,+ FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT,+ FIRESTORE_MAX_INTEGER,+ FIRESTORE_MAX_TIMESTAMP,FIRESTORE_PATH_COLUMN,FIRESTORE_UPDATE_TIME_COLUMN,GOOGLE_TOKEN_URI,@@ -53,6 +63,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.tFakeSession,credentials,)+from products.warehouse_sources.backend.types import IncrementalFieldType_FIREBASE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase"_SESSION_FACTORY = f"{_FIREBASE_MODULE}.make_tracked_session"@@ -315,6 +326,31 @@ class TestFirestorePagination:assert session.requests[0][2]["params"]["pageToken"] == "page-9"+ def test_an_incremental_checkpoint_is_not_read_as_a_page_token(self, logger: FilteringBoundLogger) -> None:+ # An incremental checkpoint stores a document name, which `listDocuments` would reject as a+ # page token, failing the same way on every retry.+ session = FakeSession(+ request_responses=[FakeResponse(payload={"documents": [firestore_document("a")]})],+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],+ )+ saved = FirebaseResumeConfig(+ cursor="projects/demo-project/databases/(default)/documents/rooms/d42",+ incremental_value='{"timestampValue": "2026-02-01T00:00:42Z"}',+ )++ list(+ iter_firestore_documents(+ session.as_session(),+ token_provider(session),+ credentials(),+ "rooms",+ FakeResumeManager(saved),+ logger,+ )+ )++ assert "pageToken" not in session.requests[0][2]["params"]+def test_a_resume_marker_with_no_state_behind_it_starts_from_the_beginning(self, logger: FilteringBoundLogger) -> None:@@ -369,6 +405,366 @@ class TestFirestorePagination:assert session.requests[1][2]["json"]["pageToken"] == "next"+def timestamped_document(document_id: str, moment: str, extra: Optional[dict[str, Any]] = None) -> dict[str, Any]:+ fields: dict[str, Any] = {"updatedOn": {"timestampValue": moment}}+ fields.update(extra or {})+ return firestore_document(document_id, fields)+++def run_query_page(documents: list[dict[str, Any]]) -> FakeResponse:+ # `runQuery` streams a JSON array whose entries each hold at most one document.+ return FakeResponse(payload=[{"document": document} for document in documents])+++def incremental_cursor(**overrides: Any) -> FirestoreIncrementalCursor:+ defaults: dict[str, Any] = {+ "field_name": "updatedOn",+ "field_type": IncrementalFieldType.DateTime,+ "last_value": datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.UTC),+ }+ defaults.update(overrides)+ return FirestoreIncrementalCursor(**defaults)+++def read_incremental(+ session: FakeSession,+ logger: FilteringBoundLogger,+ manager: Optional[FakeResumeManager] = None,+ cursor: Optional[FirestoreIncrementalCursor] = None,+) -> list[dict[str, Any]]:+ resolved = cursor or incremental_cursor()+ batches = iter_firestore_documents_incremental(+ session.as_session(),+ token_provider(session),+ credentials(),+ "rooms",+ resolved.field_name,+ resolved.field_type,+ resolved.last_value,+ manager or FakeResumeManager(),+ logger,+ )+ return [row for batch in batches for row in batch]+++class TestFirestoreIncrementalReads:+ def test_query_bounds_the_read_to_the_cursor_fields_own_type(self, logger: FilteringBoundLogger) -> None:+ # Firestore orders across types, so the lower bound alone also matches strings, arrays and+ # maps stored in the same field. Those rows can't be ordered and their values would become a+ # watermark no later timestamp can beat, so the upper bound is what keeps the read sane.+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(session, logger)++ method, url, kwargs = session.requests[0]+ query = kwargs["json"]["structuredQuery"]+ assert (method, url) == ("POST", f"{DOCUMENTS_ROOT}:runQuery")+ assert query["where"]["compositeFilter"]["filters"] == [+ {+ "fieldFilter": {+ "field": {"fieldPath": "updatedOn"},+ "op": "GREATER_THAN",+ "value": {"timestampValue": "2026-01-02T03:04:05Z"},+ }+ },+ {+ "fieldFilter": {+ "field": {"fieldPath": "updatedOn"},+ "op": "LESS_THAN_OR_EQUAL",+ "value": {"timestampValue": FIRESTORE_MAX_TIMESTAMP},+ }+ },+ ]+ # Documents that share a cursor value need the document id to break the tie, or paging past+ # them drops whichever ones the first page didn't reach.+ assert query["orderBy"] == [+ {"field": {"fieldPath": "updatedOn"}, "direction": "ASCENDING"},+ {"field": {"fieldPath": FIRESTORE_DOCUMENT_ID_FIELD}, "direction": "ASCENDING"},+ ]+ assert "startAt" not in query++ def test_integer_cursor_is_sent_as_a_json_string(self, logger: FilteringBoundLogger) -> None:+ # The REST API rejects a bare JSON number for integerValue.+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(+ session,+ logger,+ cursor=incremental_cursor(field_name="version", field_type=IncrementalFieldType.Integer, last_value=42),+ )++ assert [+ fltr["fieldFilter"]["value"]+ for fltr in session.requests[0][2]["json"]["structuredQuery"]["where"]["compositeFilter"]["filters"]+ ] == [{"integerValue": "42"}, {"integerValue": str(FIRESTORE_MAX_INTEGER)}]++ def test_a_fractional_watermark_on_an_integer_cursor_is_not_truncated(self, logger: FilteringBoundLogger) -> None:+ # Firestore orders integers and doubles together, so a field sampled as an integer can still+ # carry a doubleValue on some document. int() truncating that watermark down would leave the+ # fractional row above the lower bound, and it would be re-imported on every later run.+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(+ session,+ logger,+ cursor=incremental_cursor(field_name="version", field_type=IncrementalFieldType.Integer, last_value=42.5),+ )++ filters = session.requests[0][2]["json"]["structuredQuery"]["where"]["compositeFilter"]["filters"]+ assert filters[0]["fieldFilter"]["value"] == {"doubleValue": 42.5}++ def test_a_whole_number_float_watermark_on_an_integer_cursor_is_sent_as_an_integer(+ self, logger: FilteringBoundLogger+ ) -> None:+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(+ session,+ logger,+ cursor=incremental_cursor(field_name="version", field_type=IncrementalFieldType.Integer, last_value=42.0),+ )++ filters = session.requests[0][2]["json"]["structuredQuery"]["where"]["compositeFilter"]["filters"]+ assert filters[0]["fieldFilter"]["value"] == {"integerValue": "42"}++ @pytest.mark.parametrize(+ "last_value,expected",+ [+ (datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.UTC), "2026-01-02T03:04:05Z"),+ (datetime.datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),+ (+ datetime.datetime(2026, 1, 2, 3, 4, 5, tzinfo=datetime.timezone(datetime.timedelta(hours=2))),+ "2026-01-02T01:04:05Z",+ ),+ (datetime.datetime(2026, 1, 2, 3, 4, 5, 123456, tzinfo=datetime.UTC), "2026-01-02T03:04:05.123456Z"),+ (1767322800, "2026-01-02T03:00:00Z"),+ ],+ ids=["utc", "naive", "offset", "microseconds", "epoch"],+ )+ def test_watermark_is_rendered_as_the_utc_rfc3339_firestore_expects(+ self, logger: FilteringBoundLogger, last_value: Any, expected: str+ ) -> None:+ # Firestore rejects a timestamp with no zone, and reads one with the wrong zone as a+ # different instant, which silently re-reads or skips hours of documents.+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(session, logger, cursor=incremental_cursor(last_value=last_value))++ filters = session.requests[0][2]["json"]["structuredQuery"]["where"]["compositeFilter"]["filters"]+ assert filters[0]["fieldFilter"]["value"] == {"timestampValue": expected}++ def test_pages_from_the_last_row_and_checkpoints_after_each_yield(self, logger: FilteringBoundLogger) -> None:+ # `runQuery` returns no page token, so a page that doesn't resume from the previous page's+ # last row re-reads the same documents until MAX_PAGES.+ full_page = [+ timestamped_document(f"d{index}", f"2026-02-01T00:{index // 60:02d}:{index % 60:02d}Z")+ for index in range(300)+ ]+ session = FakeSession(+ request_responses=[+ run_query_page(full_page),+ run_query_page([timestamped_document("last", "2026-03-01T00:00:00Z")]),+ ],+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],+ )+ manager = FakeResumeManager()++ rows = read_incremental(session, logger, manager)++ assert [row[FIRESTORE_ID_COLUMN] for row in rows] == [*(f"d{index}" for index in range(300)), "last"]+ assert session.requests[1][2]["json"]["structuredQuery"]["startAt"] == {+ "values": [+ {"timestampValue": "2026-02-01T00:04:59Z"},+ {"referenceValue": f"projects/demo-project/databases/(default)/documents/rooms/d299"},+ ],+ # Inclusive would re-yield the boundary row on every page.+ "before": False,+ }+ assert [(state.cursor, state.incremental_value) for state in manager.saved] == [+ (+ "projects/demo-project/databases/(default)/documents/rooms/d299",+ '{"timestampValue": "2026-02-01T00:04:59Z"}',+ )+ ]+ assert manager.cleared is True++ def test_resumes_mid_collection_from_the_saved_position(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )+ saved = FirebaseResumeConfig(+ cursor="projects/demo-project/databases/(default)/documents/rooms/d42",+ incremental_value='{"timestampValue": "2026-02-01T00:00:42Z"}',+ )++ read_incremental(session, logger, FakeResumeManager(saved))++ assert session.requests[0][2]["json"]["structuredQuery"]["startAt"] == {+ "values": [+ {"timestampValue": "2026-02-01T00:00:42Z"},+ {"referenceValue": "projects/demo-project/databases/(default)/documents/rooms/d42"},+ ],+ "before": False,+ }++ def test_a_full_refresh_checkpoint_is_not_read_as_a_position(self, logger: FilteringBoundLogger) -> None:+ # A full-refresh read of the same collection checkpoints a `listDocuments` page token, which+ # names no document. Feeding it to an ordered query would make Firestore reject every page.+ session = FakeSession(+ request_responses=[run_query_page([])], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]+ )++ read_incremental(session, logger, FakeResumeManager(FirebaseResumeConfig(cursor="page-9")))++ assert "startAt" not in session.requests[0][2]["json"]["structuredQuery"]++ def test_stream_entries_carrying_no_document_are_skipped(self, logger: FilteringBoundLogger) -> None:+ # Firestore reports read progress with entries that hold only a readTime.+ session = FakeSession(+ request_responses=[+ FakeResponse(+ payload=[+ {"readTime": "2026-03-01T00:00:00Z"},+ {"document": timestamped_document("a", "2026-02-01T00:00:00Z")},+ ]+ )+ ],+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],+ )++ assert [row[FIRESTORE_ID_COLUMN] for row in read_incremental(session, logger)] == ["a"]+++class TestFirestoreIncrementalFieldDiscovery:+ @pytest.mark.parametrize(+ "documents,expected",+ [+ (+ [{"updatedOn": {"timestampValue": "2026-01-01T00:00:00Z"}}] * 2,+ [("updatedOn", IncrementalFieldType.DateTime)],+ ),+ (+ [{"version": {"integerValue": "1"}}, {"version": {"integerValue": "2"}}],+ [("version", IncrementalFieldType.Integer)],+ ),+ # Firestore drops a document from an ordered read when the ordered field is missing, so+ # a field only part of the collection sets would strand the rest of it permanently.+ (+ [{"updatedOn": {"timestampValue": "2026-01-01T00:00:00Z"}}, {"title": {"stringValue": "x"}}],+ [],+ ),+ # The same name holding two types cannot order the collection either.+ (+ [{"updatedOn": {"timestampValue": "2026-01-01T00:00:00Z"}}, {"updatedOn": {"integerValue": "1"}}],+ [],+ ),+ # An ISO-8601 string compares byte by byte, which orders "…:00Z" after "…:00.5Z".+ ([{"updatedOn": {"stringValue": "2026-01-01T00:00:00Z"}}] * 2, []),+ # Firestore would read the dot as a path into a nested field, so this reads a field that+ # isn't the one the user picked.+ ([{"updated.on": {"timestampValue": "2026-01-01T00:00:00Z"}}] * 2, []),+ # The flattened row overwrites this name with the document's own update time, so the+ # watermark would track the metadata while the query filtered the document field.+ ([{FIRESTORE_UPDATE_TIME_COLUMN: {"timestampValue": "2026-01-01T00:00:00Z"}}] * 2, []),+ ],+ ids=[+ "timestamp",+ "integer",+ "missing-from-one",+ "type-changes",+ "iso-string",+ "dotted-name",+ "shadowed-by-metadata",+ ],+ )+ def test_only_fields_that_can_order_the_whole_collection_are_offered(+ self, documents: list[dict[str, Any]], expected: list[tuple[str, Any]]+ ) -> None:+ session = FakeSession(+ request_responses=[+ FakeResponse(+ payload={+ "documents": [firestore_document(f"d{index}", fields) for index, fields in enumerate(documents)]+ }+ )+ ],+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],+ )++ found = sample_firestore_incremental_fields(+ session.as_session(), token_provider(session), credentials(), "rooms"+ )++ assert [(field["field"], field["field_type"]) for field in found] == expected++ def test_an_update_tracking_field_is_offered_ahead_of_a_creation_only_one(self) -> None:+ # Several surfaces default to the first candidate, and a created_at cursor never re-reads a+ # row that was edited after it was written.+ session = FakeSession(+ request_responses=[+ FakeResponse(+ payload={+ "documents": [+ firestore_document(+ "a",+ {+ "created_at": {"timestampValue": "2026-01-01T00:00:00Z"},+ "updated_at": {"timestampValue": "2026-01-02T00:00:00Z"},+ },+ )+ ]+ }+ )+ ],+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],+ )++ found = sample_firestore_incremental_fields(+ session.as_session(), token_provider(session), credentials(), "rooms"+ )++ assert [field["field"] for field in found] == ["updated_at", "created_at"]++ def test_a_collection_that_cannot_be_read_leaves_the_other_tables_discoverable(self) -> None:+ # One collection the service account can't read must not empty the whole schema picker.+ responses = [+ FakeResponse(status_code=403, payload={"error": {"status": "PERMISSION_DENIED"}}),+ FakeResponse(payload={"documents": [timestamped_document("a", "2026-01-01T00:00:00Z")]}),+ ]+ with mock.patch(_SESSION_FACTORY, return_value=FakeSession(responses, [FakeResponse(payload=TOKEN_PAYLOAD)])):+ found = get_incremental_fields(credentials(), ["firestore_secrets", "firestore_rooms", AUTH_USERS_TABLE])++ assert list(found) == ["firestore_rooms"]++ def test_a_list_every_table_request_samples_only_up_to_the_discovery_limit(self) -> None:+ # A sync-settings request for one table never reaches this: it passes `table_names=[that+ # table]`, well under the limit. Only a "list every table" request against a project with an+ # unusually large number of collections can hit it, and that request must not turn into one+ # synchronous HTTP call per collection with no upper bound.+ table_count = FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT + 1+ tables = [f"firestore_c{index}" for index in range(table_count)]+ responses = [+ FakeResponse(payload={"documents": [timestamped_document("a", "2026-01-01T00:00:00Z")]})+ for _ in range(table_count)+ ]+ session = FakeSession(responses, [FakeResponse(payload=TOKEN_PAYLOAD)])+ with mock.patch(_SESSION_FACTORY, return_value=session):+ found = get_incremental_fields(credentials(), tables)++ assert len(session.requests) == FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT+ assert list(found) == tables[:FIRESTORE_INCREMENTAL_DISCOVERY_LIMIT]++class TestAuthUsersPagination:def test_stops_when_google_returns_no_token(self, logger: FilteringBoundLogger) -> None:session = FakeSession(@@ -782,6 +1178,66 @@ class TestSourceResponseShape:with pytest.raises(FirebaseConfigError, match="not configured"):list(get_rows(credentials(), "made_up_table", FakeResumeManager(), logger))+ @pytest.mark.parametrize(+ "should_use_incremental_field,expected_sort_mode",+ [(True, "asc"), (False, None)],+ ids=["incremental", "full-refresh"],+ )+ def test_only_an_ordered_read_declares_a_sort_mode(+ self, logger: FilteringBoundLogger, should_use_incremental_field: bool, expected_sort_mode: Optional[str]+ ) -> None:+ # The pipeline persists the watermark only for a sorted resource, so `None` here means an+ # incremental sync re-reads the whole collection every run. Declaring "asc" for an unsorted+ # read is worse: the watermark jumps to the highest value any batch happened to carry.+ response = firebase_source(+ credentials(),+ "firestore_rooms",+ FakeResumeManager(),+ logger,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field_name="updatedOn",+ incremental_field_type=IncrementalFieldType.DateTime,+ db_incremental_field_last_value=datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC),+ )++ assert response.sort_mode == expected_sort_mode++ def test_a_table_with_no_server_side_filter_is_never_read_incrementally(self) -> None:+ # Auth users and Realtime Database paths page on a key and expose no timestamp filter. If a+ # stale schema row still asks for incremental, reading everything while the pipeline merges+ # it as a delta would strand every row below the watermark.+ assert (+ resolve_incremental_cursor(+ AUTH_USERS_TABLE, True, "createdAt", IncrementalFieldType.DateTime, last_value=None+ )+ is None+ )++ def test_a_collection_with_no_watermark_yet_reads_from_the_epoch(self) -> None:+ cursor = resolve_incremental_cursor(+ "firestore_rooms", True, "updatedOn", IncrementalFieldType.DateTime, last_value=None+ )++ assert cursor is not None+ assert cursor.last_value == datetime.datetime(1970, 1, 1, tzinfo=datetime.UTC)++ @pytest.mark.parametrize(+ "field_name,field_type,message",+ [+ (None, None, "no field to sync on"),+ ("title", IncrementalFieldType.ObjectID, "isn't a timestamp or a number"),+ ("updated.on", IncrementalFieldType.DateTime, "can't sort on a field named"),+ ],+ ids=["no-field", "unorderable-type", "dotted-name"],+ )+ def test_a_cursor_firestore_cannot_order_on_is_refused_with_the_fix(+ self, field_name: Optional[str], field_type: Optional[IncrementalFieldType], message: str+ ) -> None:+ # Each of these would otherwise reach Firestore as a query it answers with a bare 400, or as+ # a read of a nested field the user never picked.+ with pytest.raises(FirebaseConfigError, match=message):+ resolve_incremental_cursor("firestore_rooms", True, field_name, field_type, last_value=None)+class TestCredentialValidation:def test_valid_key_mints_a_token(self) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.pyindex 5933bdedba50..4045b0f3a921 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py@@ -4,6 +4,7 @@ from unittest import mockimport structlog+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import AUTH_USERS_TABLEfrom products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source import FirebaseSource@@ -11,11 +12,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_FirebaseKeyFileConfig,FirebaseSourceConfig,)+from products.warehouse_sources.backend.types import IncrementalFieldType_GET_TABLES = "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source.get_tables"+_GET_INCREMENTAL_FIELDS = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source.get_incremental_fields"+)_VALIDATE = ("products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source.validate_firebase_credentials")+_UPDATED_ON = incremental_field("updatedOn", IncrementalFieldType.DateTime)def firebase_config(**overrides: Any) -> FirebaseSourceConfig:@@ -66,18 +72,29 @@ class TestFirebaseSource:"realtime_database_paths",]- def test_get_schemas_lists_discovered_tables_as_full_refresh(self) -> None:- with mock.patch(_GET_TABLES, return_value=[AUTH_USERS_TABLE, "firestore_rooms"]):- schemas = self.source.get_schemas(firebase_config(), team_id=1)-- assert [schema.name for schema in schemas] == [AUTH_USERS_TABLE, "firestore_rooms"]- assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)-- def test_get_schemas_honors_the_name_filter(self) -> None:+ def test_get_schemas_offers_incremental_only_where_a_cursor_field_was_found(self) -> None:+ # Advertising incremental on a table with no usable cursor field lets the pipeline merge a+ # full read as if it were a delta, and the sync then fails at query time instead of at setup.+ with mock.patch(_GET_TABLES, return_value=[AUTH_USERS_TABLE, "firestore_rooms", "firestore_logs"]):+ with mock.patch(_GET_INCREMENTAL_FIELDS, return_value={"firestore_rooms": [_UPDATED_ON]}):+ schemas = self.source.get_schemas(firebase_config(), team_id=1)++ assert {schema.name: schema.supports_incremental for schema in schemas} == {+ AUTH_USERS_TABLE: False,+ "firestore_rooms": True,+ "firestore_logs": False,+ }+ assert [schema.incremental_fields for schema in schemas if schema.name == "firestore_rooms"] == [[_UPDATED_ON]]++ def test_get_schemas_samples_only_the_tables_it_was_asked_for(self) -> None:+ # Discovery costs one request per Firestore collection, and the sync settings for one table+ # ask for that table alone.with mock.patch(_GET_TABLES, return_value=[AUTH_USERS_TABLE, "firestore_rooms"]):- schemas = self.source.get_schemas(firebase_config(), team_id=1, names=["firestore_rooms"])+ with mock.patch(_GET_INCREMENTAL_FIELDS, return_value={}) as discover:+ schemas = self.source.get_schemas(firebase_config(), team_id=1, names=["firestore_rooms"])assert [schema.name for schema in schemas] == ["firestore_rooms"]+ assert discover.call_args.args[1] == ["firestore_rooms"]def test_source_for_pipeline_syncs_the_requested_table(self) -> None:manager = self.source.get_resumable_source_manager(source_inputs("firestore_rooms"))