Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-migration-validator@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin bigquery-migration-validator v1.0.0 follows the Agent Plugins spec.
gh skills-hub install bigquery-migration-validator Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/bigquery-migration-validator/ Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-migration-validator for Copilot to auto-discover it.
Skill Files (10)
SKILL.md 16.8 KB
---
name: bigquery-migration-validator
metadata:
version: "1.0.0"
category: BigDataAndAnalytics
publisher: google
description: >-
Validates that tables migrated to BigQuery match their source (Teradata,
Snowflake, Oracle, Redshift, Databricks, PostgreSQL, SQL Server, MySQL,
MariaDB, Hive, Impala, Vertica) with the BigQuery Migration Service (BQMS)
validation tool: schema and data type comparison, column aggregate
comparison, and row-level data comparison. Use when generating or editing a
validation config, running a validation, choosing sampling or partitioning,
fixing connection or driver errors, or investigating validation results in
BigQuery and Cloud Storage to decide which mismatches to fix. Don't use for
SQL translation (use bigquery-migration-sql-translator), extracting source
database catalog metadata or query logs, generating SQL scripts (such as COPY
INTO) or exporting or unloading source tables to Parquet on Cloud Storage,
loading staged files into BigQuery (such as bq load), or general BigQuery
query failures and tuning (use bigquery-troubleshooting or
bigquery-optimization).
---
# BigQuery Migration Validator
The validation tool compares a source table with its migrated BigQuery table. It
runs in two halves:
1. **Client (this machine)**: Reads the config, queries the source database,
and stages a row sample, source aggregates, and run metadata in Cloud
Storage. It then starts a BigQuery Migration workflow for each table and
exits.
2. **Backend (Google Cloud, asynchronous)**: Loads the staged sample into
BigQuery, compares it with the target table, and writes the results to
BigQuery and Cloud Storage.
Results do not exist when the command exits. Wait for the workflow to finish
before reading them (Section 4).
## Usage attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Before you begin
1. **Google Cloud CLI and project**: Ensure the
[Google Cloud CLI][gcloud_install] is installed, verify that the Google
Cloud project has an active Cloud Billing account, and configure the target
project (check regional service availability at
[Google Cloud locations][cloud_locations] when choosing `--location` for
validation workflows):
```bash
gcloud config set project PROJECT_ID
```
2. **Enable the APIs** (ask the user before enabling APIs): BigQuery
(`bigquery.googleapis.com`), BigQuery Migration
(`bigquerymigration.googleapis.com`), Cloud Storage
(`storage.googleapis.com`), and Secret Manager
(`secretmanager.googleapis.com`, when reading source passwords from Secret
Manager):
```bash
gcloud services enable \
bigquery.googleapis.com \
bigquerymigration.googleapis.com \
storage.googleapis.com
# Only when source passwords come from Secret Manager:
gcloud services enable secretmanager.googleapis.com
```
3. **Local runtime, authentication, and IAM permissions** (ask before
installing software):
* **Runtime and drivers**: Java 11 or later (JRE 11+) first on `PATH`, the
`bqms` gcloud component (installed on first use or with
`gcloud components install bqms`), local network access to the source
database, and vendor JDBC driver JARs for Teradata (`terajdbc4.jar`),
Vertica (`vertica-jdbc.jar`), Impala, and DuckDB in `./drivers` or
`BQMS_DRIVER_DIR` when required (other JDBC drivers download on first
use; see [connections and drivers](references/connections.md)).
* **Google Cloud credentials and IAM**: Authenticate the Google Cloud CLI
and Application Default Credentials with `gcloud auth login` and
`gcloud auth application-default login` (or set
`GOOGLE_APPLICATION_CREDENTIALS` for a service account). The identity
needs write access to the staging Cloud Storage bucket
(`roles/storage.objectAdmin`), permission to create BigQuery Migration
workflows (`roles/bigquerymigration.editor`), and permission to run
BigQuery jobs and write validation results in the target project and,
if set, the `results.projectId` project (`roles/bigquery.dataEditor`
and `roles/bigquery.jobUser`). With Secret Manager passwords, it also
needs `roles/secretmanager.secretAccessor` on the secret, or
`roles/iam.serviceAccountTokenCreator` on the service account named in
`secretImpersonateServiceAccount` (which then needs the accessor role).
4. **Cost and cleanup**: Review
[Google Cloud Pricing](https://cloud.google.com/pricing) for BigQuery, Cloud
Storage, and Secret Manager. Staged samples in Cloud Storage contain source
rows. When validation is complete, ask the user before deleting the staged
run directory (a `gcs_paths` entry in `run_state.json`) and any per-run
tables they no longer need (list them as in the
[results reference](references/results.md), Section 5). Deleting the run
directory also deletes the backend reports stored there (`results.json`,
`validation_summary.txt`, `column_details.txt`, `queries.sql`) and
`sample_metadata.json`, so `run_history.gcs_uri` no longer resolves;
say so and offer to copy the reports locally first:
```bash
gcloud storage cp GCS_RUN_PATH/results.json \
GCS_RUN_PATH/validation_summary.txt GCS_RUN_PATH/column_details.txt \
GCS_RUN_PATH/queries.sql LOCAL_DIR/
gcloud storage rm --recursive GCS_RUN_PATH
bq rm -f -t RESULTS_PROJECT:DATASET.TABLE_NAME
```
## 1. What gets compared
Pillar | `--validation-types` | Compares | Coverage
:------------ | :------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :-------
**Schema** | `schema` | Column presence, mapping, and data type compatibility (one of 9 compatibility notes) | All columns
**Aggregate** | `aggregate` | Column statistics per type (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`, `SUM_LENGTH`, ...), computed per partition, then rolled up | 100% of rows (pushed down)
**Data** | `data` | Cell-by-cell values joined on comparison keys, with a distance per mismatched cell | Sampled or full rows
With `--validation-types` omitted, all three run. With `--validation-types` set
(for example `--validation-types=schema,aggregate`), only the listed types run.
Query (code) validation is not available in this tool.
Each pillar catches what the others miss. Aggregates cover every row cheaply but
cannot see offsetting errors (one row +5, another -5). Row sampling sees those
but only in the sample. Run both for sign-off.
## 2. Quick start
Both validation commands run in the **alpha** release track through the Google
Cloud CLI, which calls the `bqms` component (Java 11+ required). Arguments after
`--` are forwarded unchanged to the validation client.
> [!IMPORTANT]
> The commands are in the alpha track. If gcloud reports an invalid choice or
> unknown command, ask the user before running `gcloud components update` (or
> `gcloud components install alpha bqms`). If the Google Cloud CLI was
> installed with a system package manager such as `apt` or `yum`, the
> component manager is disabled; have the user upgrade `google-cloud-cli`
> through that package manager instead. If the command is still unavailable,
> stop and point the user to the [CLI reference](references/cli.md) and the
> [installation guide][gcloud_install] rather than retrying.
```bash
# 1. Generate per-table configs offline from extractor metadata or BQMS
# translation output (writes ./validation_config/).
gcloud alpha bq migration validation configure \
--metadata=dwh-migration-oracle-metadata.zip \
--target-dataset=warehouse \
--output=validation_config
# 2. Edit validation_config/connections.yaml (check the source dialect;
# set the target dataset) and settings.yaml (googleCloudStorage.gcsPath),
# then run schema and aggregate checks first.
gcloud alpha bq migration validation run validation_config/ \
--location=us --validation-types=schema,aggregate
# 3. Run row-level comparison, optionally on a subset of tables.
gcloud alpha bq migration validation run validation_config/ \
--location=us --validation-types=data --tables=orders
```
Then wait for the workflows (Section 4) and investigate (Section 5).
Every answer that runs or recommends `validation run` must tell the user that
the comparison finishes later in a BigQuery Migration workflow, that exit code 0
does not mean the data matched, and how to check the workflow before reading
results. Users who skip this read an empty or stale results dataset as a pass.
## 3. Configure
Settings come from YAML (modular `validation_config/` directory or one
`validation-config.yaml`), then CLI flags. The essentials:
* `connections`: a `source` and a BigQuery `target`. The target needs
`projectId` and `dataset`; without `dataset` the run fails, even when every
`targetTable.name` is fully qualified. `configure` can scaffold the wrong
source `dialect` (for example `snowflake` for PostgreSQL metadata), so
check it and its properties before the first run. Connection names are
letters and digits only; a name with `_` or `-` fails config validation. If
the user asks for such a name, drop the separators (for example `sales-db`
becomes `salesdb`) and tell them why, because the name also forms the
environment variable prefix. Keep secrets out of YAML: use
`BQMS_VALIDATION_<CONNECTION>_PASSWORD` or a Secret Manager reference (see
[connections and drivers](references/connections.md)). Never ask the user
to type a password into the conversation and never echo one. For commands
you run yourself, use a Secret Manager reference (`passwordSecret` or
`BQMS_VALIDATION_<CONNECTION>_PASSWORD_SECRET`); give plaintext `export`
lines only for the user to run in their own terminal.
* `googleCloudStorage.gcsPath`: required staging bucket (`gs://bucket/path`,
no trailing slash). Results artifacts also land here.
* Per table: `sourceTable` and `targetTable` (each with `name` and, under
`sourceTable`, `comparisonKeys`: the columns that uniquely identify a row
for the validation join when the table has no primary key — explain that
`comparisonKeys` only control how validation matches rows, so no database
primary key or schema change is needed; `configure` fills them in only
when the metadata includes primary keys), `columnSettings` (exclusions,
transforms, tolerances), `sampleSize`, and `partitioning`.
* `results.dataset` and optional `results.projectId`: BigQuery dataset and
project for results (defaults `validation_results` and the target
connection's project). Query results where these point.
Details: [configuration reference](references/configuration.md).
## 4. Run and wait
1. Run `gcloud alpha bq migration validation run`. Exit code 1 means a config
or source-side failure; read the error and fix it. Exit code 0 means the
samples were staged (or that usage was printed for a bad forwarded flag;
check the output). Mismatches never change the exit code.
2. Confirm a workflow started. The client prints a workflow name per table and
writes `run_state.json` (run ID, Cloud Storage paths, workflow names,
results dataset) to `--output-dir` (default `/tmp/validation_outputs`,
passed after `--`). If it instead prints "Could not initiate BigQuery
Migration validation workflow", fix the cause it reports (usually
permissions or the API not enabled) and re-run, or create the workflow from
the console link it prints.
3. Poll until the workflow finishes:
```bash
gcloud bq migration-workflows describe WORKFLOW_NAME
```
Or check `run_history.status` in the results dataset; `IN_PROGRESS` means
the backend is still working.
## 5. Investigate results
Results are in three places. Pick by question, not by habit:
Surface | Audience | Grain | Use for
:--------------------------------------------- | :------------- | :--------------------------------------------- | :------
BigQuery results dataset | Agents, humans | Run, slice (partition), column, aggregate, row | All investigation; the only source for per-partition and per-row detail
Cloud Storage `results.json` | Agents | One run (whole table) | Quick status of one table without BigQuery access; execution times
`validation_summary.txt`, `column_details.txt` | Humans | One run | Show the user; do not parse
Web UI | Humans | All of the above, visual | Point the user to it if the printed link is a real URL
Investigate by zooming in one level at a time, stopping as soon as the cause is
clear:
1. **All tables**: Latest run per table with status, row deltas, and mismatch
counts. Errors first, then the largest mismatch counts.
2. **One table, by pillar**: Schema compatibility, then failed aggregates, then
missing rows, then per-column mismatch statistics.
3. **Partitions**: Per-slice metrics show whether mismatches are local (one day
or range: a failed load) or everywhere (a systematic conversion).
4. **Rows**: Group mismatched cells by column and distance, then read a few
rows to confirm the pattern.
5. **Fix and re-run narrowly**: Pass `--tables` and `-- --where`, then compare
the new run with the old one.
Then zoom back out: say which tables pass, which have explained differences, and
which need a fix in the migration itself. A narrower re-run (some
`--validation-types`, or `--where`) becomes the table's latest run without
covering the rest; a table passes only when every pillar and the whole table
passed.
Queries, field names, and decision rules for each level:
[investigation workflow](references/investigation.md). What every status, field,
and table means: [results reference](references/results.md).
## 6. Reference guides
Guide | Read when
:------------------------------------------------------------ | :--------
[CLI reference](references/cli.md) | Installing, running, flags, exit codes, workflow status
[Configuration reference](references/configuration.md) | Writing or auditing YAML, keys, transforms, tolerances
[Connections and drivers](references/connections.md) | Credentials, Secret Manager, JDBC drivers, JDBC URLs
[Sampling and partitioning](references/performance_tuning.md) | Sample sizes, partitioned runs, wide tables, concurrency
[Results reference](references/results.md) | Statuses, `results.json`, BigQuery tables and views, distances
[Investigation workflow](references/investigation.md) | Step-by-step drill-down queries and decision rules
[Dialects and types](references/dialect_mapping.md) | Default aggregates, type compatibility, dialect quirks
[Troubleshooting](references/troubleshooting.md) | Mismatch signatures and their config fixes, run errors
## 7. Operating principles
1. **Read-only**: Validation only runs `SELECT` on the source and target. Never
modify source or target data to make a validation pass.
2. **Mismatches are findings, not failures**: A run that finishes with
mismatches (`COMPLETED_WITH_MISMATCHES`) succeeded and found differences.
Reserve "failed" for `ERROR` runs and non-zero exit codes.
3. **Explain before excluding**: Do not add `exclude`, tolerances, or
transforms to hide a difference until the row-level evidence shows it is a
representation difference (padding, precision, empty string versus NULL) and
not lost or wrong data. Say which one it is.
4. **Protect row data**: Mismatch tables hold real customer values. Query
aggregates and small samples (`LIMIT`), and do not paste bulk row values
into the conversation unless the user asks.
5. **Edit the user's config in place**: When the user names a config file, read
it, change only what the task needs, and keep everything else as written:
table names (including dataset or schema prefixes), `comparisonKeys`,
filters, and settings. Do not normalize or shorten existing names. A changed
`targetTable.name` points the comparison at a different table, and a dropped
`comparisonKeys` changes what counts as a missing row, so either silently
changes what is validated. If something existing looks wrong, say so instead
of changing it.
[cloud_locations]: https://cloud.google.com/about/locations
[gcloud_install]: https://cloud.google.com/sdk/docs/install
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-migration-validator)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:bigquery-migration-validator)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```text
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-migration-validator)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
cli.md 11.3 KB
# Validation CLI reference
Commands, flags, exit codes, and workflow tracking for the validation tool.
## Contents
* [1. Installation](#1-installation): Lines 15-35
* [2. Command shape](#2-command-shape): Lines 37-46
* [3. validation configure](#3-validation-configure): Lines 48-111
* [4. validation run](#4-validation-run): Lines 113-157
* [5. Exit codes and output](#5-exit-codes-and-output): Lines 159-186
* [6. Tracking the backend workflow](#6-tracking-the-backend-workflow): Lines 188-201
* [7. Runtime environment](#7-runtime-environment): Lines 203-212
## 1. Installation
The validation commands belong to the Google Cloud CLI. They call the `bqms`
component, which bundles the validation client and the migration extractor.
* **Java 11 or later** must be the first `java` on `PATH`. gcloud does not
read `JAVA_HOME`; if an older `java` comes first, put the newer one ahead
of it, for example `export PATH="$JAVA_HOME/bin:$PATH"`.
* **Application Default Credentials** are required:
`gcloud auth application-default login`. The identity needs write access to
the staging bucket, BigQuery access in the target project, and permission to
create BigQuery Migration workflows there.
* The commands need the `alpha` and `bqms` components. Ask the user before
installing or updating anything. gcloud offers to install `bqms` on first
use; to install both explicitly, run
`gcloud components install alpha bqms`. If the command group is missing,
run `gcloud components update`. If the Google Cloud CLI was installed with
a system package manager (`apt`, `yum`), the component manager is disabled:
upgrade `google-cloud-cli` with that package manager instead. If the
command group is still missing, stop and point the user to the
[installation guide](https://cloud.google.com/sdk/docs/install).
## 2. Command shape
Both validation commands live under `gcloud alpha bq migration validation`.
gcloud flags come first; any validation client flags not exposed directly on
gcloud go after `--` and are forwarded unchanged to the client:
Command | Purpose
:--------------------------------------------------------------------------- | :------
`gcloud alpha bq migration validation configure` | Write table configs from offline metadata
`gcloud alpha bq migration validation run CONFIG_PATH --location=LOCATION` | Stage samples and start validation workflows
## 3. validation configure
```text
gcloud alpha bq migration validation configure --output=DIRECTORY
[--metadata=PATH] [--tables-yaml=PATH[,...]] # at least one; both allowed
[--target-dataset=TARGET_DATASET] [--schemas=SCHEMA[,...]]
[--tables=TABLE[,...]] [--force] [--endpoint-mode=ENDPOINT_MODE]
[-- CLIENT_ARGS ...]
```
Builds per-table configs from offline metadata without connecting to the source
database. `--output` and at least one of `--metadata` or `--tables-yaml` are
required (both can be combined). With `--quiet` (or in non-interactive shells),
ambiguities resolve with defaults instead of prompting.
gcloud flags (before `--`):
Flag | Default | Meaning
:--------------------------- | :------------ | :------
`--output DIRECTORY` | required | Output directory (for example `validation_config`)
`--metadata PATH` | None | Extractor metadata `.zip` (`dwh-migration-*-metadata.zip`) or a directory containing `.zip` archives and `tables.yaml` files
`--tables-yaml PATH[,...]` | None | BQMS translation `tables.yaml` mapping files or directories
`--target-dataset DATASET` | source schema | BigQuery dataset for target table names
`--schemas S1,S2` | None | Only generate configuration for these source schemas
`--tables T1,T2` | None | Only generate configuration for these source tables
`--force` | None | Overwrite existing configuration files in `--output`
`--endpoint-mode MODE` | `global` | `global`, `regional`, or `regional-preferred`
Client flags forwarded after `--`:
Flag | Default | Meaning
:------------------------ | :-------- | :------
`--update` | None | Merge new metadata into existing table files, keeping manual edits
`--clean` | None | Delete the output directory first
`--combine`, `-f FILE` | None | Write one combined file instead (`-f` implies `--combine`; default `validation-config.yaml`)
`--filter-file FILE` | None | Newline-separated table names or patterns (`#` comments)
`--target NAME` | `target` | Target connection for tables that do not name one
A non-empty `--output` directory is an error unless `--force` (before `--`) or
`--update` / `--clean` (after `--`) is given. Prefer `-- --update` once users
have edited the configs.
What generation fills in:
* `comparisonKeys` from primary keys, only when the metadata includes them.
PostgreSQL extractor archives carry no primary keys, so their table files
get none. Add them by hand under `sourceTable` (see
[comparison keys](configuration.md#4-comparison-keys)):
```yaml
table:
sourceTable:
name: "salesdb.sales.orders"
comparisonKeys: [order_id]
```
* `exclude` for column types the comparison cannot handle.
* `transform: TRIM` for padded character columns (`CHAR(n)`).
* Fully qualified names (`schema.table`). These override the connection's
default dataset or schema, so check that `targetTable.name` points at the
intended BigQuery dataset.
* Teradata metadata is parsed natively, including partitions and indexes.
Other dialects use generic `tables.csv`/`columns.csv` parsing, so
partition-aware split keys are not inferred for them.
## 4. validation run
```text
gcloud alpha bq migration validation run CONFIG_PATH [CONFIG_PATH ...]
--location=LOCATION [--validation-types=TYPE[,...]]
[--tables=TABLE[,...]] [--gcs-path=gs://...] [--labels=KEY=VALUE[,...]]
[--endpoint-mode=ENDPOINT_MODE]
[-- [--where=SQL] [--source-where=SQL] [--target-where=SQL]
[--no-partition] [--max-concurrency=N] [--output-dir=DIR]
[--extract-only] [--performance]]
```
`CONFIG_PATH` (one or more required positional values) may be a directory (such
as `validation_config/`, read recursively), a `.yaml`/`.yml` file (such as
`validation-config.yaml`), a glob pattern such as
`validation_config/databases/edw/sales/*.yaml`, or a `gs://` path to configs in
Cloud Storage.
gcloud flags (before `--`):
Flag | Meaning
:----------------------------- | :------
`--location LOCATION` | Required. Location of the BigQuery Migration Service workflows (for example `us` or `europe-west1`)
`--validation-types TYPE[,...]`| Comma-separated list of `schema`, `aggregate`, `data` (default: all three)
`--tables TABLE[,...]` | Only these tables (matches full source/target name or dot-separated suffix, for example, `orders` or `sales.orders`)
`--gcs-path gs://...` | Override `googleCloudStorage.gcsPath`
`--labels KEY=VALUE[,...]` | Labels attached to the validation run
`--endpoint-mode MODE` | `global`, `regional`, or `regional-preferred`
Client flags forwarded after `--`:
Flag | Meaning
:--------------------------------- | :------
`--where SQL` | Filter applied to both sides; replaces table `whereClause`
`--source-where`, `--target-where` | Side-specific filters; replace the table's filter
`--no-partition` | Disable partitioned execution for every table
`--max-concurrency N` | Slices processed in parallel; overrides table `maxConcurrency`
`--output-dir DIR` | Local output directory for `run_state.json` (default `/tmp/validation_outputs`)
`--extract-only` | Stage samples in Cloud Storage without starting backend workflows
`--json '{...}'`, `--json @FILE` | Pass client arguments as JSON; overrides flags
`-v`, `-d` | Verbose or debug client logging (also derived from gcloud `--verbosity`)
`--performance` | Extra timing lines in the client log
`--where` style flags replace the configured filter outright; they do not add to
it. Pass them after `--` for quick narrow re-runs (one day, one key range).
## 5. Exit codes and output
Exit | Meaning | Action
:--- | :-------------------------------------------------------- | :-----
`0` | Samples staged (workflows usually started) | Check the output for a dispatch warning, then wait (Section 6)
`1` | Config error, credentials error, or a source query failed | Read the error, fix, re-run
An unknown forwarded client flag or invalid `--json` payload prints client usage
and exits 0 without doing anything. Check that the output shows tables being
sampled.
Exit code 0 does not mean the data matched; the comparison has not run yet. If
workflow creation failed, the client still exits 0 and prints "Could not
initiate BigQuery Migration validation workflow" with a ready-to-run
`gcloud bq migration-workflows create` command and a Cloud console link. Fix the
cause (usually permissions or the BigQuery Migration API not enabled), then
re-run `validation run` or create the workflow from the console link.
The client writes `run_state.json` to `--output-dir`:
```json
{"run_id": "...", "gcs_path": "gs://...", "gcs_paths": ["gs://..."],
"workflow_name": "projects/.../workflows/...", "workflow_names": ["..."],
"bq_results": "PROJECT.validation_results", "ui_url": "..."}
```
Use it to find the workflow, the staged run directory, and the results dataset
without parsing logs.
## 6. Tracking the backend workflow
The client starts one BigQuery Migration workflow per table (display name
`validation_<run_id>`, in the `--location` passed to `validation run`). The
backend comparison runs there.
```bash
gcloud bq migration-workflows describe WORKFLOW_NAME
gcloud bq migration-workflows list --location=us --project=PROJECT
```
Wait until the workflow and its validation task are finished. A failed task
means the backend could not compare (for example, missing target table or
permissions); the error is in the workflow and in `run_history.error_message`.
## 7. Runtime environment
Variable | Effect
:------------------------------------------------------------------ | :-----
`PATH` | The first `java` on `PATH` is used (11+); gcloud ignores `JAVA_HOME`
`JAVA_OPTS` | Extra JVM flags, for example `-Xmx8g` for large samples
`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` | Not converted for Java by gcloud; pass proxies in `JAVA_OPTS`, for example `-Dhttps.proxyHost=HOST -Dhttps.proxyPort=PORT`
`BQMS_VALIDATION_LOCATION` | Set automatically from `--location` by `validation run`
`BQMS_VALIDATION_CONNECTIONS_PATH`, `BQMS_VALIDATION_SETTINGS_PATH` | Fallback shared `connections.yaml` / `settings.yaml`, used only when none is found in a parent directory
`BQMS_DRIVER_DIR`, `BQMS_AUTO_DOWNLOAD_DRIVERS` | JDBC driver location and download switch (see [connections](connections.md))
configuration.md 9.9 KB
# Validation configuration reference
How to write and audit validation configs.
## Contents
* [1. Layout and precedence](#1-layout-and-precedence): Lines 14-45
* [2. Top-level keys](#2-top-level-keys): Lines 47-84
* [3. Table keys](#3-table-keys): Lines 86-111
* [4. Comparison keys](#4-comparison-keys): Lines 113-135
* [5. Column settings](#5-column-settings): Lines 137-175
* [6. Aggregates and tolerances](#6-aggregates-and-tolerances): Lines 177-221
## 1. Layout and precedence
`gcloud alpha bq migration validation configure` writes a modular directory:
```text
validation_config/
├── connections.yaml # connections (+ optional Cloud Storage/results)
├── settings.yaml # googleCloudStorage, results, defaults
├── index.yaml
└── databases/<database>/<schema>/<table>.yaml # one `table:` per file
```
A single `validation-config.yaml` holding everything also works.
How a table file finds its shared settings: the tool walks up from the table
file through parent directories, checking each for `connections.yaml`,
`validation_config/connections.yaml`, or `validation-config.yaml`. The env vars
`BQMS_VALIDATION_CONNECTIONS_PATH` and `BQMS_VALIDATION_SETTINGS_PATH` are only
fallbacks: they are read when no such file is found in any parent directory,
so a config file higher up the tree wins over them.
Order of precedence, lowest to highest:
1. Root defaults (`tolerance`, `tolerances`, `aggregate`, `labels`), copied
into every table.
2. Table-level values.
3. CLI flags (`--where` and similar replace the table filter; `--no-partition`
disables partitioning everywhere).
4. `--json` arguments.
Unknown keys are ignored silently, so a misspelled key has no effect. Check
spelling against this page when a setting seems ignored.
## 2. Top-level keys
```yaml
connections:
source: # names: letters and digits only
dialect: teradata
host: td.example.com
user: migrator # password from env or Secret Manager
target:
dialect: bigquery
projectId: my-project
dataset: warehouse # required; default for unqualified names
googleCloudStorage:
gcsPath: gs://my-bucket/validation # required; no trailing slash
format: PARQUET # PARQUET (default) or CSV
compression: SNAPPY # SNAPPY default for Parquet, GZIP for CSV
results:
projectId: results-project # optional; defaults to the target project
dataset: validation_results # results dataset in results.projectId
resultTtlHours: 168 # must be > 0
tables: [...]
```
* Connection names must match `^[a-zA-Z0-9]+$` (no `_` or `-`).
* The BigQuery target connection needs `projectId` and `dataset`. Without
`dataset`, `validation run` fails with `dataset is required for BigQuery
connection`, even when every `targetTable.name` is fully qualified.
* At least one connection and one table are required.
* Invalid `format`/`compression` values fall back to the defaults silently.
* `results.projectId` and `results.dataset` are honored: results and per-run
tables go to `results.projectId` (default: the target connection's
project). When `billingProjectId` on the target BigQuery connection is unset
or blank, BigQuery jobs are billed to `results.projectId` first and fall
back to the target connection's `projectId`. `results.location` is accepted
but ignored. Query results in that project, not in the target project.
## 3. Table keys
Key | Default | Meaning
:------------------------------------- | :----------- | :------
`sourceTable` | required | `name`, `connection`, `comparisonKeys`, `whereClause`, `useAllColumnsAsKey`, `totalTableRowCount`
`targetTable` | source name | Same keys as `sourceTable`
`whereClause` | None | Filter for both sides when the side-specific one is blank
`columnSettings` | None | Section 5
`aggregate` | per type | Section 6
`sampleSize` | `70000` | Rows sampled (per slice when partitioned)
`strategy` | `smart` | `smart`, `sample`, `brute_force`
`partitioning` | auto | `{type, column, partitionSize, rowsPerSlice}`; see [sampling and partitioning](performance_tuning.md)
`disablePartitioning` | `false` | Never split this table
`physicalPartitions` | None | Explicit physical partition list
`maxSlices` | `0` (no cap) | Upper bound on slices
`maxConcurrency` | `1` | Slices of this table processed in parallel
`maxColumnsPerTile` | `100` | Columns per comparison query for wide tables
`skipRandomization` | `false` | Take rows in order instead of random sampling
`runSchema`, `runAggregate`, `runData` | None | Per-table pillar switches
`labels` | None | Key-value labels for the run
`strategy: smart` uses a full comparison (`brute_force`) below 100,000 rows and
sampling above. `brute_force` compares every source row and never partitions;
use it only for small tables or final sign-off of a critical table. With either
strategy, rows that exist only in BigQuery are not reported at row level; they
show up only in total row counts and aggregates such as `COUNT`.
## 4. Comparison keys
Comparison keys are the columns that uniquely identify a row on both sides.
Row-level comparison joins source and target on them, so they decide whether a
difference shows up as a changed value or as a missing row.
* They work like a primary key but need no constraint in either database.
* If the table has no unique key, list a composite key that is unique.
* If no unique combination exists, set `useAllColumnsAsKey: true`. The
comparison then counts identical rows (hash mode) and reports only rows
present on one side, not column-level drift.
* A non-unique key multiplies rows in the join and produces false mismatches.
* Put `comparisonKeys` under `sourceTable` (or `targetTable`). It is a field
of the table definition, not of the table entry, so a `comparisonKeys`
placed directly on the entry does not set the keys.
```yaml
- sourceTable:
name: retail.order_items
comparisonKeys: [order_id, line_item_id]
targetTable:
name: warehouse.order_items
```
## 5. Column settings
```yaml
columnSettings:
exclude: ['etl_*', 'blob_payload'] # glob patterns
columns:
account_status:
transform: TRIM
middle_name:
transform: EMPTY_TO_NULL
amount:
tolerance: 0.01 # row comparison: max |t - s|
diffMethod: SUBTRACTION
cust_id:
targetColumn: customer_id # renamed in BigQuery
created_local:
transformExpression: "DATETIME(created_local, 'America/New_York')"
```
Transform | Applies | Use for
:--------------- | :---------------------------------- | :------
`TRIM` | `TRIM(col)` | `CHAR(n)` padding
`UPPER`, `LOWER` | Case folding | Case-insensitive source collations
`EMPTY_TO_NULL` | `NULLIF(CAST(col AS STRING), '')` | Oracle-style empty string versus `NULL`
`NULL_TO_EMPTY` | `COALESCE(CAST(col AS STRING), '')` | The reverse
`CAST_TO_STRING` | `CAST(col AS STRING)` | Compare as text
* Transforms are applied in BigQuery during comparison. Unknown transform
names are ignored without an error.
* `transformExpression` is a BigQuery SQL expression in which the column name
is replaced by the column reference. It takes precedence over `transform`.
Semicolons are rejected.
* `exclude` is for unsupported types and columns that legitimately differ
(load timestamps, surrogate keys). Do not exclude columns to work around
query size limits; wide tables are split automatically
(`maxColumnsPerTile`).
* `diffMethod` overrides how distance is measured: `SUBTRACTION`, `LENGTH`,
`EDIT_DISTANCE`, `BITWISE_HAMMING_DISTANCE`, `IDENTITY` (see
[results reference](results.md)).
## 6. Aggregates and tolerances
Default aggregates per type:
Column type | Aggregates
:-------------------------------------- | :---------
Integer, `NUMERIC`, `BIGNUMERIC` | `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`
Floating point | `COUNT`, `MIN`, `MAX`
`BOOLEAN` | `COUNT`, `COUNT_TRUE`, `COUNT_FALSE`, `COUNT_NULL`
String | `COUNT`, `SUM_LENGTH`
`DATE`, `DATETIME`, `TIME`, `TIMESTAMP` | `MIN`, `MAX`, `COUNT`
String `MIN`/`MAX` are off by default because databases sort strings differently
(collation), which produces false mismatches. Add them per column only when
collations match.
Change the checks per column, so the source and target compute the same
functions:
```yaml
columnSettings:
aggregate:
tolerance: 0.001 # default for all columns of this table
columns:
region_name:
aggregate:
functions: [COUNT, SUM_LENGTH, MIN, MAX] # replaces the defaults
unit_price:
aggregate:
tolerance: 0.01
```
Allowed functions: `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`, `SUM_LENGTH`,
`COUNT_TRUE`, `COUNT_FALSE`, `COUNT_NULL`. `aggregate.disabled: true` removes
the default checks (for a column or the whole table).
How tolerances are applied:
* Tolerances are absolute (`|target - source| <= tolerance`), not relative.
* For `SUM`, an inherited (root or table) tolerance is multiplied by the row
count, so it acts as a per-row tolerance.
* Date tolerances are in days; timestamp and time tolerances in seconds.
* With no tolerance, `AVG` and floating-point aggregates allow a tiny relative
error (about 1e-9); everything else must be exactly equal.
* A per-column `aggregate.tolerance` overrides the table-level one.
connections.md 5.3 KB
# Connections, credentials, and drivers
How the validation tool connects to source databases and BigQuery.
## Contents
* [1. Supported dialects](#1-supported-dialects): Lines 12-40
* [2. Credentials](#2-credentials): Lines 42-106
* [3. JDBC URLs](#3-jdbc-urls): Lines 108-117
* [4. JDBC drivers](#4-jdbc-drivers): Lines 119-136
## 1. Supported dialects
`dialect` values: `teradata`, `snowflake`, `oracle`, `redshift`, `databricks`,
`postgresql`, `sqlserver` (alias `mssql`), `mysql`, `mariadb`, `hive`, `impala`,
`vertica`, `duckdb`, and `bigquery` (target).
When no connections exist yet, `validation configure` scaffolds
`connections.yaml` with the properties each dialect expects (host, port,
database, warehouse, role, and so on). Every property can also come from an
environment variable (Section 2).
Check the scaffolded source `dialect` before running. For a PostgreSQL
metadata archive, `configure` can scaffold `dialect: snowflake` with `account`
and `warehouse`; replace that block with the real dialect and its properties.
A PostgreSQL source with a BigQuery target:
```yaml
connections:
source:
dialect: postgresql
host: pg.example.com
port: 5432
database: salesdb
user: migrator # password from env or Secret Manager
target:
dialect: bigquery
projectId: my-project
dataset: sales # required
```
## 2. Credentials
Never write passwords into config files. The tool reads connection properties
from environment variables, which override YAML:
```text
BQMS_VALIDATION_<CONNECTION>_<PROPERTY>
```
`<CONNECTION>` is the connection name in uppercase. Lookup is case-insensitive.
Connection names may contain only letters and digits; a name such as `sales_db`
or `sales-db` is rejected with a config error before anything runs. Use
`salesdb` instead (environment prefix `BQMS_VALIDATION_SALESDB_`) and tell the
user about the rename.
```bash
export BQMS_VALIDATION_SOURCE_USER='migrator'
export BQMS_VALIDATION_SOURCE_PASSWORD='...'
export BQMS_VALIDATION_SNOWSRC_WAREHOUSE='REPORTING_WH'
```
Plaintext password exports like the one above are for the user to run in
their own terminal. An agent must never ask for a password in the conversation,
echo one, or export one in its own shell (transcripts keep it, and the variable
does not persist between separate commands). For commands the agent runs, use a
Secret Manager reference (`passwordSecret` or
`BQMS_VALIDATION_<CONN>_PASSWORD_SECRET`).
### Secret Manager
A password can be a Secret Manager reference instead of a value. The tool
resolves the password from the first of these that is set:
1. env `BQMS_VALIDATION_<CONN>_PASSWORD` (cleartext or full reference)
2. env `BQMS_VALIDATION_<CONN>_PASSWORD_SECRET` (any reference)
3. YAML `password` (cleartext or full reference)
4. YAML `passwordSecret` (any reference)
A full reference is `projects/P/secrets/S[/versions/V]` or `sm://P/S[/V]`.
`_PASSWORD` and `password` treat any other value as a literal password. Only
`_PASSWORD_SECRET` and `passwordSecret` also accept `P/S[/V]` or a bare secret
ID with optional `:version`. The version defaults to `latest`.
The secret's project comes from `BQMS_VALIDATION_<CONN>_SECRET_PROJECT_ID`, YAML
`secretProjectId`, `GOOGLE_CLOUD_PROJECT`, or `GCP_PROJECT`, in that order. To
read the secret as a service account, set
`BQMS_VALIDATION_<CONN>_SECRET_IMPERSONATE_SERVICE_ACCOUNT` or YAML
`secretImpersonateServiceAccount`.
```yaml
connections:
source:
dialect: snowflake
account: ab98765.europe-west4.gcp
user: migrator
passwordSecret: sm://my-project/snowflake-migrator
database: SALES
schema: PUBLIC
```
### BigQuery target
The target uses Application Default Credentials. The BigQuery connection
requires `projectId` and `dataset` (even when table names are fully qualified),
and also accepts `impersonateServiceAccount` and `credentialsFile`.
## 3. JDBC URLs
Authentication modes that are not plain user and password (SSO, key pair, OAuth,
tokens) are usually set through JDBC URL parameters. Supply the full URL as the
`url` property, or as `BQMS_VALIDATION_<CONN>_URL` when it holds a token.
```text
jdbc:snowflake://ACCOUNT.snowflakecomputing.com/?authenticator=externalbrowser&role=SYSADMIN&warehouse=LOAD_WH
jdbc:databricks://HOST:443/default;transportMode=http;ssl=1;AuthMech=3;httpPath=HTTP_PATH
```
## 4. JDBC drivers
Drivers are downloaded on first use from Maven Central, checked against a pinned
SHA-256, and cached under `~/.cache/google-cloud-bqms/drivers`:
Downloaded automatically | Supplied by the user
:------------------------------------------------------------------------------------ | :-------------------
Oracle, Snowflake, Redshift, Databricks, PostgreSQL, SQL Server, MySQL, MariaDB, Hive | Teradata (`terajdbc4.jar`), Vertica (`vertica-jdbc.jar`), Impala (Cloudera Impala JDBC driver), DuckDB (DuckDB JDBC driver)
The BigQuery driver is bundled.
* Put user-supplied JARs in `./drivers`, or point `BQMS_DRIVER_DIR` at their
directory.
* On machines without internet access, set `BQMS_AUTO_DOWNLOAD_DRIVERS=false`
and place the JARs in the driver directory, or set `BQMS_MAVEN_MIRROR` to an
internal Maven mirror.
* A "driver not found" error for Teradata, Vertica, Impala, or DuckDB means
the JAR is missing from the driver directory; it is never downloaded.
dialect_mapping.md 3.4 KB
# Dialect and type behavior
Cross-database differences that cause validation findings, and how the tool
compares each type. Default aggregates per type are in the
[configuration reference](configuration.md#6-aggregates-and-tolerances);
compatibility notes and distance units are in the
[results reference](results.md).
## 1. How types are compared
Type family | Row comparison | Aggregates
:---------------------- | :------------------------------------------------ | :---------
Integer, decimal | Signed difference | `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`
Floating point | Signed difference; tiny noise may end as `HEALED` | `COUNT`, `MIN`, `MAX` (no `SUM`/`AVG` by default)
String | Edit distance | `COUNT`, `SUM_LENGTH`
`DATE` | Days apart | `MIN`, `MAX`, `COUNT`
`TIMESTAMP`, `DATETIME` | Microseconds apart | `MIN`, `MAX`, `COUNT`
`BOOLEAN` | Equal or not | `COUNT`, `COUNT_TRUE`, `COUNT_FALSE`, `COUNT_NULL`
`BYTES` | Equal or not (byte-level) | none by default
`JSON` | Equal or not | none by default
## 2. Known dialect differences
Difference | Sources | Symptom | Fix
:---------------------------- | :---------------------------------------------- | :----------------------------------------------------------------- | :--
Empty string stored as `NULL` | Oracle | Column `COUNT` lower in source; one side `NULL`, other `''` | `transform: EMPTY_TO_NULL`
Fixed-width `CHAR(n)` padding | Teradata, Oracle, SQL Server | `SUM_LENGTH` mismatch, edit distance equals pad length | `transform: TRIM` (added automatically by `validation configure`)
Case-insensitive collation | SQL Server, MySQL (default collations) | Values differ only by case; string `MIN`/`MAX` differ | `transform: UPPER`/`LOWER`; keep string `MIN`/`MAX` off
Time zone semantics | All (`TIMESTAMP` with versus without time zone) | Constant timestamp distance (hours) | Align the BigQuery type (`TIMESTAMP` versus `DATETIME`) or use `transformExpression`
`NUMBER` without precision | Oracle, Snowflake | `LOSSY_CONVERSION` or `NARROWED` to `NUMERIC`; large values differ | Use `BIGNUMERIC` in BigQuery or set a tolerance after checking values
Float versus exact decimal | All | Tiny numeric distances; `SUM` differs slightly | Column `tolerance`, or align types
Identifier case | Snowflake, Oracle (uppercase) versus BigQuery | Columns reported missing on one side | Map with `targetColumn`; check generated names
Large integers in floats | All | Integers above 2^53 differ after `INT64` to `FLOAT64` | Keep integer types
Always confirm with row-level evidence (the
[investigation workflow](investigation.md)) before applying a fix. The same
symptom can come from a real data defect.
investigation.md 13.7 KB
# Investigating validation results
A drill-down procedure for deciding which differences matter and what to fix.
Field and table definitions are in the [results reference](results.md).
Placeholders: `PROJECT` is the results project (`results.projectId`, default
the target project), `DATASET` the results dataset (default
`validation_results`), `RUN_ID` a run ID from `run_history`, and `RUN_KEY` the
run ID as it appears in per-run table names, after the leading `run_`. Default
run IDs have no `run_` prefix (for example `20261026101500_8f3a`, giving
`run_20261026101500_8f3a_mismatches_details`); copy `RUN_KEY` from the table
list query in Section 5 of the [results reference](results.md).
## Contents
* [0. Before starting](#0-before-starting): Lines 25-33
* [1. All tables](#1-all-tables): Lines 35-94
* [2. One table, by pillar](#2-one-table-by-pillar): Lines 96-164
* [3. Partitions](#3-partitions): Lines 166-198
* [4. Rows](#4-rows): Lines 200-241
* [5. Diagnose](#5-diagnose): Lines 243-261
* [6. Fix, re-run, compare](#6-fix-re-run-compare): Lines 263-285
* [7. Report](#7-report): Lines 287-301
## 0. Before starting
* Confirm that the backend finished: the workflow is done, or the run's
`run_history.status` is no longer `IN_PROGRESS`.
* Choose the surface. For one table and a quick status, `results.json` in the
run directory is enough. For several tables, partitions, rows, or history,
use BigQuery.
* Query aggregates first and read rows last, with `LIMIT`. Mismatch tables
contain customer data.
## 1. All tables
Latest run per table pair with the numbers that rank problems:
```sql
WITH latest AS (
SELECT run_id, source_table, target_table, status, started_at, error_message
FROM `PROJECT.DATASET.run_history`
QUALIFY ROW_NUMBER() OVER (
PARTITION BY source_table, target_table ORDER BY started_at DESC) = 1
),
head AS (
SELECT run_id, metrics_json AS m
FROM `PROJECT.DATASET.run_metrics`
WHERE slice_id = 'HEAD'
QUALIFY ROW_NUMBER() OVER (PARTITION BY run_id ORDER BY timestamp DESC) = 1
)
SELECT
l.source_table, l.target_table, l.run_id, l.status, l.error_message,
CAST(JSON_VALUE(h.m, '$.source_total_row_count') AS INT64) AS src_rows,
CAST(JSON_VALUE(h.m, '$.target_total_row_count') AS INT64) AS tgt_rows,
CAST(JSON_VALUE(h.m, '$.source_only_row_count') AS INT64) AS missing_in_bq,
CAST(JSON_VALUE(h.m, '$.target_only_row_count') AS INT64) AS extra_in_bq,
CAST(JSON_VALUE(h.m, '$.mismatch_count') AS INT64) AS mismatched_rows,
JSON_VALUE(h.m, '$.sample_coverage') AS sample_coverage,
JSON_VALUE(h.m, '$.run_schema') AS ran_schema,
JSON_VALUE(h.m, '$.run_aggregate') AS ran_aggregate,
JSON_VALUE(h.m, '$.run_data') AS ran_data,
JSON_VALUE(h.m, '$.source_partition_filter') AS where_filter
FROM latest l LEFT JOIN head h USING (run_id)
ORDER BY l.status = 'ERROR' DESC, mismatched_rows DESC;
```
Read the result in this order:
1. `ERROR` runs: the comparison did not happen. Fix `error_message` causes
first (permissions, missing target table, config); they are not data
findings.
2. Total row counts differ: rows were lost or added. Highest impact. The
target count is filled in only when the aggregate pillar ran
(`ran_aggregate`); data-only runs report `tgt_rows` as 0, which means not
counted, not lost rows. Use a `--validation-types=schema,aggregate` run
for row counts.
3. Rows missing from BigQuery in the sample (`missing_in_bq`). Rows that
exist only in BigQuery are not reported here (`extra_in_bq` stays 0); they
show up only as a total row count or `COUNT` aggregate difference.
4. Value mismatches (`mismatched_rows`).
5. `HEALED` and `COMPLETED`: pass.
This shows only the latest run per table pair, not overall parity. A later
narrower re-run (only some `--validation-types`, or a `--where` range) replaces
an earlier full run here, and can hide a failure the full run found. Check the
scope: `ran_schema`, `ran_aggregate`, and `ran_data` say which pillars ran, and
a non-empty `where_filter` means only that range was compared. For a narrower
latest run, also read the earlier runs of that table in `run_history`.
Without BigQuery, read each table's `results.json` (`overallStatus`,
`sourceTotalRowCount`, `targetTotalRowCount`, `sourceOnlyRowCount`,
`targetOnlyRowCount`, `mismatchCount`). `targetTotalRowCount` is also 0 in
data-only runs.
## 2. One table, by pillar
Work through the pillars in this order. Each step can explain the next, so stop
when the cause is clear.
**Schema**: Columns whose types are not compatible:
```sql
SELECT JSON_VALUE(c, '$.name') AS col,
JSON_VALUE(c, '$.compatibility') AS compatibility,
JSON_VALUE(c, '$.source_type') AS source_type,
JSON_VALUE(c, '$.target_type') AS target_type,
CAST(JSON_VALUE(c, '$.mismatch_count') AS INT64) AS mismatches
FROM `PROJECT.DATASET.run_metrics`,
UNNEST(JSON_QUERY_ARRAY(metrics_json, '$.column_metrics')) AS c
WHERE run_id = 'RUN_ID' AND slice_id = 'HEAD'
AND JSON_VALUE(c, '$.compatibility') NOT IN ('COMPATIBLE', 'WIDENED', '')
QUALIFY ROW_NUMBER() OVER (
PARTITION BY JSON_VALUE(c, '$.name') ORDER BY timestamp DESC) = 1;
```
**Aggregates**: Failed checks cover 100% of rows, so they size the problem:
```sql
SELECT JSON_VALUE(a, '$.column_name') AS col,
JSON_VALUE(a, '$.function') AS fn,
JSON_VALUE(a, '$.source_value') AS source_value,
JSON_VALUE(a, '$.target_value') AS target_value,
JSON_VALUE(a, '$.diff') AS diff
FROM `PROJECT.DATASET.run_metrics`,
UNNEST(JSON_QUERY_ARRAY(metrics_json, '$.aggregate_metrics')) AS a
WHERE run_id = 'RUN_ID' AND slice_id = 'HEAD'
AND JSON_VALUE(a, '$.match_result') = 'false'
QUALIFY ROW_NUMBER() OVER (
PARTITION BY JSON_VALUE(a, '$.column_name'), JSON_VALUE(a, '$.function')
ORDER BY timestamp DESC) = 1;
```
How to read failed aggregates:
* `COUNT` of a column differs but table row counts match: `NULL` handling
(empty strings, defaults).
* Table `COUNT` differs: missing or extra rows; go to Section 3.
* `SUM_LENGTH` differs, `COUNT` matches: padding or truncation.
* `SUM`/`AVG` differ by a tiny relative amount: precision; differ a lot: wrong
values or missing rows.
* `MIN`/`MAX` differ: the boundary values (often time zone or truncation).
**Rows and columns**: Rows missing from BigQuery come from the HEAD metrics
(Section 1). Per-column value differences:
```sql
SELECT JSON_VALUE(c, '$.name') AS col,
JSON_VALUE(c, '$.diff_method') AS method,
CAST(JSON_VALUE(c, '$.mismatch_count') AS INT64) AS mismatches,
CAST(JSON_VALUE(c, '$.min_diff') AS FLOAT64) AS min_diff,
CAST(JSON_VALUE(c, '$.avg_diff') AS FLOAT64) AS avg_diff,
CAST(JSON_VALUE(c, '$.max_diff') AS FLOAT64) AS max_diff
FROM `PROJECT.DATASET.run_metrics`,
UNNEST(JSON_QUERY_ARRAY(metrics_json, '$.column_metrics')) AS c
WHERE run_id = 'RUN_ID' AND slice_id = 'HEAD'
AND CAST(JSON_VALUE(c, '$.mismatch_count') AS INT64) > 0
QUALIFY ROW_NUMBER() OVER (
PARTITION BY JSON_VALUE(c, '$.name') ORDER BY timestamp DESC) = 1
ORDER BY mismatches DESC;
```
The same numbers are in `results.json` (`columnMismatchStats`, `aggregateStats`,
`columnTypeComparisons`).
## 3. Partitions
Only for partitioned runs (more than one `slice_id`). Shows whether a problem is
local or everywhere:
```sql
SELECT slice_id,
JSON_VALUE(metrics_json, '$.source_partition_filter') AS slice_filter,
JSON_VALUE(metrics_json, '$.overall_status') AS status,
CAST(JSON_VALUE(metrics_json, '$.source_only_row_count') AS INT64)
AS missing_in_bq,
CAST(JSON_VALUE(metrics_json, '$.target_only_row_count') AS INT64)
AS extra_in_bq,
CAST(JSON_VALUE(metrics_json, '$.mismatch_count') AS INT64)
AS mismatched_rows
FROM `PROJECT.DATASET.run_metrics`
WHERE run_id = 'RUN_ID' AND slice_id != 'HEAD'
QUALIFY ROW_NUMBER() OVER (PARTITION BY slice_id ORDER BY timestamp DESC) = 1
ORDER BY IFNULL(missing_in_bq, 0) + IFNULL(extra_in_bq, 0)
+ IFNULL(mismatched_rows, 0) DESC;
```
* Problems concentrated in a few slices (one date range, one key range): a
load or extract most likely failed for that range. Before re-loading,
confirm the rows are really absent: look up a few missing keys from the
run's `mismatches` table in both systems (Section 4), or compare that
range's row counts directly. A filter or key difference on one range can
look the same, and a re-load is expensive. Then re-load the range and re-run
validation for that range only (Section 6). No config change.
* Problems spread evenly across slices: a systematic conversion difference.
Continue to Section 4 to identify it.
Per-slice aggregates are in `run_<run>_<slice>_agg_joined`.
## 4. Rows
Find the run's tables (Section 5 of the [results reference](results.md)), then
profile the mismatched cells before reading any rows:
```sql
SELECT column_name, failure_type, COUNT(*) AS cells,
MIN(distance) AS min_d, MAX(distance) AS max_d,
APPROX_TOP_COUNT(distance, 5) AS common_distances,
COUNTIF(source_value IS NULL) AS src_null,
COUNTIF(target_value IS NULL) AS tgt_null
FROM `PROJECT.DATASET.run_RUN_KEY_mismatches_details`
GROUP BY column_name, failure_type
ORDER BY cells DESC;
```
Then read a few examples of the top pattern:
```sql
SELECT __s_comparison_id, source_value, target_value, distance
FROM `PROJECT.DATASET.run_RUN_KEY_mismatches_details`
WHERE column_name = 'COLUMN' AND failure_type = 'DATA_DRIFT'
ORDER BY ABS(distance) DESC
LIMIT 10;
```
For rows missing from BigQuery, list keys from the `mismatches` table:
```sql
SELECT __s_comparison_id
FROM `PROJECT.DATASET.run_RUN_KEY_mismatches`
WHERE __source_only_row
LIMIT 20;
```
Check a few of those keys directly in the source and in BigQuery before
concluding rows are lost; a filter or key difference can look the same.
Rows that exist only in BigQuery never appear in the `mismatches` table, even
with `brute_force`. When the target row count or `COUNT` aggregate is higher,
find the extra keys with a direct anti-join: load the source comparison keys
into a BigQuery table, then select target rows whose key has no match there.
## 5. Diagnose
Pattern in the evidence | Likely cause | Fix
:------------------------------------------------------------------------------------- | :----------------------------------------------------- | :--
One distance value dominates on a timestamp (for example 3.6e9 or 1.8e10 microseconds) | Time zone offset | Align types or add a `transformExpression`; confirm which side is right
Tiny absolute numeric distances (for example 1e-8) | Float versus decimal precision | `tolerance` on the column
`EDIT_DISTANCE` equals trailing space count, `SUM_LENGTH` differs | `CHAR(n)` padding | `transform: TRIM`
One side `NULL`, other side `''` | Empty string versus `NULL` (Oracle) | `transform: EMPTY_TO_NULL`
Case-only differences | Collation | `transform: UPPER` or `LOWER`
`ROW` mismatches clustered in some slices | Partial load or extract | Re-load the range
`ROW` mismatches spread evenly, total row counts match | Wrong or non-unique comparison key, or filter mismatch | Fix `comparisonKeys` or `whereClause`
Large, varied numeric distances | Wrong values (bad transformation) | Fix the migration logic; do not tolerate
`NARROWED`/`LOSSY_CONVERSION` plus value mismatches | DDL loses data | Change the BigQuery column type
More signatures and config examples: [troubleshooting](troubleshooting.md).
A config fix (tolerance, transform, exclude) is right only for representation
differences. If values are actually wrong or missing, the fix belongs in the
migration, and the finding should be reported as a defect.
## 6. Fix, re-run, compare
1. Change the config for the affected table and column only.
2. Re-run just that table, and just the affected range when the problem is
local:
```bash
gcloud alpha bq migration validation run validation_config/ \
--location=us --tables=shipments \
-- --where="ship_date = '2025-11-02'"
```
3. Compare the two runs per column:
```sql
SELECT source_column_name, target_column_name, run_id, status, mismatch_count, run_timestamp
FROM `PROJECT.DATASET.column_history`
WHERE source_table = 'SOURCE_TABLE'
ORDER BY source_column_name, run_timestamp DESC;
```
`status` can be `MISMATCH` with `mismatch_count` 0 when only an aggregate
failed, so rank columns by `mismatch_count`.
## 7. Report
Summarize from the top again (Section 1 query after the last runs):
* Tables that pass (`COMPLETED`, `HEALED`), counted only when every pillar
and the whole table passed: either the latest run covered all of them (no
`where_filter`), or each earlier run of the missing pillars or ranges also
passed.
* Tables with explained, accepted differences, and the config that accepts
them (tolerance, transform), with the evidence.
* Tables with defects to fix in the migration: what, where (columns,
partitions), how many rows, and example keys.
* Runs that errored and why.
* Where to look: the results dataset, the run directories, and the web UI
link if the client printed a real URL (not a placeholder).
performance_tuning.md 5.6 KB
# Sampling, partitioning, and scale
How to size samples, split large tables, and keep wide tables within BigQuery
query limits.
## Contents
* [1. Sample size](#1-sample-size): Lines 15-33
* [2. Aggregates first](#2-aggregates-first): Lines 34-48
* [3. Partitioned validation](#3-partitioned-validation): Lines 49-107
* [4. Wide tables](#4-wide-tables): Lines 108-116
* [5. Concurrency and memory](#5-concurrency-and-memory): Lines 117-125
* [6. Timing information](#6-timing-information): Lines 126-132
## 1. Sample size
Row comparison samples rows at random. The chance of seeing at least one bad row
when a fraction `p` of rows is bad is `1 - (1 - p)^n` for `n` sampled rows.
`sampleSize` | Detects with 99.9% confidence
:---------------- | :----------------------------
`70000` (default) | 1 bad row in 10,000
`700000` | 1 bad row in 100,000
* Tables (or slices) smaller than `sampleSize` are compared in full.
* With `strategy: smart` (default), tables under 100,000 rows are always
compared in full (`brute_force`).
* When partitioned, `sampleSize` applies per slice, so total sampled rows grow
with the number of slices.
Sampling cannot prove that no row is wrong. Aggregates cover every row; use
both, and say what confidence the sample gives when reporting a clean result.
## 2. Aggregates first
Aggregate checks run as push-down queries on both databases and cover 100% of
rows with little data movement. Run them first, together with the schema
check (type compatibility), which is cheap:
```bash
gcloud alpha bq migration validation run validation_config/ \
--location=us --validation-types=schema,aggregate
```
If row counts differ by `k` rows in `N`, the error density is `k/N`. Size the
row sample from that (Section 1), or narrow the run with `-- --where` to the
affected range.
## 3. Partitioned validation
Large tables are split into slices. Each slice is sampled and compared
separately (sample, aggregates, row comparison), then the backend rolls the
slices up into whole-table results. Per-slice results stay available in
BigQuery, which is what makes local problems (one failed daily load) visible.
When a table is partitioned (first rule that applies):
1. `disablePartitioning: true` or `--no-partition`: never.
2. Strategy resolves to `brute_force` (small tables): never.
3. A `partitioning` block is present: always.
4. Row count above `partitioning.partitionSize` (default 1,000,000): yes.
Partition type (`partitioning.type`):
Type | Splits by | `partitionSize` unit
:--------------- | :---------------------------------------------------------------------------------- | :-------------------
`AUTO` (default) | Physical partitions for Oracle and partitioned Teradata tables, else integer ranges | as chosen
`INTEGER_RANGE` | Ranges of an integer column | rows per slice (default 1,000,000)
`DATE_RANGE` | Ranges of a date column | days per slice (default 30)
`PHYSICAL` | The source table's own partitions | Not applicable
Daily partitions for a date-partitioned fact table:
```yaml
- sourceTable:
name: logistics.shipments
comparisonKeys: [shipment_id]
targetTable:
name: logistics_dw.shipments
partitioning:
type: DATE_RANGE
column: ship_date
partitionSize: 1 # one day per slice
sampleSize: 10000 # per slice
maxConcurrency: 4 # slices in parallel
```
* `DATE_RANGE` is used only when configured; `AUTO` never picks it.
* Choose the partition column the data was loaded by (load date, batch date),
so a failed load maps to one slice.
* `maxSlices` caps the slice count; the run fails with an error if the range
needs more slices than allowed. Increase `partitionSize` or narrow the range
with `whereClause`.
* `rowsPerSlice` overrides the per-slice row limit.
When you configure partitioning, tell the user where per-slice results will be,
because that is why they asked for it:
* BigQuery `run_metrics` rows with `slice_id` other than `'HEAD'` (one per
slice; `source_partition_filter` in `metrics_json` names the range).
* Per-slice tables
`run_<run>_<slice>_{mismatches,mismatches_details,agg_joined}`.
* `results.json` and the text summaries hold whole-table totals only.
The query for this is in the
[investigation workflow](investigation.md#3-partitions).
## 4. Wide tables
Tables with hundreds of columns produce comparison queries too large for
BigQuery. The tool splits columns into tiles of `maxColumnsPerTile` columns (100
by default) and compares each tile separately. If a wide table still fails with
a query complexity or resource error, lower `maxColumnsPerTile` (for example
50). Do not exclude columns to get under the limit; excluded columns are not
validated at all.
## 5. Concurrency and memory
* `maxConcurrency` (per table) or `--max-concurrency N` (all tables): slices
processed in parallel.
* Source load grows with concurrency. Keep them low against busy production
databases.
* Large samples need client memory: pass `JAVA_OPTS=-Xmx8g` (or more) if the
client runs out of heap.
## 6. Timing information
Source and target query times per run are in `results.json`
(`sourceExecutionTimeMs`, `targetExecutionTimeMs`); total duration is in
`validation_summary.txt` and `run_history` (`started_at`, `finished_at`).
`--performance` adds timing lines to the client log. There is no separate
performance report.
results.md 16.8 KB
# Validation results reference
What the backend writes, where, and what each status and field means. For the
order in which to read it, see the [investigation workflow](investigation.md).
## Contents
* [1. Statuses](#1-statuses): Lines 18-37
* [2. Where results live](#2-where-results-live): Lines 39-48
* [3. Cloud Storage artifacts](#3-cloud-storage-artifacts): Lines 50-98
* [4. BigQuery observability tables](#4-bigquery-observability-tables): Lines 100-142
* [5. BigQuery per-run tables](#5-bigquery-per-run-tables): Lines 144-185
* [6. Cloud Storage versus BigQuery](#6-cloud-storage-versus-bigquery): Lines 187-204
* [7. Row and cell classification](#7-row-and-cell-classification): Lines 206-221
* [8. Diff methods and distances](#8-diff-methods-and-distances): Lines 223-251
* [9. Type compatibility notes](#9-type-compatibility-notes): Lines 253-271
## 1. Statuses
Status | Meaning | Report as
:-------------------------- | :------------------------------------------------------------------- | :--------
`COMPLETED` | Compared; everything matched within tolerance | Pass
`HEALED` | Compared; only negligible numeric noise remained (below) | Pass, mention the noise
`COMPLETED_WITH_MISMATCHES` | Compared; differences found | Finished with findings, not a failure
`ERROR` | The comparison itself failed (permissions, missing table, SQL error) | Run failure; read `error_message`
`SKIPPED`, `ESCALATED` | Not compared, or handed off for review | Say so
`IN_PROGRESS` | Backend still working | Wait
`HEALED` replaces `COMPLETED_WITH_MISMATCHES` only when all of these hold: no
rows are missing on either side, every mismatched column's differences are
negligible (maximum difference below 1e-4, or mean below 1e-4 with standard
deviation below 1e-3), and every failed aggregate differs by less than 1e-6. It
typically means floating-point noise. If a user needs exact equality, look at
the mismatch counts anyway.
A partitioned run's overall status is the worst of its slices
(`COMPLETED_WITH_MISMATCHES` over `HEALED` over `COMPLETED`).
## 2. Where results live
Surface | Location | Written
:-------------------------- | :------------------------------------------------------------------------------ | :------
Cloud Storage run directory | `<gcsPath>/validationOutputs/<table path>/<run_id>/` | Client (inputs) and backend (reports, at the end)
BigQuery results dataset | `<results.projectId or target project>.<results.dataset or validation_results>` | Backend, during and after the run
Web UI | Link printed by the client | Reads BigQuery
The run directory path is also in `run_state.json` (`gcs_paths`) and in
`run_history.gcs_uri`.
## 3. Cloud Storage artifacts
Run directory contents:
File | Writer | Content
:------------------------------------- | :------ | :------
`<table>_sample_1.parquet` (or `.csv`) | Client | Source row sample (under `slices/<id>/` when partitioned)
`source_aggregates.*` | Client | Source-side aggregate values
`source_query_result.json` | Client | Source row counts and column metadata
`sample_metadata.json` | Both | Run configuration handed to the backend
`manifest.jsonl` | Client | Slice list for partitioned runs
`run.log` | Client | Client log
`results.json` | Backend | Machine-readable run summary (below)
`validation_summary.txt` | Backend | Human-readable run summary
`column_details.txt` | Backend | Human-readable per-column breakdown
`queries.sql` | Backend | Comparison SQL that ran
The four backend files are written once, when the whole run (all slices) has
finished. If they are missing, the run is still in progress or failed before the
end; check `run_history`.
### results.json
`{"startedAt", "finishedAt", "tables": {...}}`, where `tables` is a single
object for the run's table pair (not a list). Fields in `tables`:
Group | Fields
:--------- | :-----
Status | `overallStatus`, `errorMessage`, `strategy`, `runSchema`, `runAggregate`, `runData`
Identity | `sourceTable`, `targetTable`, `sourceConnection`, `targetConnection`, `comparisonKeys`, `excludeColumns`, `labels`
Rows | `sourceTotalRowCount`, `targetTotalRowCount`, `sourcePartitionRowCount`, `targetPartitionRowCount`, `sourcePartitionFilter`, `targetPartitionFilter`, `sourceRowsQueried`, `joinedRowCount`, `sourceOnlyRowCount`, `targetOnlyRowCount`, `rowLimit`
Sampling | `samplesCollected`, `confidence`, `joinStability`
Mismatches | `mismatchCount`, `mismatchRate`, `contentCellMismatches`, `structuralCellMismatches`, `logicalRowMismatches`, `tableDataDriftCells`, `tableSchemaCells`, `tableRowCells`, `tableExactMatchCells`
Columns | `columnsInComparison`, `sourceIncludedColumnCount`, `sourceExcludedColumnCount`, `columnTypeComparisons[]`, `typeSummary`, `structuralMismatchesPerColumn{}`
Per column | `columnMismatchStats{col: {mismatchCount, diffMethod, diffStats{min, max, avg, maxDelta, sumDelta, sumDeltaSq, rowCount, metricRowCount}}}`
Aggregates | `aggregateStats{"<col>_<FUNCTION>": {...}}`
Timing | `sourceExecutionTimeMs`, `targetExecutionTimeMs`
SQL | `sqlSections[]`
Read it with `gcloud storage cat RUN_DIR/results.json`. For partitioned runs it
holds the rolled-up totals only; per-partition numbers are only in BigQuery.
### validation_summary.txt and column_details.txt
Formatted for people: status per pillar, links to the BigQuery results and the
Cloud Storage directory, row counts, sample coverage, mismatch summary, type
differences, and per-column type compatibility, mismatch rate, distance
statistics, and aggregate table. Show them to the user or link them; read the
same numbers from `results.json` or BigQuery instead of parsing the text.
## 4. BigQuery observability tables
All in the results dataset. Query the views; the `_raw` tables back them.
Object | Grain | Key columns
:----------------------------------- | :---------------------------------------- | :----------
`run_history` (view) | One row per run (one table pair) | `run_id`, `status`, `started_at`, `finished_at`, `source_table`, `target_table`, `source_connection`, `target_connection`, `gcs_uri`, `config_hash`, `config_json`, `error_message`, `labels`
`run_metrics` (view) | One row per write per (run, slice) | `run_id`, `slice_id`, `validation_pillar`, `status`, `timestamp`, `metrics_json`, plus projected scalar columns
`column_history` | One row per (run, column), whole run only | `run_id`, `source_table`, `target_table`, `source_column_name`, `target_column_name`, `status` (`MATCH`/`MISMATCH`), `mismatch_count`, `run_timestamp`
`run_history_raw`, `run_metrics_raw` | Storage behind the views | `history_json`, `metrics_json`
Rules for querying `run_metrics`:
* **`slice_id = 'HEAD'`** is the whole-run row. Partitioned runs also have one
row per slice (other `slice_id` values).
* **Deduplicate**: Retries append rows. Keep the latest per (run, slice):
`QUALIFY ROW_NUMBER() OVER (PARTITION BY run_id, slice_id ORDER BY timestamp
DESC) = 1`.
* **Read fields from `metrics_json`**: Some projected view columns are not
populated. `JSON_VALUE(metrics_json, '$.<field>')` with the field names
below always works. Numbers come back as strings; `CAST` them.
`metrics_json` fields (snake case): `overall_status`, `error_message`,
`source_table`, `target_table`, `source_total_row_count`,
`target_total_row_count`, `source_partition_row_count`,
`source_partition_filter`, `target_partition_filter`, `source_rows_queried`,
`joined_row_count`, `source_only_row_count`, `target_only_row_count`,
`mismatch_count`, `mismatch_rate`, `total_mismatches`, `logical_row_mismatches`,
`table_data_drift_cells`, `table_schema_cells`, `table_row_cells`,
`table_exact_match_cells`, `columns_in_comparison`, `sample_coverage`,
`confidence`, `join_stability`, `strategy`, `labels`, `finished_at`, and these
arrays:
* `column_metrics[]`: `name`, `status`, `mismatch_count`, `diff_method`,
`source_type`, `target_type`, `compatibility`, `structural_mismatch_count`,
`min_diff`, `max_diff`, `avg_diff`, `max_delta`, `sum_delta`,
`sum_delta_sq`, `row_count`, `metric_row_count`
* `aggregate_metrics[]`: `column_name`, `function`, `source_value`,
`target_value`, `diff`, `match_result`
* `sql_sections[]`: `title`, `code`
`run_history.config_json` holds the effective table config, comparison keys,
column settings, and source and target column types for the run.
## 5. BigQuery per-run tables
Created in the results dataset for each run. Names use the run ID; partitioned
runs add the slice ID:
```text
run_<run>_<type> # unpartitioned run, or run-level union table
run_<run>_<slice>_<type> # one slice of a partitioned run
run_<run>[_<slice>]_agg_<type>
```
Names use the run ID as written by the backend. List them rather than
guessing. `RUN_KEY` is the run ID as it appears in these names, after the
leading `run_`. Default run IDs are a UTC timestamp and a 4-character suffix
with no `run_` prefix, such as `20261026101500_8f3a` (tables
`run_20261026101500_8f3a_<type>`). In `LIKE`, a distinctive part of it also
works, with any `-` written as `_` (an `_` matches any one character):
```sql
SELECT table_name, table_type
FROM `PROJECT.DATASET.INFORMATION_SCHEMA.TABLES`
WHERE table_name LIKE '%RUN_KEY%'
ORDER BY table_name;
```
Type | One row per | Columns
:------------------------- | :----------------------------------- | :------
`sample` | Staged source row (shared by slices) | Source columns as extracted
`joined` | Joined source/target row | `s_<col>`, `t_<col>`
`mismatches` | Row with at least one difference | `__s_comparison_id`, `__t_comparison_id` (key structs), `__source_only_row`, `__target_only_row`, `s_<col>`, `t_<col>`, `<col>_status`, `<col>_distance`
`mismatches_details` | Mismatched cell (unpivoted) | `__s_comparison_id`, `__t_comparison_id`, `column_name`, `failure_type`, `source_value`, `target_value` (strings), `distance` (FLOAT64)
`agg_source`, `agg_target` | One row per side | `<col>_<FUNCTION>` values
`agg_joined` | Aggregate check | `column_name`, `function`, `source_value`, `target_value`, `diff`, `match_result`
* For partitioned runs, `run_<run>_<type>` (no slice) is a run-level table
that unions all slices. Query it for the whole table and the slice tables
for one partition.
* `mismatches_details` is the easiest table to aggregate (one cell per row).
Use `mismatches` when you need the whole row, or the other columns of a row,
side by side.
* In hash mode (`useAllColumnsAsKey`), `joined` and `mismatches` carry
`row_hash`, `source_count`, and `target_count` instead of per-column values.
## 6. Cloud Storage versus BigQuery
Need | `results.json` | BigQuery
:-------------------------------------- | :---------------------: | :------:
Run status, row counts, mismatch totals | yes | yes (`run_metrics` HEAD)
Per-column statistics and type notes | yes | yes (`column_metrics`)
Aggregate results | yes | yes (`aggregate_metrics`, `agg_joined`)
Per-partition (slice) metrics | no | yes (`run_metrics` slice rows, slice tables)
Mismatched rows and cell values | no | yes (`mismatches`, `mismatches_details`)
History across runs, trends per column | no | yes (`run_history`, `column_history`)
All tables in one query | no (one file per table) | yes
Lifecycle while running, error details | no (written at end) | yes (`run_history.status`, `error_message`)
Effective config and column types | partial | yes (`config_json`)
Source and target query times | yes | no
Needs only Cloud Storage access | yes | no
Use `results.json` for a fast single-table answer or when BigQuery access is
missing. Use BigQuery for anything comparative, per-partition, or row-level.
## 7. Row and cell classification
`<col>_status` and `failure_type` values:
Value | Meaning | Typical cause
:------------ | :------------------------------------------------------------ | :------------
`ROW` | The row exists on one side only (see row direction below) | Missing load, filter difference, duplicates, deletes during migration
`SCHEMA` | The column exists on one side only, or types are incompatible | DDL difference
`DATA_DRIFT` | Row on both sides, value differs beyond tolerance | Conversion, precision, padding, time zone, encoding
`EXACT_MATCH` | Equal (never in `mismatches_details`) | Not applicable
Row direction: `__source_only_row = TRUE` means missing in BigQuery;
`__target_only_row = TRUE` means present only in BigQuery. Rows that exist only
in BigQuery are not reported at row level, even with `brute_force`:
`target_only_row_count` stays 0 and no `__target_only_row` rows appear. They
show up only in the total row counts and aggregates such as `COUNT`.
## 8. Diff methods and distances
Results record the method as `<CATEGORY>_<METHOD>`: the BigQuery column's type
category (`NUMERIC`, `TEMPORAL`, `STRING`, `BYTES`, `BOOLEAN`, `JSON`) and the
`diffMethod` config value (`SUBTRACTION`, `EDIT_DISTANCE`, `LENGTH`,
`BITWISE_HAMMING_DISTANCE`, `IDENTITY`). Match on these recorded values in
`results.json` (`diffMethod`) and `column_metrics[]` (`diff_method`):
Recorded value | Default for | `distance`
:---------------------------------- | :------------------------- | :---------
`NUMERIC_SUBTRACTION` | Numeric | `target - source` (signed)
`TEMPORAL_SUBTRACTION` | `DATE` | Absolute difference in days
`TEMPORAL_SUBTRACTION` | `TIMESTAMP`, `DATETIME` | Absolute difference in **microseconds**
`STRING_EDIT_DISTANCE` | String | Edit distance between the two strings
`STRING_LENGTH`, `BYTES_LENGTH` | (option for string, bytes) | Absolute length difference
`BYTES_BITWISE_HAMMING_DISTANCE` | `BYTES` | `0` equal, `1` different
`BOOLEAN_IDENTITY`, `JSON_IDENTITY` | `BOOL`, `JSON` | `NULL` (equal or not)
* `UNSUPPORTED` means no diff method exists for the column's type (for
example `TIME`); `HASH_MATCH` means hash mode (`useAllColumnsAsKey`), which
has no per-column distance.
* Floating-point columns ignore differences up to 5e-7 even without a
tolerance.
* `distance` is `NULL` when either value is `NULL`. A `NULL` on one side is
still a mismatch; check `source_value`/`target_value`.
* Column statistics (`min_diff`, `max_diff`, `avg_diff`) cover `DATA_DRIFT`
cells only and are rounded to 8 decimal places.
* A one-hour time zone shift shows as a distance of 3,600,000,000 on
timestamps.
## 9. Type compatibility notes
The schema pillar classifies each column pair:
Note | Schema pillar | Meaning
:------------------ | :------------ | :------
`COMPATIBLE` | Pass | Equivalent types
`WIDENED` | Pass | Target holds more (precision, scale, range)
`NARROWED` | Fail | Same family, target holds less; overflow or truncation possible
`COERCED` | Fail | Different representation, not necessarily lossy (for example `JSON` to `STRING`, `DATE` to `STRING`)
`LOSSY_CONVERSION` | Fail | Precision or time components can be lost (integer and float, decimal to float, decimal to integer, `TIMESTAMP` to `DATETIME`/`DATE`/`TIME`, `DATETIME` to `TIMESTAMP`)
`CHANGED_TYPE` | Fail | Incompatible families
`MISSING_IN_SOURCE` | Fail | Column only in BigQuery
`MISSING_IN_TARGET` | Fail | Column only in the source
`UNKNOWN` | Fail | Type could not be read
A schema finding does not mean values differ. Check the column's data mismatches
before recommending a DDL change: a `LOSSY_CONVERSION` column with zero
mismatches is a risk to note, not a defect found.
troubleshooting.md 5.7 KB
# Troubleshooting
Run errors and mismatch signatures with their fixes. For the procedure that
finds these signatures, see the [investigation workflow](investigation.md).
## 1. Run errors
Symptom | Cause | Fix
:------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------- | :--
Exit 1 with a config error | Invalid YAML, connection name with `_` or `-`, `gcsPath` with trailing slash, `;` in a filter or name | Fix the reported key
Exit 1: `dataset is required for BigQuery connection` | `dataset` missing on the BigQuery target connection (required even with fully qualified table names) | Add `dataset` to the target connection
Source connection fails; `connections.yaml` has the wrong `dialect` | `configure` scaffolded another dialect (for example `snowflake` for PostgreSQL metadata) | Set the real `dialect` and its properties; see [connections](connections.md)
Exit 1 with a credentials error | No Application Default Credentials, missing password variable, unreadable secret | `gcloud auth application-default login`; set `BQMS_VALIDATION_<CONN>_PASSWORD` or a secret reference
Driver not found | Teradata, Vertica, Impala, or DuckDB JAR missing (never downloaded), or downloads blocked for other drivers | Put the JAR in `./drivers` or `BQMS_DRIVER_DIR`; see [connections](connections.md)
"Could not initiate BigQuery Migration validation workflow" (exit 0) | No permission or API not enabled in the target project | Fix permissions, then re-run or create the workflow from the printed console link
Run `ERROR` with a missing table | `targetTable.name` points at the wrong dataset (generated names override the connection dataset) | Correct `targetTable.name`
Run `ERROR`, query too complex or resources exceeded | Very wide table | Lower `maxColumnsPerTile`; do not exclude columns
"Planned partition slice count exceeds maxSlices" | Range too large for `partitionSize` | Increase `partitionSize`, raise `maxSlices`, or narrow `whereClause`
Client out of memory | Large sample or many slices in parallel | `JAVA_OPTS=-Xmx8g`; lower `maxConcurrency` or `sampleSize`
No results after exit 0 | Backend still running | Wait for the workflow (see [CLI reference](cli.md#6-tracking-the-backend-workflow))
`results.json` missing, `run_history` row exists | Run in progress or failed before the final report | Check `run_history.status` and `error_message`
## 2. Mismatch signatures
### Row counts differ
* **Evidence**: `source_total_row_count != target_total_row_count` in a run
with the aggregate pillar (data-only runs report a target count of 0),
`ROW` mismatches, or a failed table `COUNT`. Rows that exist only in
BigQuery appear only in the counts, not as `ROW` mismatches.
* **Causes**: one side filtered differently (`whereClause`), loads still
running, rows deleted or inserted after migration, failed load of some
partitions.
* **Fix**: make filters equivalent on both sides; validate against a static
snapshot or quiet window; use per-slice metrics to find failed ranges and
re-load them.
### Rows reported missing, evenly spread
* **Evidence**: many `__source_only_row` rows that a direct lookup finds in
BigQuery, while total row counts match.
* **Cause**: comparison keys are not unique, or key values differ in
representation (padding, case, type).
* **Fix**: correct `comparisonKeys`, add transforms to key columns, or use
`useAllColumnsAsKey` for tables without a key.
### Floating-point or decimal precision
* **Evidence**: tiny distances, `min_diff` around `1e-8`; often `HEALED`.
* **Fix**:
```yaml
columnSettings:
columns:
amount:
tolerance: 0.001
```
### Padding
* **Evidence**: `SUM_LENGTH` differs; edit distance equals trailing spaces.
* **Fix**: `transform: TRIM` on the column.
### Empty string versus NULL
* **Evidence**: column `COUNT` differs while row counts match; one side
`NULL`, the other `''`.
* **Fix**: `transform: EMPTY_TO_NULL` on the column. `TRIM` does not help.
```yaml
columnSettings:
columns:
middle_name:
transform: EMPTY_TO_NULL
```
### Time zone offset
* **Evidence**: one dominant timestamp distance, a multiple of 3,600,000,000
microseconds.
* **Fix**: decide which side is correct. If BigQuery should store UTC, fix the
load. If the difference is only representation, align types or add a
`transformExpression`.
### Wrong values
* **Evidence**: large, varied distances on numeric or string columns, failed
`SUM`/`AVG`, no consistent pattern.
* **Fix**: none in validation config. This is a migration defect; report the
column, affected partitions, row count, and example keys.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE