# Validate the Migration

Source: https://docs.formance.com/v4.0/modules/ledger/migration/validation

Stack: v4.0

A mirror can be `FOLLOWING` and still contain an unacceptable business result. Ledger does not compare source and target balances or state hashes for you.

Use the same validation specification for the rehearsal, the live-following period, and the final frozen-source check. Only the final check runs against a source that can no longer move.

## Define materiality before comparing

For each ledger, record:

- accounts and account groups whose balances must match exactly;
- assets, precisions, and colors to compare;
- transaction and reference samples, including boundaries and high-value cases;
- reverted and backdated transactions;
- metadata keys, expected types, deleted keys, and null behavior;
- transformations and drops that deliberately change the target;
- query, index, authentication, event, and performance requirements;
- who approves each check and what constitutes a blocking difference.

Do not decide that a difference is immaterial during the production cutover without the validation owner.

## Enforce the final comparison boundary

Run this gate after every Ledger v2 writer is frozen. During rehearsal, use it only against a quiesced source; otherwise the source can advance between the two reads.

Set every prerequisite explicitly. The configured `ledgerctl` profile must point to the candidate target cluster and have read access to `$TARGET_LEDGER`. Choose the source transport used by the mirror; do not configure HTTP credentials for a PostgreSQL source.

Save these blocks as one script

The three shell blocks on this page are one program, not independent snippets. `set -euo pipefail`, the `V2_*` exports, the helper functions, and `FINAL_SOURCE_LOG_ID` are defined in earlier blocks and consumed by later ones, and the gate exits with `exit 1` on every failure.

Append them in order to a single file and run that file. Pasting them into an interactive shell works until something fails, at which point `exit 1` closes the session — taking the exported source configuration and the helper functions with it, at the moment a frozen-source window is open and you most need them.

```bash
set -euo pipefail
set +x

export SOURCE_TRANSPORT="postgres" # "http" or "postgres"
export SOURCE_LEDGER="main-v2"
export TARGET_LEDGER="main-target"

# HTTP source only:
# export V2_URL="https://ledger-v2.example.com"
# export V2_TOKEN="<source-read-token>"

# PostgreSQL source only. Build a passwordless, hostname-verifying DSN from
# the same endpoint, database, and identity configured on the mirror. The
# preflight below reassembles V2_PG_DSN from these four variables, so edit
# them rather than the DSN string.
export SOURCE_POSTGRES_AUTH="rds-iam" # "password" or "rds-iam"
export V2_PG_HOST="v2-db.example.com"
export V2_PG_PORT="5432"
export V2_PG_DATABASE="ledger"
export V2_PG_USER="mirror_reader"
export V2_PG_DSN="postgresql://${V2_PG_USER}@${V2_PG_HOST}:${V2_PG_PORT}/${V2_PG_DATABASE}?sslmode=verify-full"

# Password authentication only. Mount this file from a secret manager with
# mode 0600; never put the password in V2_PG_DSN.
export PGPASSFILE="/run/secrets/ledger-v2.pgpass"

# RDS IAM authentication only. Leave the role ARN empty when the current
# runtime identity already has rds-db:connect.
export V2_AWS_REGION="eu-west-1"
export V2_AWS_ASSUME_ROLE_ARN="${V2_AWS_ASSUME_ROLE_ARN:-}"
export V2_AWS_ROLE_SESSION_NAME="ledger-v2-source-head-$$"

: "${SOURCE_TRANSPORT:?set SOURCE_TRANSPORT}"
: "${SOURCE_LEDGER:?set SOURCE_LEDGER}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
command -v jq >/dev/null
command -v ledgerctl >/dev/null

case "$SOURCE_TRANSPORT" in
  http)
    : "${V2_URL:?set V2_URL for an HTTP source}"
    : "${V2_TOKEN:?set V2_TOKEN for an HTTP source}"
    command -v curl >/dev/null
    ;;
  postgres)
    : "${SOURCE_POSTGRES_AUTH:?set SOURCE_POSTGRES_AUTH}"
    : "${V2_PG_HOST:?set V2_PG_HOST}"
    : "${V2_PG_PORT:?set V2_PG_PORT}"
    : "${V2_PG_DATABASE:?set V2_PG_DATABASE}"
    : "${V2_PG_USER:?set V2_PG_USER}"

    # Constrain the parts, then build the DSN. Do not inspect a supplied one:
    # libpq percent-decodes URI parameter names and honours quoting in
    # keyword/value conninfo, so no shell-level check can establish the sslmode
    # libpq will actually apply. Assembling the URI from validated components
    # makes verify-full true by construction, with nothing left to parse.
    [[ "$V2_PG_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || {
      printf 'V2_PG_HOST must be a bare hostname\n' >&2
      exit 1
    }
    [[ "$V2_PG_PORT" =~ ^[1-9][0-9]*$ ]] || {
      printf 'V2_PG_PORT must be a port number\n' >&2
      exit 1
    }
    [[ "$V2_PG_DATABASE" =~ ^[A-Za-z0-9_-]+$ ]] || {
      printf 'V2_PG_DATABASE must be a bare database name\n' >&2
      exit 1
    }
    [[ "$V2_PG_USER" =~ ^[A-Za-z0-9_-]+$ ]] || {
      printf 'V2_PG_USER must be a bare role name\n' >&2
      exit 1
    }

    V2_PG_DSN="postgresql://${V2_PG_USER}@${V2_PG_HOST}:${V2_PG_PORT}/${V2_PG_DATABASE}?sslmode=verify-full"

    command -v psql >/dev/null

    case "$SOURCE_POSTGRES_AUTH" in
      password)
        : "${PGPASSFILE:?set PGPASSFILE for password authentication}"
        if [ ! -r "$PGPASSFILE" ]; then
          printf 'PGPASSFILE must be a readable, secret-backed mode-0600 file\n' >&2
          exit 1
        fi
        pgpass_mode="$(stat -c '%a' "$PGPASSFILE" 2>/dev/null || stat -f '%Lp' "$PGPASSFILE")"
        if [ "$pgpass_mode" != "600" ]; then
          printf 'PGPASSFILE must have mode 0600; found %s\n' "$pgpass_mode" >&2
          exit 1
        fi
        ;;
      rds-iam)
        : "${V2_AWS_REGION:?set V2_AWS_REGION}"
        : "${V2_AWS_ROLE_SESSION_NAME:?set V2_AWS_ROLE_SESSION_NAME}"
        command -v aws >/dev/null
        ;;
      *)
        printf 'unsupported SOURCE_POSTGRES_AUTH: %s\n' \
          "$SOURCE_POSTGRES_AUTH" >&2
        exit 1
        ;;
    esac
    ;;
  *)
    printf 'unsupported SOURCE_TRANSPORT: %s\n' "$SOURCE_TRANSPORT" >&2
    exit 1
    ;;
esac
```

For a PostgreSQL source, the reader needs `CONNECT` on the database, `USAGE` on `_system` and the selected bucket schema, `SELECT` on `_system.ledgers`, and `SELECT` on the selected bucket's `logs` table. It does not need write access. Protect credentials as secrets, keep shell tracing disabled, and use the same hostname, database, TLS policy, and identity that the mirror uses.

Define the PostgreSQL authentication helpers and one source-head function, then use them for this gate. `V2_PG_HOST` must be the exact RDS endpoint used in the DSN, not a different alias. The RDS IAM helper generates a fresh 15-minute token for every psql process. When an assume-role ARN is set, it also obtains fresh role credentials for that invocation. Neither the token nor the temporary AWS credentials enter command-line arguments, global environment variables, or evidence files.

```bash
generate_source_postgres_iam_token() {
  local credentials_json
  local access_key_id
  local secret_access_key
  local session_token

  if [ -z "$V2_AWS_ASSUME_ROLE_ARN" ]; then
    AWS_PAGER="" aws rds generate-db-auth-token \
      --no-cli-pager \
      --hostname "$V2_PG_HOST" \
      --port "$V2_PG_PORT" \
      --region "$V2_AWS_REGION" \
      --username "$V2_PG_USER" || return
    return
  fi

  credentials_json="$(AWS_PAGER="" aws sts assume-role \
    --no-cli-pager \
    --role-arn "$V2_AWS_ASSUME_ROLE_ARN" \
    --role-session-name "$V2_AWS_ROLE_SESSION_NAME" \
    --duration-seconds 900 \
    --output json)" || return

  access_key_id="$(jq -er '.Credentials.AccessKeyId' \
    <<<"$credentials_json")" || return
  secret_access_key="$(jq -er '.Credentials.SecretAccessKey' \
    <<<"$credentials_json")" || return
  session_token="$(jq -er '.Credentials.SessionToken' \
    <<<"$credentials_json")" || return

  AWS_ACCESS_KEY_ID="$access_key_id" \
  AWS_SECRET_ACCESS_KEY="$secret_access_key" \
  AWS_SESSION_TOKEN="$session_token" \
  AWS_PAGER="" \
    aws rds generate-db-auth-token \
      --no-cli-pager \
      --hostname "$V2_PG_HOST" \
      --port "$V2_PG_PORT" \
      --region "$V2_AWS_REGION" \
      --username "$V2_PG_USER" || return
}

source_psql() {
  local iam_token

  case "$SOURCE_POSTGRES_AUTH" in
    password)
      psql "$V2_PG_DSN" "$@"
      ;;
    rds-iam)
      iam_token="$(generate_source_postgres_iam_token)" || return
      if [ -z "$iam_token" ] || [[ "$iam_token" == *$'\n'* ]]; then
        printf 'RDS IAM token generation returned an invalid value\n' >&2
        return 1
      fi
      PGPASSWORD="$iam_token" psql "$V2_PG_DSN" "$@"
      ;;
  esac
}

read_source_log_id() {
  local source_head_json
  local source_log_id

  case "$SOURCE_TRANSPORT" in
    http)
      source_head_json="$(curl --fail --silent --show-error \
        --header "Authorization: Bearer $V2_TOKEN" \
        "$V2_URL/v2/$SOURCE_LEDGER/logs?pageSize=1")"

      source_log_id="$(jq -er '
        .cursor.data
        | if type != "array" then
            error("source response has no cursor.data array")
          elif length == 0 then
            "0"
          else
            (.[0].id | tostring) as $id
            | if $id | test("^[1-9][0-9]*$") then
                $id
              else
                error("newest source log has an invalid id")
              end
          end
      ' <<<"$source_head_json")"
      ;;
    postgres)
      source_log_id="$(
        source_psql \
          --no-psqlrc \
          --no-password \
          --set=ON_ERROR_STOP=1 \
          --set=source_ledger="$SOURCE_LEDGER" \
          --quiet \
          --tuples-only \
          --no-align <<'SQL'
SELECT bucket AS source_bucket
FROM _system.ledgers
WHERE name = :'source_ledger'
\gset

\if :{?source_bucket}
SELECT COALESCE(MAX(id), 0)::text
FROM :"source_bucket".logs
WHERE ledger = :'source_ledger';
\else
\warn 'source ledger did not resolve to exactly one bucket'
\endif
SQL
      )"
      ;;
  esac

  if [[ "$source_log_id" == *$'\n'* ]] ||
     ! [[ "$source_log_id" =~ ^(0|[1-9][0-9]*)$ ]]; then
    printf 'source head must be exactly one unsigned integer row\n' >&2
    return 1
  fi

  printf '%s\n' "$source_log_id"
}

FINAL_SOURCE_LOG_ID="$(read_source_log_id)"

jq -n \
  --arg finalSourceLogId "$FINAL_SOURCE_LOG_ID" \
  '{finalSourceLogId: $finalSourceLogId}' \
  > source-head.json
```

The two paths do not rest on the same guarantee. The PostgreSQL query takes `MAX(id)`, so it is order-independent. The HTTP path reads the first element of a one-item page and treats it as the newest log, which assumes the endpoint returns logs newest-first — an ordering the v2 API contract does not state. Confirm it holds on the Ledger v2 version you are migrating from before you trust the recorded `finalSourceLogId`: if the endpoint ever returns oldest-first, the gate still fails closed, but the evidence file records the wrong boundary while appearing complete.

Read the target once, capture the complete progress tuple, and stop unless the target is a mirror at the same frozen boundary with no active error:

```bash
TARGET_LEDGER_JSON="$(ledgerctl ledgers get "$TARGET_LEDGER" --json)"

jq -e '.mirrorSyncProgress != null' <<<"$TARGET_LEDGER_JSON" >/dev/null

TARGET_MODE="$(jq -r '.mode // "(absent)"' <<<"$TARGET_LEDGER_JSON")"
if ! jq -e '
  .mirrorSyncProgress as $p
  | ["cursor", "sourceLogCount", "remainingLogs"]
  | all(. as $k
      | if ($p | has($k))
        then ($p[$k] | tostring | test("^[0-9]+$"))
        else true
        end)
' <<<"$TARGET_LEDGER_JSON" >/dev/null; then
  printf 'mirrorSyncProgress counters must be omitted or unsigned integers\n' >&2
  exit 1
fi

TARGET_CURSOR="$(jq -er '(.mirrorSyncProgress.cursor // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
TARGET_SOURCE_HEAD="$(jq -er '(.mirrorSyncProgress.sourceLogCount // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
TARGET_REMAINING="$(jq -er '(.mirrorSyncProgress.remainingLogs // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
TARGET_ERROR_JSON="$(jq -c '.mirrorSyncProgress.error // null' <<<"$TARGET_LEDGER_JSON")"

if [ "$TARGET_MODE" != "LEDGER_MODE_MIRROR" ] ||
   [ "$TARGET_CURSOR" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$TARGET_SOURCE_HEAD" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$TARGET_REMAINING" != "0" ] ||
   [ "$TARGET_ERROR_JSON" != "null" ]; then
  printf '%s\n' \
    "final mirror gate failed" \
    "source=$FINAL_SOURCE_LOG_ID" \
    "mode=$TARGET_MODE" \
    "cursor=$TARGET_CURSOR" \
    "observedSource=$TARGET_SOURCE_HEAD" \
    "remaining=$TARGET_REMAINING" \
    "errorPresent=$([ "$TARGET_ERROR_JSON" = "null" ] && printf no || printf yes)" >&2

  if [ "$TARGET_ERROR_JSON" != "null" ]; then
    if (set -o noclobber; umask 077; printf '%s\n' "$TARGET_ERROR_JSON" \
          > mirror-error.json) 2>/dev/null
    then
      printf 'persisted mirror error written to mirror-error.json (mode 0600)\n' >&2
    else
      printf 'refusing to write mirror-error.json: the path already exists\n' >&2
    fi
  fi

  exit 1
fi

jq \
  --arg finalSourceLogId "$FINAL_SOURCE_LOG_ID" \
  '{
    name,
    mode,
    finalSourceLogId: $finalSourceLogId,
    mirrorSyncProgress
  }' <<<"$TARGET_LEDGER_JSON" > target-ledger.json
```

The failure dump reports only whether an error is present. The persisted mirror error is the raw source, translation or apply error, so it can echo the source endpoint or a PostgreSQL DSN, and it must stay out of CI logs and transcripts. Since the gate exits on failure, the error cannot be left in a shell variable for the operator to inspect: it is written to `mirror-error.json` with mode `0600` instead. `set -o noclobber` is deliberate. `umask` only applies when a file is created, so a plain redirect into an existing path would keep that file's mode while claiming `0600`, or follow a symlink left there. Under `noclobber` the shell opens with `O_EXCL`, so an existing path — regular file or symlink — makes the write fail rather than succeed somewhere unintended. That is one atomic operation, unlike removing the path first and then creating it, which leaves a window for a symlink to be planted in between. If the write is refused, inspect or remove the existing file and rerun. Read that file, then delete it with the rest of the credential-bearing artifacts.

Two details of the wire format shape those reads, and a gate written without both rejects the one state it exists to accept. The counters are 64-bit integers, so they arrive as JSON strings rather than numbers — assert on their digits, not on `type == "number"`. And a field sitting at its default value is omitted from the response entirely, which is exactly what happens to `remainingLogs` on a fully caught-up mirror and to `mode` on a normal ledger.

