Skip to content

Feat/mongodb data validator [DRAFT] - #4587

Open
suryansh29 wants to merge 4 commits into
GoogleCloudPlatform:mainfrom
suryansh29:feat/mongodb-data-validator
Open

suryansh29 wants to merge 4 commits into
GoogleCloudPlatform:mainfrom
suryansh29:feat/mongodb-data-validator

Conversation

@suryansh29

Copy link
Copy Markdown

No description provided.

Suryansh Sharma and others added 2 commits November 19, 2026 09:44
…n template

Adds the Mongodb_To_Firestore_Data_Validator batch Flex Template, which
compares a source MongoDB database against a target Firestore with MongoDB
compatibility database and reports the differences.

- Diffs collections and index definitions before reading documents.
- Splits each collection into _id ranges and compares source and target
  with ordered cursors, resuming a cursor from the last _id on transient
  errors or cursor expiry.
- Re-reads candidate mismatches from the source primary and the target
  after a delay, so replication lag is not reported as a mismatch.
- Writes a run summary, per-collection stats and mismatch rows to GCS,
  and optionally to BigQuery.
@google-cla

google-cla Bot commented Nov 19, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@suryansh29 suryansh29 changed the title Feat/mongodb data validator Feat/mongodb data validator [DRAFT] Nov 19, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new Dataflow Flex Template designed to validate data parity between a source MongoDB cluster and a target Cloud Firestore database. The solution leverages a high-performance, zero-shuffle merge-join architecture to compare document counts and BSON field values at scale. It includes robust features for handling replication lag via delayed rechecks, automatic cursor recovery, and comprehensive reporting to both Cloud Storage and BigQuery.

Highlights

  • New Data Validator Template: Added a new Dataflow Flex Template 'Mongodb_To_Firestore_Data_Validator' to perform comprehensive data parity validation between MongoDB and Cloud Firestore.
  • Zero-Shuffle Merge-Join: Implemented a co-partitioned merge-join strategy that processes sorted _id ranges in lockstep, enabling efficient counting of billions of documents in-memory.
  • Resilient Data Validation: Added automatic cursor resumption and delayed primary rechecks to handle transient network issues and CDC replication lag, ensuring accurate validation results.
  • Strict BSON Fidelity: Introduced a deep BSON comparator that enforces strict type checking, subdocument key ordering, and handles complex BSON types like Decimal128 and Binary subtypes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 the mongodb-data-validator module, a Google Cloud Dataflow Flex Template designed to validate collection catalogs, secondary indexes, document counts, and deep BSON field-by-field parity between a source MongoDB cluster and a target Cloud Firestore database. Key components include zero-shuffle co-partitioned merge-joins, automatic cursor resumption, live-CDC lag tolerance via delayed rechecks, and strict BSON fidelity comparators. The code review feedback highlights three main improvement opportunities: reversing the configuration order in MongoClientManager to preserve user-specified UUID representations, using BigDecimal.valueOf(d) instead of new BigDecimal(d) in BsonOrderComparator to prevent floating-point precision issues, and removing a redundant JSON parsing step in BsonEncodingUtils to optimize performance.

Comment on lines +68 to +71
MongoClientSettings.Builder builder =
MongoClientSettings.builder()
.applyConnectionString(connString)
.uuidRepresentation(UuidRepresentation.STANDARD)

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.

high

The current builder configuration applies the connection string first and then unconditionally sets the UUID representation to UuidRepresentation.STANDARD. This order of operations will overwrite any custom uuidRepresentation specified by the user in their connection URI (e.g., uuidRepresentation=javaLegacy or uuidRepresentation=cSharpLegacy), which is a common requirement for legacy MongoDB databases. Reversing the order allows the connection string configuration to correctly override the default standard representation.

Suggested change
MongoClientSettings.Builder builder =
MongoClientSettings.builder()
.applyConnectionString(connString)
.uuidRepresentation(UuidRepresentation.STANDARD)
MongoClientSettings.Builder builder =
MongoClientSettings.builder()
.uuidRepresentation(UuidRepresentation.STANDARD)
.applyConnectionString(connString)

Comment on lines +237 to +239
case DOUBLE:
double d = v.asDouble().getValue();
return d == 0.0d ? BigDecimal.ZERO : new BigDecimal(d);

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.

high

Using new BigDecimal(d) for DOUBLE values introduces floating-point precision issues (for example, new BigDecimal(0.1) is not exactly 0.1). This can cause inconsistent comparisons and incorrect sorting order when comparing Double and Decimal128 values, leading to false mismatches or incorrect cursor advancement in the sorted merge-join. Using BigDecimal.valueOf(d) ensures the exact decimal representation is used, matching how BsonDocumentComparator handles double values.

Suggested change
case DOUBLE:
double d = v.asDouble().getValue();
return d == 0.0d ? BigDecimal.ZERO : new BigDecimal(d);
case DOUBLE:
double d = v.asDouble().getValue();
return d == 0.0d ? BigDecimal.ZERO : BigDecimal.valueOf(d);

Comment on lines +64 to +78
/** Renders a {@link BsonValue} as canonical Extended JSON (e.g. {@code {"$oid": "..."}}). */
public static String toExtendedJson(BsonValue idValue) {
if (idValue == null) {
return "null";
}
BsonDocument wrapper = new BsonDocument("_id", idValue);
String fullJson = wrapper.toJson(EXTENDED_JSON);
BsonDocument parsed = BsonDocument.parse(fullJson);
// Extract just the canonical value representation when possible
int colonIdx = fullJson.indexOf(':');
int endBrace = fullJson.lastIndexOf('}');
if (colonIdx > 0 && endBrace > colonIdx && parsed.containsKey("_id")) {
return fullJson.substring(colonIdx + 1, endBrace).trim();
}
return fullJson;

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

Parsing the generated JSON string back into a BsonDocument via BsonDocument.parse(fullJson) is highly redundant and inefficient. Since wrapper is explicitly created with _id as its only key, parsed.containsKey("_id") is guaranteed to be true. Removing this parsing step avoids significant CPU and memory overhead on a hot path.

  public static String toExtendedJson(BsonValue idValue) {
    if (idValue == null) {
      return "null";
    }
    BsonDocument wrapper = new BsonDocument("_id", idValue);
    String fullJson = wrapper.toJson(EXTENDED_JSON);
    // Extract just the canonical value representation when possible
    int colonIdx = fullJson.indexOf(':');
    int endBrace = fullJson.lastIndexOf('}');
    if (colonIdx > 0 && endBrace > colonIdx) {
      return fullJson.substring(colonIdx + 1, endBrace).trim();
    }
    return fullJson;
  }

Suryansh Sharma added 2 commits November 20, 2026 13:52
…l Pass-2 skip and $sample-first partitioning

- Adopt $sample-first empirical quantile partitioning (omitting $type on single-type collections to avoid Ignite $type probe timeouts)
- Add bounded concurrency slots via ValidationSlotTask (--maxConcurrentReads, default 128)
- Default --comparisonStrategy to BATCH_LOOKUP (batched _id $in lookups, batchSize=1000) with ConditionalReverseOrphanFn skipping Pass 2 when targetCount == foundInTarget
- Remove live-CDC RecheckMismatchesFn and resolved_on_recheck_count fields
- Add unit tests covering $sample-first splitting and conditional Pass-2 skip/execution (16/16 passing, 0 Checkstyle violations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant