# Create a Mirror

Source: https://docs.formance.com/v4.0/modules/ledger/migration/create-mirror

Stack: v4.0

Mirror mode is a creation-time choice. Create a new target with its source and optional transformations in one operation.

If the target model must differ from Ledger v2, finish [Transform Mirrored Data](https://docs.formance.com/v4.0/modules/ledger/migration/transformations) before running the commands on this page. Rewrite rules cannot be added or changed after creation.

You cannot convert an existing normal ledger into a mirror. While the target is in mirror mode, application writes are rejected; only the mirror worker imports Ledger v2 logs.

## Choose a creation surface

| Surface     | Use it for                                                                                                | Credential behavior                                                                                                                  |
| ----------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `ledgerctl` | Controlled administration, including clusters that require signed writes, or a non-Kubernetes deployment. | Accepts request-signing keys, secrets, and DSNs as CLI or profile values. Protect the environment, process list, and command output. |
| HTTP API    | Programmatic creation only when the target accepts unsigned writes.                                       | Accepts OAuth2 secrets or a PostgreSQL DSN inline in the request body. Request signing and RDS IAM fields are not exposed over HTTP. |

The source configuration and rewrite rules become part of the immutable ledger configuration. Restrict access to ledger configuration and audit data accordingly.

Operator-managed mirror creation is not supported in the Stack v4 preview. Use the current `ledgerctl` or HTTP workflow only when direct management is approved for the target.

## Create a mirror with `ledgerctl`

Set the values for this `ledgerctl` session. Configure the target Ledger endpoint and authentication through your normal `ledgerctl` profile.

When the target has `require_signatures=true`, configure that profile with a registered Ed25519 key or add `--signing-key <seed-file> --signing-key-id <registered-key-id>` before `ledgers create`. `ledgerctl` signs the complete gRPC Apply batch. The target still requires the caller's normal authorization scopes. The examples below assume the active profile supplies these values when mandatory signing is enabled; see [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing).

`ledgerctl ledgers create` attaches an idempotency key only when you pass `--idempotency-key`; it never generates one. The examples below pass a key generated once per creation attempt. While Ledger retains that key, 24 hours by default, rerunning the identical command returns the original outcome instead of creating the ledger again or failing because it now exists. Keys share one cluster-wide namespace, so never reuse one for a different operation, and change no flag on a rerun: the same key with a different request is rejected as a key conflict. Do not put the command in an unbounded retry loop. If the outcome is still unknown, read the exact target ledger and resolve it as described below.

```bash
export TARGET_LEDGER="main-target"
export SOURCE_LEDGER="main-v2"
export V2_URL="https://ledger-v2.example.com"
export CREATE_IDEMPOTENCY_KEY="create-mirror:$TARGET_LEDGER:$(date -u +%Y%m%dT%H%M%SZ)"
```

For an HTTP source without OAuth2:

```bash
ledgerctl ledgers create "$TARGET_LEDGER" \
  --idempotency-key "$CREATE_IDEMPOTENCY_KEY" \
  --mode mirror \
  --mirror-source-type http \
  --mirror-ledger-name "$SOURCE_LEDGER" \
  --mirror-base-url "$V2_URL"
```

For OAuth2, add all credential fields together:

```bash
export V2_CLIENT_ID="ledger-mirror"
export V2_CLIENT_SECRET="<source-client-secret>"
export V2_TOKEN_ENDPOINT="https://auth.example.com/oauth/token"
export V2_SCOPE="ledger:read"

ledgerctl ledgers create "$TARGET_LEDGER" \
  --idempotency-key "$CREATE_IDEMPOTENCY_KEY" \
  --mode mirror \
  --mirror-source-type http \
  --mirror-ledger-name "$SOURCE_LEDGER" \
  --mirror-base-url "$V2_URL" \
  --mirror-oauth2-client-id "$V2_CLIENT_ID" \
  --mirror-oauth2-client-secret "$V2_CLIENT_SECRET" \
  --mirror-oauth2-token-endpoint "$V2_TOKEN_ENDPOINT" \
  --mirror-oauth2-scopes "$V2_SCOPE"
```

For PostgreSQL password authentication, use an ephemeral environment variable to keep the URI DSN out of shell history:

```bash
export V2_MIRROR_DSN="postgres://ledger_mirror:<password>@source.example.com:5432/ledger?sslmode=verify-full"

ledgerctl ledgers create "$TARGET_LEDGER" \
  --idempotency-key "$CREATE_IDEMPOTENCY_KEY" \
  --mode mirror \
  --mirror-source-type postgres \
  --mirror-ledger-name "$SOURCE_LEDGER" \
  --mirror-dsn "$V2_MIRROR_DSN"
```

The shell still expands secrets and DSNs into command-line arguments. Run `ledgerctl` from a restricted administration environment, prevent untrusted local process inspection, and unset the variables afterward.

The source database user needs permission to connect to the database, resolve the source ledger's bucket, and read that bucket's logs. Ask the source database administrator to replace the database, role, and bucket placeholders before applying grants:

```sql
GRANT CONNECT ON DATABASE ledger TO ledger_mirror;
GRANT USAGE ON SCHEMA _system, "<bucket>" TO ledger_mirror;
GRANT SELECT ON TABLE _system.ledgers, "<bucket>".logs TO ledger_mirror;
```

Ledger reads `_system.ledgers` to find `<bucket>` for `SOURCE_LEDGER`, then queries that schema's `logs` table. A table-level `SELECT` grant without database `CONNECT` and schema `USAGE` is insufficient.

For RDS IAM, the DSN must use URI form, contain no password, and declare an explicit TLS mode:

```bash
export V2_MIRROR_DSN="postgres://ledger_mirror@source.example.com:5432/ledger?sslmode=verify-full"
export V2_AWS_REGION="eu-west-1"

ledgerctl ledgers create "$TARGET_LEDGER" \
  --idempotency-key "$CREATE_IDEMPOTENCY_KEY" \
  --mode mirror \
  --mirror-source-type postgres \
  --mirror-ledger-name "$SOURCE_LEDGER" \
  --mirror-dsn "$V2_MIRROR_DSN" \
  --mirror-aws-iam-region "$V2_AWS_REGION"
```

The target Ledger runtime identity needs `rds-db:connect` permission for the exact RDS database-user ARN. Add `--mirror-aws-iam-assume-role-arn <role-arn>` when that identity must assume another role; the base identity then needs `sts:AssumeRole`, and the assumed role needs `rds-db:connect`.

### Resolve an ambiguous `ledgerctl` result

After a timeout, connection loss, or unknown CLI result, you can rerun the identical `ledgers create` command with the same `CREATE_IDEMPOTENCY_KEY` while the key is retained. Otherwise, or if the outcome is still unclear, retry only the read:

```bash
set -euo pipefail

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

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

Then run the mode, source, progress, and read-only assertions in [Verify creation and read-only behavior](#verify-creation-and-read-only-behavior). Resolve the outcome as follows:

| Read outcome                                                                        | Decision                                                                                             |
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| The exact target exists and every assertion matches the requested source and rules. | Creation committed. Continue without another create request.                                         |
| The target exists but its mode, source, credentials, batch size, or rules differ.   | Stop. Treat it as a name collision or unexpected state; do not delete or overwrite it automatically. |
| The read times out, is unavailable, or returns an unclassified error.               | State remains unknown. Retry the read, not the create request.                                       |
| The authoritative target returns an explicit `NotFound`.                            | The target is definitively absent. A new, approved create attempt is allowed.                        |

Ledger redacts the mirror credentials only in the ledger reads: HTTP `GET /v3/{ledger}` and `GET /v3/`, gRPC `GetLedger` and `ListLedgers`, and the `ledgerctl ledgers` commands built on them, such as `get`, `list`, and `configuration`. In those reads, the OAuth2 client secret reads as `[redacted]`, and a password, a passwordless HTTP(S) username, or a credential query parameter in the source URL, token endpoint, or DSN reads as `xxxxx`. Ledger also re-encodes any query string in those URLs, so its parameters can come back sorted by name. The response still names the source endpoint, database host and user, and OAuth2 client ID. Compare it only in the restricted administration environment, emit a Boolean result, and do not store or print the raw response.

The redaction does not cover:

- the create response: the HTTP `201` body, the gRPC `Apply` response, and `ledgerctl ledgers create --json` return the source configuration as submitted, so discard them as described below;
- the global log entry that records the ledger's creation. `GET /v3/_/logs/{sequence}`, gRPC `GetLog`, and `ledgerctl logs get` return its `mirrorSource` with the full credentials to callers with `ledger:OpsRead`;
- audit entry details, whose serialized orders carry the same create request to callers with `ledger:AuditRead`;
- backups.

Restrict `ledger:OpsRead` and `ledger:AuditRead`, avoid logging raw log or audit responses, and treat backups as secret-bearing.

## Create an HTTP mirror through the HTTP API

The caller needs the effective `ledger:LedgerWrite` scope. With the default scope mapping, the virtual `ledger:write` scope includes it.

The HTTP create handler submits an unsigned request. It is rejected when the target has `require_signatures=true`, regardless of the bearer token's scopes. Use `ledgerctl` with a registered signing key or a client that sends a signed gRPC `ApplyRequest`, as described in [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing). Do not disable mandatory signing to create the mirror.

Build the body once, save it with restrictive permissions, and generate one stable idempotency key for this creation attempt. The body contains the source client secret, so keep these files only in the restricted administration environment and never add them to the migration record.

```bash
set -euo pipefail
umask 077

export TARGET_URL="https://ledger.example.com"
export TARGET_TOKEN="<target-access-token>"
export TARGET_LEDGER="main-target"
export SOURCE_LEDGER="main-v2"
export V2_URL="https://ledger-v2.example.com"
export V2_CLIENT_ID="ledger-mirror"
export V2_CLIENT_SECRET="<source-client-secret>"
export V2_TOKEN_ENDPOINT="https://auth.example.com/oauth/token"
export V2_SCOPE="ledger:read"
export MIRROR_CREATE_TIMEOUT_SECONDS="30"

export MIRROR_CREATE_BODY_FILE="mirror-create-$TARGET_LEDGER.request.json"
export MIRROR_CREATE_KEY_FILE="mirror-create-$TARGET_LEDGER.idempotency-key"
export MIRROR_CREATE_URL_FILE="mirror-create-$TARGET_LEDGER.request-url"
export MIRROR_CREATE_BODY_SHA256_FILE="mirror-create-$TARGET_LEDGER.request.sha256"
export MIRROR_CREATE_RESPONSE_PREFIX="mirror-create-$TARGET_LEDGER.response"

for value in \
  TARGET_URL TARGET_TOKEN TARGET_LEDGER SOURCE_LEDGER \
  V2_URL V2_CLIENT_ID V2_CLIENT_SECRET V2_TOKEN_ENDPOINT V2_SCOPE \
  MIRROR_CREATE_TIMEOUT_SECONDS MIRROR_CREATE_BODY_FILE \
  MIRROR_CREATE_KEY_FILE MIRROR_CREATE_URL_FILE \
  MIRROR_CREATE_BODY_SHA256_FILE \
  MIRROR_CREATE_RESPONSE_PREFIX; do
  test -n "${!value:-}" || {
    printf 'missing creation variable: %s\n' "$value" >&2
    exit 1
  }
done

[[ "$MIRROR_CREATE_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]] || {
  printf 'MIRROR_CREATE_TIMEOUT_SECONDS must be a positive integer\n' >&2
  exit 1
}

command -v awk >/dev/null
command -v curl >/dev/null
command -v jq >/dev/null
command -v openssl >/dev/null

for file in \
  "$MIRROR_CREATE_BODY_FILE" \
  "$MIRROR_CREATE_KEY_FILE" \
  "$MIRROR_CREATE_URL_FILE" \
  "$MIRROR_CREATE_BODY_SHA256_FILE"; do
  test ! -e "$file" || {
    printf 'creation evidence already exists; do not overwrite it: %s\n' "$file" >&2
    exit 1
  }
done

jq -n \
  --arg sourceLedger "$SOURCE_LEDGER" \
  --arg sourceUrl "$V2_URL" \
  --arg clientId "$V2_CLIENT_ID" \
  --arg clientSecret "$V2_CLIENT_SECRET" \
  --arg tokenEndpoint "$V2_TOKEN_ENDPOINT" \
  --arg scope "$V2_SCOPE" \
  '{
  mode: "MIRROR",
  mirrorSource: {
    ledgerName: $sourceLedger,
    type: "http",
    baseUrl: $sourceUrl,
    oauth2ClientId: $clientId,
    oauth2ClientSecret: $clientSecret,
    oauth2TokenEndpoint: $tokenEndpoint,
    oauth2Scopes: [$scope],
    batchSize: 100
  }
}' > "$MIRROR_CREATE_BODY_FILE"

MIRROR_CREATE_KEY="mirror-create-$(openssl rand -hex 16)"
test "${#MIRROR_CREATE_KEY}" -le 256
printf '%s\n' "$MIRROR_CREATE_KEY" > "$MIRROR_CREATE_KEY_FILE"
printf '%s\n' "$TARGET_URL/v3/$TARGET_LEDGER" > "$MIRROR_CREATE_URL_FILE"
openssl dgst -sha256 -r "$MIRROR_CREATE_BODY_FILE" \
  > "$MIRROR_CREATE_BODY_SHA256_FILE"
```

Submit the saved bytes. This block can be repeated after an ambiguous result because it reloads the same key and refuses to continue if the body hash changed:

```bash
set -euo pipefail
umask 077

: "${TARGET_URL:?set TARGET_URL}"
: "${TARGET_TOKEN:?set TARGET_TOKEN}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
: "${MIRROR_CREATE_TIMEOUT_SECONDS:?set MIRROR_CREATE_TIMEOUT_SECONDS}"
: "${MIRROR_CREATE_BODY_FILE:?set MIRROR_CREATE_BODY_FILE}"
: "${MIRROR_CREATE_KEY_FILE:?set MIRROR_CREATE_KEY_FILE}"
: "${MIRROR_CREATE_URL_FILE:?set MIRROR_CREATE_URL_FILE}"
: "${MIRROR_CREATE_BODY_SHA256_FILE:?set MIRROR_CREATE_BODY_SHA256_FILE}"
: "${MIRROR_CREATE_RESPONSE_PREFIX:?set MIRROR_CREATE_RESPONSE_PREFIX}"
command -v awk >/dev/null
command -v curl >/dev/null
command -v date >/dev/null
command -v openssl >/dev/null
command -v tr >/dev/null
test -f "$MIRROR_CREATE_BODY_FILE"
test -f "$MIRROR_CREATE_KEY_FILE"
test -f "$MIRROR_CREATE_URL_FILE"
test -f "$MIRROR_CREATE_BODY_SHA256_FILE"

MIRROR_CREATE_KEY="$(tr -d '\n' < "$MIRROR_CREATE_KEY_FILE")"
: "${MIRROR_CREATE_KEY:?saved idempotency key is empty}"
test "${#MIRROR_CREATE_KEY}" -le 256
MIRROR_CREATE_URL="$(tr -d '\n' < "$MIRROR_CREATE_URL_FILE")"
: "${MIRROR_CREATE_URL:?saved request URL is empty}"
test "$MIRROR_CREATE_URL" = "$TARGET_URL/v3/$TARGET_LEDGER"
EXPECTED_BODY_SHA256="$(awk '{print $1}' "$MIRROR_CREATE_BODY_SHA256_FILE")"
ACTUAL_BODY_SHA256="$(openssl dgst -sha256 -r "$MIRROR_CREATE_BODY_FILE" | awk '{print $1}')"
test "$ACTUAL_BODY_SHA256" = "$EXPECTED_BODY_SHA256"

MIRROR_CREATE_RESPONSE_FILE="${MIRROR_CREATE_RESPONSE_PREFIX}.$(date -u +%Y%m%dT%H%M%SZ)-$$-$RANDOM.body"
test ! -e "$MIRROR_CREATE_RESPONSE_FILE"

set +e
MIRROR_CREATE_STATUS="$(curl --silent --show-error \
  --max-time "$MIRROR_CREATE_TIMEOUT_SECONDS" \
  --output "$MIRROR_CREATE_RESPONSE_FILE" \
  --write-out '%{http_code}' \
  --request POST \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $MIRROR_CREATE_KEY" \
  --data-binary @"$MIRROR_CREATE_BODY_FILE" \
  "$MIRROR_CREATE_URL")"
MIRROR_CREATE_EXIT="$?"
set -e

printf 'curlExit=%s httpStatus=%s bodySha256=%s\n' \
  "$MIRROR_CREATE_EXIT" \
  "$MIRROR_CREATE_STATUS" \
  "$ACTUAL_BODY_SHA256"

printf 'curlExit=%s httpStatus=%s bodySha256=%s\n' \
  "$MIRROR_CREATE_EXIT" \
  "$MIRROR_CREATE_STATUS" \
  "$ACTUAL_BODY_SHA256" \
  > "$MIRROR_CREATE_RESPONSE_FILE.status"
```

A `201` with curl exit `0` is a successful response. For any timeout, connection loss, or unexpected status, read and verify the target before deciding what happened. If a retry is required, repeat only the second block with the saved URL, body, and key, within the server's configured idempotency-retention window. Keep the destination cluster, method, target URL, content type, idempotency key, and body bytes unchanged. The URL check catches changed environment variables; independently confirm that DNS and routing still select the same target cluster. A short-lived bearer token may be refreshed under the same approved caller identity. `IDEMPOTENCY_KEY_CONFLICT` means the key was reused with different request content; stop and investigate.

After the outcome is resolved, delete the request body and response files because both can contain the source secret. Keep only the request URL, non-secret body hash, idempotency key, final status, and filtered verification evidence.

For PostgreSQL, set `type` to `postgres` and provide `dsn`. The HTTP request does not expose RDS IAM configuration; use `ledgerctl` or the gRPC contract for that authentication method.

The request and the response use different shapes

The create body above is flat: `type` selects the source, and the source's own fields (`baseUrl`, `oauth2ClientId`, `dsn`) sit beside it.

A read of the ledger returns the stored configuration in a nested form instead — `mirrorSource.http.baseUrl` with credentials under `mirrorSource.http.oauth2ClientCredentials`, or `mirrorSource.postgres.dsn` with `mirrorSource.postgres.awsIamAuth`. The response carries **no `type` field at all**: which sub-object is present is what identifies the source.

So a verification cannot be written by mirroring the request body, and it must not look for `mirrorSource.type`. The verification block below reads the nested form for that reason.

## Optional creation settings

- `batchSize` defaults to 100. The server also enforces a maximum batch size. Tune it only from rehearsal measurements.
- Add `rewriteRules` only when source data must produce a deliberately different target projection. See [Transform Mirrored Data](https://docs.formance.com/v4.0/modules/ledger/migration/transformations).
- Create and verify the indexes required by validation before switching production readers.

## Verify creation and read-only behavior

Use the same target ledger variable as the creation command. With `ledgerctl`, fail unless the ledger is in mirror mode and exposes a valid progress object:

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

jq -e \
  --arg target "$TARGET_LEDGER" \
  '
  def enum_tail: split("_")[-1];
  def uint64:
    ((. // 0) | tostring) | test("^[0-9]+$");
  . as $ledger
  | $ledger.mirrorSyncProgress as $progress
  | ($ledger.name == $target)
    and (($ledger.mode | enum_tail) == "MIRROR")
    and ($progress != null)
    and (((($progress.state // "MIRROR_SYNC_STATE_SYNCING") | enum_tail) == "SYNCING") or
         ((($progress.state // "MIRROR_SYNC_STATE_SYNCING") | enum_tail) == "FOLLOWING"))
    and ($progress.cursor | uint64)
    and ($progress.sourceLogCount | uint64)
    and ($progress.remainingLogs | uint64)
' <<<"$LEDGER_JSON"
```

For HTTP, define this verification surface even when you created the mirror with `ledgerctl`:

```bash
export TARGET_URL="https://ledger.example.com"
export TARGET_TOKEN="<target-access-token>"
export TARGET_LEDGER="main-target"

LEDGER_JSON="$(curl --fail --silent --show-error \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  "$TARGET_URL/v3/$TARGET_LEDGER")"

jq -e \
  --arg target "$TARGET_LEDGER" \
  '
  def enum_tail: split("_")[-1];
  def uint64:
    ((. // 0) | tostring) | test("^[0-9]+$");
  .data as $ledger
  | $ledger.mirrorSyncProgress as $progress
  | ($ledger.name == $target)
    and (($ledger.mode | enum_tail) == "MIRROR")
    and ($progress != null)
    and (((($progress.state // "MIRROR_SYNC_STATE_SYNCING") | enum_tail) == "SYNCING") or
         ((($progress.state // "MIRROR_SYNC_STATE_SYNCING") | enum_tail) == "FOLLOWING"))
    and ($progress.cursor | uint64)
    and ($progress.sourceLogCount | uint64)
    and ($progress.remainingLogs | uint64)
' <<<"$LEDGER_JSON"
```

Both surfaces this page uses carry the full protobuf spelling: `mode` reads `LEDGER_MODE_MIRROR` and `state` reads `MIRROR_SYNC_STATE_FOLLOWING`. There is no short spelling to accept — the enum checks below tolerate one defensively, but do not write new automation against `MIRROR` or `FOLLOWING`, because nothing emits them. Fixed-width progress values arrive as JSON strings for the same reason, so the checks validate either representation as an unsigned integer rather than asserting a JSON number. The encoding also omits a field sitting at its default, which covers the zero-value syncing state and zero-valued progress counters; only those omissions are interpreted as protobuf defaults.

Verify the immutable source configuration against the values used for this attempt. Normalize either the top-level `ledgerctl` record or the HTTP `{data: ...}` envelope without printing it. Select one source type, set the stored batch size (`0` for the CLI default or `100` in the HTTP example above), and require no rewrite rules on this page. `EXPECTED_SOURCE_TYPE` is this script's own selector, naming the four combinations it knows how to assert — it is not an API value, and it does not correspond to the request's `type` or to `--mirror-source-type`, both of which accept only `http` or `postgres`:

```bash
set -euo pipefail

export EXPECTED_SOURCE_TYPE="http-oauth"
export EXPECTED_BATCH_SIZE="100"
export EXPECTED_RULE_COUNT="0"
export V2_AWS_ASSUME_ROLE_ARN="${V2_AWS_ASSUME_ROLE_ARN:-}"

: "${LEDGER_JSON:?read the target ledger into LEDGER_JSON first}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
: "${SOURCE_LEDGER:?set SOURCE_LEDGER}"
[[ "$EXPECTED_BATCH_SIZE" =~ ^[0-9]+$ ]]
[[ "$EXPECTED_RULE_COUNT" =~ ^[0-9]+$ ]]
command -v jq >/dev/null

case "$EXPECTED_SOURCE_TYPE" in
  http)
    : "${V2_URL:?set V2_URL}"
    ;;
  http-oauth)
    : "${V2_URL:?set V2_URL}"
    : "${V2_CLIENT_ID:?set V2_CLIENT_ID}"
    : "${V2_TOKEN_ENDPOINT:?set V2_TOKEN_ENDPOINT}"
    : "${V2_SCOPE:?set V2_SCOPE}"
    ;;
  postgres-password)
    : "${V2_MIRROR_DSN:?set V2_MIRROR_DSN}"
    ;;
  postgres-rds-iam)
    : "${V2_MIRROR_DSN:?set V2_MIRROR_DSN}"
    : "${V2_AWS_REGION:?set V2_AWS_REGION}"
    ;;
  *)
    printf 'unsupported EXPECTED_SOURCE_TYPE: %s\n' "$EXPECTED_SOURCE_TYPE" >&2
    exit 1
    ;;
esac

LEDGER_RECORD_JSON="$(jq -ce '
  if (.data? | type) == "object" then .data else . end
' <<<"$LEDGER_JSON")"

jq -e \
  --arg sourceType "$EXPECTED_SOURCE_TYPE" \
  --arg batchSize "$EXPECTED_BATCH_SIZE" \
  --arg ruleCount "$EXPECTED_RULE_COUNT" \
  '
    def enum_tail: split("_")[-1];
    def url_view:
      def credential_key:
        ascii_downcase | gsub("-"; "_")
        | IN("password", "sslpassword", "passwd", "secret", "token",
             "api_key", "apikey", "access_token", "access_key",
             "client_secret", "authorization");
      gsub("^\\s+|\\s+$"; "")
      | (index("?")) as $q
      | (if $q == null then . else .[:$q] end) as $base
      | (if $q == null then "" else .[$q + 1:] end) as $query
      | {
          base: (
            $base
            | if test("^[A-Za-z][A-Za-z0-9+.-]*://[^@/?]*:[^@/?]*@") then
                sub("^(?<head>[A-Za-z][A-Za-z0-9+.-]*://[^:@/?]*):[^@/?]*@"; "\(.head):xxxxx@")
              elif test("^[Hh][Tt][Tt][Pp][Ss]?://[^:@/?]+@") then
                sub("^(?<scheme>[A-Za-z]+)://[^:@/?]+@"; "\(.scheme)://xxxxx@")
              else
                .
              end
          ),
          query: (
            $query
            | split("&")
            | map(select(. != "")
                | (index("=")) as $eq
                | (if $eq == null then [., ""] else [.[:$eq], .[$eq + 1:]] end)
                | if (.[0] | credential_key) then [.[0], "xxxxx"] else . end)
            | sort_by(.[0])
          )
        };
    def same_url($expected): url_view == ($expected | url_view);
    (.name == $ENV.TARGET_LEDGER)
    and ((.mode | enum_tail) == "MIRROR")
    and (.mirrorSyncProgress != null)
    and (.mirrorSource.ledgerName == $ENV.SOURCE_LEDGER)
    and (((.mirrorSource.batchSize // 0) | tostring) == $batchSize)
    and (((.mirrorSource.rewriteRules // []) | length) == ($ruleCount | tonumber))
    and (
      if $sourceType == "http" then
        (.mirrorSource.http.baseUrl | same_url($ENV.V2_URL))
        and (.mirrorSource.http.oauth2ClientCredentials == null)
        and (.mirrorSource.postgres == null)
      elif $sourceType == "http-oauth" then
        (.mirrorSource.http.baseUrl | same_url($ENV.V2_URL))
        and (.mirrorSource.http.oauth2ClientCredentials.clientId == $ENV.V2_CLIENT_ID)
        and (.mirrorSource.http.oauth2ClientCredentials.clientSecret == "[redacted]")
        and (.mirrorSource.http.oauth2ClientCredentials.tokenEndpoint | same_url($ENV.V2_TOKEN_ENDPOINT))
        and (.mirrorSource.http.oauth2ClientCredentials.scopes == [$ENV.V2_SCOPE])
        and (.mirrorSource.postgres == null)
      elif $sourceType == "postgres-password" then
        (.mirrorSource.postgres.dsn | same_url($ENV.V2_MIRROR_DSN))
        and (.mirrorSource.postgres.awsIamAuth == null)
        and (.mirrorSource.http == null)
      elif $sourceType == "postgres-rds-iam" then
        (.mirrorSource.postgres.dsn | same_url($ENV.V2_MIRROR_DSN))
        and (.mirrorSource.postgres.awsIamAuth.region == $ENV.V2_AWS_REGION)
        and ((.mirrorSource.postgres.awsIamAuth.assumeRoleArn // "") == $ENV.V2_AWS_ASSUME_ROLE_ARN)
        and (.mirrorSource.http == null)
      else
        false
      end
    )
  ' <<<"$LEDGER_RECORD_JSON" >/dev/null
```

Every comparison is exact except the credentials, which Ledger redacts on read. The check confirms that a client secret is stored, as `[redacted]`. `same_url` compares the source URL, token endpoint, and DSN after applying Ledger's redaction to the value you supplied: a password or passwordless HTTP(S) username becomes `xxxxx`, as does the value of a `password`, `sslpassword`, `passwd`, `secret`, `token`, `api_key`, `apikey`, `access_token`, `access_key`, `client_secret`, or `authorization` query parameter, and query parameters are compared by name in sorted order. It compares the URL as written, so any URL that Ledger stores in a different canonical form fails the check and must be compared by hand. The check fails closed: a mismatch returns false and prints nothing. The common cases are a query value that Go's form encoding re-escapes, such as `sslrootcert=<path>` next to `sslmode=verify-full`, whose `/` reads back as `%2F`; an upper-case scheme; a raw `@` in the password; a `;` in the query; a key-value DSN such as `host=… password=…`; and a URL that reads back as a bare `[redacted]`. The script emits only its exit status. For multiple OAuth2 scopes, replace `[$ENV.V2_SCOPE]` with the exact ordered array supplied at creation. A transformed mirror must additionally compare the complete ordered rule list and accepted rule hash as described on [Transform Mirrored Data](https://docs.formance.com/v4.0/modules/ledger/migration/transformations).

Finally, prove that an application write is rejected with the exact `LEDGER_IN_MIRROR_MODE` reason.

The probe has to submit a structurally valid order. Ledger rejects a malformed one during admission, before the mirror-mode gate in the state machine runs, so an intentionally invalid body returns a content error on a mirror and on a normal ledger alike and proves nothing. Only a well-formed order reaches the gate.

Use a metadata deletion for a key that does not exist. Deleting account metadata is not on the mirror-safe list, so on a mirror it reaches the gate and is refused with `LEDGER_IN_MIRROR_MODE`. On a normal ledger the same request fails its existence check with `METADATA_NOT_FOUND` before anything is written — no log, no account, no balance change. The probe therefore cannot commit value even if the target turns out to be writable, which a transaction probe from `world` would.

Re-read the ledger record immediately before the probe and refuse to run unless the target is still a mirror:

```bash
PROBE_LEDGER_JSON="$(
  curl --fail-with-body --silent --show-error \
    --header "Authorization: Bearer $TARGET_TOKEN" \
    "$TARGET_URL/v3/$TARGET_LEDGER"
)"

jq -e '
  (if (.data? | type) == "object" then .data else . end)
  | .mode == "LEDGER_MODE_MIRROR"
' <<<"$PROBE_LEDGER_JSON" >/dev/null
```

`LEDGER_MODE_NORMAL` is the zero value of the enum, so a normal ledger omits `mode` entirely and this check fails closed. Read it here rather than reusing the record fetched for the configuration comparison above, so the value cannot be stale by the time the probe runs.

The probe needs the effective `ledger:MetadataWrite` scope — the metadata routes sit behind a different scope from the transaction routes.

```bash
PROBE_ACCOUNT="migration:read-only-probe"
PROBE_KEY="mirror-read-only-probe-$(date +%s)-${RANDOM}"
READ_ONLY_BODY_FILE="$(mktemp)"
trap 'rm -f "$READ_ONLY_BODY_FILE"' EXIT

HTTP_STATUS="$(
  curl --silent --show-error \
    --output "$READ_ONLY_BODY_FILE" \
    --write-out '%{http_code}' \
    --request DELETE \
    --header "Authorization: Bearer $TARGET_TOKEN" \
    "$TARGET_URL/v3/$TARGET_LEDGER/accounts/$PROBE_ACCOUNT/metadata/$PROBE_KEY"
)"

test "$HTTP_STATUS" = "409"
jq -e '.errorCode == "LEDGER_IN_MIRROR_MODE"' "$READ_ONLY_BODY_FILE"
```

Both assertions must pass. `PROBE_KEY` carries a timestamp and a random suffix so it is a key no writer has set; the probe proves admission is shut, not that the key is absent.

A `400` with `METADATA_NOT_FOUND` means the request passed the gate and reached the existence check — the target is accepting writes and is no longer a mirror. Treat that as a stop condition: preserve the response, block the migration, and establish the target's mode before continuing. Nothing was written, so there is no probe state to clean up.

## Change or rotate the configuration

The source, credentials, batch size, and rewrite rules are immutable after creation. Changing a value in the deployment's secret manager does not rewrite the credential already stored in the mirror configuration.

To change any of those values:

1. keep Ledger v2 authoritative;
2. save the current evidence and rule file;
3. delete the target mirror;
4. update the secret-manager value or source configuration;
5. choose a new target ledger name;
6. create the replacement mirror under that new name;
7. update staged client, validation, and cutover configuration to the replacement name;
8. replay and validate from the beginning.

Ledger retains a tombstone after deletion, so the deleted target ledger name cannot be reused. Ledger also has no supported update operation for the source or rewrite configuration. Changing it requires a replacement mirror with a new target name. Promotion is the only supported transition from a mirror to a normal ledger.

Continue with [Transform Mirrored Data](https://docs.formance.com/v4.0/modules/ledger/migration/transformations) when the target model must differ from Ledger v2. Otherwise, continue with [Monitor the Mirror](https://docs.formance.com/v4.0/modules/ledger/migration/monitor-mirror).