Absent and present-but-wrong are not the same thing, which is why the check tests `has()` rather than defaulting with `//`. An omitted counter is a protobuf default and is accepted as zero; a counter that is present as `null`, `false`, or a non-integer is a contract violation and fails the gate. `// 0` alone cannot tell those apart, because jq treats `null` and `false` as absent — so a malformed response would have been read as a legitimately empty source. Once the check has established that every present counter is digits, the reads below can default with `//` safely.

Keep the two filtered evidence files with the migration record. Do not save the complete structured ledger response. This ledger read redacts the OAuth2 client secret and any password in the source configuration, but the response still names the source endpoint, database host and user, and OAuth2 client ID. Other surfaces, such as the creation log entry, audit entries, and backups, return the credentials without redaction; see [Create a Mirror](https://docs.formance.com/v4.0/modules/ledger/migration/create-mirror#resolve-an-ambiguous-ledgerctl-result) for the complete list.

## Run the technical checks

| Check                | Evidence                                                               | Pass condition                                                                         |
| -------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Log coverage         | Final source log ID, cursor, observed source head, and remaining logs. | Cursor equals the recorded source ID; remaining logs are zero; no error is present.    |
| Ledger identity      | Source worksheet and target ledger info.                               | Source and target names map as planned; target remains in mirror mode before approval. |
| Transaction coverage | Counts by agreed range plus sampled IDs and references.                | Matches after documented drops and transformations.                                    |
| Reversions           | Source transaction, reversion, and resulting target state.             | Original and compensating effects are represented as expected.                         |
| Account coverage     | Counts by material prefix and selected boundary accounts.              | All required accounts exist at their expected target addresses.                        |
| Balances and volumes | Per account/group, asset, and color comparison.                        | Exact equality except for pre-approved transformation effects.                         |
| Metadata             | Account and transaction key/value/type samples.                        | Values, deletions, typed nulls, and conversions match the specification.               |
| Rewrite evidence     | Rule-file hash and fixture results.                                    | Every expected match, non-match, collision, and drop is explained.                     |
| Indexes              | Index status from every target replica.                                | Every index required by a production query is ready.                                   |
| Mirror health        | Time series of cursor/head/error.                                      | The target follows normally and has no unresolved error.                               |

Counts are useful for coverage but do not prove accounting equality. Pair them with balance, volume, and representative transaction checks.

## Compare business invariants

Translate each domain invariant into a repeatable source query and target query. Examples include:

- customer liabilities equal the corresponding safeguarding or settlement accounts;
- clearing account balances remain within an approved range;
- the sum of wallet balances per asset matches the source result;
- a payout transaction preserves principal, fee, and destination totals;
- every settled business reference remains unique;
- no account moved into an unintended prefix after address rewriting.

For each invariant, save:

1. query or command version;
2. exact source and target parameters;
3. source log boundary;
4. normalized result;
5. expected transformation adjustment;
6. pass/fail result and reviewer.

Do not compare formatted monetary values with floating-point arithmetic. Compare Ledger integer amounts at the declared asset precision.

## Validate transformed data

For each rewrite rule, reconcile the fixture register against the target:

| Rule effect              | Required proof                                                                            |
| ------------------------ | ----------------------------------------------------------------------------------------- |
| Address rewrite          | Positive and negative fixtures, collision analysis, and account-group balance comparison. |
| Metadata set/delete      | Original value, expected target value/type, missing-field behavior, and deletion result.  |
| Typed coercion           | Valid conversion and invalid value represented as the expected typed null.                |
| Derived account metadata | Captured segments, target account, type, and non-matching address.                        |
| Drop                     | Source log ID, reason, transaction ID when present, and accounting impact.                |

An unexplained difference is a failed validation, even if it appears to match the intent of a rule.

## Validate application workflows

Connect a non-production application instance to the target. A mirror rejects writes, so split the test:

- run read, filter, pagination, metadata-read, and reporting workflows against the production-shaped mirror;
- run create, retry, revert, metadata-write, and bulk workflows against a disposable normal target built from the same release;
- test the final endpoint and authentication switch in the cutover rehearsal;
- verify every target identity has the intended scope and no broader one;
- test timeout, conflict, unavailable, and rate-limit handling where relevant.

The application must use the target contract. A correct data copy does not make a Ledger v2 client compatible.

## Validate event consumers

Mirrored Ledger v2 entries are ordinary target logs. Every supported imported change produces a standard target event, and a newly created sink starts at cursor `0` and replays all supported retained history. The current sink configuration does not provide a start cursor that opts out of that replay.

Treat historical replay as part of the migration, not as an optional event mode. Keep the target destination or consumer quarantined while Ledger v2 remains the production authority: it may durably receive and inspect target events, but it must not repeat business effects already produced from the Ledger v2 pipeline.

For every downstream consumer:

- confirm the target sink configuration;
- verify the standard target event type and payload for imported transactions, reversions, and metadata changes;
- persist and deduplicate target at-least-once delivery using a stable target source identity plus `logSequence`;
- deduplicate business effects across versions with a key that survives the Ledger v2-to-target translation;
- run the full retained replay through quarantine and prove that no historical message produces a second effect;
- after the mirror reaches the frozen source boundary, record the target sink cursor and destination or consumer checkpoint that prove replay has drained through the corresponding target event history;
- verify recovery and redelivery after temporarily interrupting the destination;
- activate effects only for events after the approved cutover boundary, then test the first post-boundary event.

Do not use only the target `logSequence` as the cross-version business key: it belongs to the target cluster and does not match the identity used by an existing Ledger v2 pipeline. Document the business key for every effecting event type. If one cannot be defined, the consumer is not ready for cutover.

The mirror cursor is a Ledger v2 log ID; the sink cursor is a target global log sequence. They are different sequence spaces and must not be compared numerically.

Record the point at which the Ledger v2 consumer stops, the replay checkpoint reached in quarantine, and the point at which target effects become active. The activation boundary is migration evidence enforced by your consumer workflow; it is not a configurable sink start cursor.

## Validate operational readiness

- target cluster has a stable leader and quorum;
- disk, WAL, memory, and compaction headroom remain within the approved budget;
- replay and query latency meet the migration objectives;
- required indexes are ready on every replica;
- authentication, TLS, monitoring, alerts, backup, and incident ownership are active;
- administrators can read mirror progress and promotion status without exposing source credentials.

## Store the evidence

Use a durable record rather than a chat transcript. One check can be represented as:

```yaml
check: material-customer-liability-balance
sourceLedger: "<source-ledger>"
sourceLogId: 4821931
targetLedger: "<target-ledger>"
targetCursor: 4821931
queryVersion: 4f36a9e
expectedAdjustment: none
result: pass
evidence: s3://migration-evidence/<target-ledger>/2026-08-01/liability.json
reviewer: finance-platform-owner
reviewedAt: 2026-08-01T10:24:00Z
```

Keep secrets and access tokens out of the record.

## Final approval gate

- [ ] The source is frozen and the final source log ID is recorded.
- [ ] Target cursor equals that final ID, remaining logs are zero, and no error is present.
- [ ] Transactions, references, accounts, balances, volumes, and reversions pass.
- [ ] Metadata, typed nulls, transformations, and drops pass.
- [ ] Required indexes and queries pass.
- [ ] Client authentication and production workflows pass.
- [ ] Target event replay has drained through the event boundary captured after the final frozen-source check.
- [ ] Historical target events cannot repeat Ledger v2 business effects.
- [ ] Sink and consumer checkpoints, stable deduplication keys, and the activation boundary are recorded.
- [ ] Recovery, redelivery, and the rehearsal's first post-boundary event pass.
- [ ] Performance and operational readiness pass.
- [ ] Every difference has an owner-approved explanation.
- [ ] The validation and migration owners sign the evidence.

Do not promote because the maintenance window is ending. If a material check fails or lacks evidence, keep Ledger v2 frozen only as long as the approved window allows, then resume it and schedule another cutover.

Continue with [Cut Over and Promote](https://docs.formance.com/v4.0/modules/ledger/migration/cut-over-and-promote) only after the final approval gate passes.
