# Transform Mirrored Data

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

Stack: v4.0

A transformation is an ordered list of rules Ledger runs over each Ledger v2 log entry as it translates that entry into a target operation. A rule can rename account addresses, add, retype or remove metadata, or skip the entry entirely. Ledger's own vocabulary for these is _rewrite rules_: they are the `rewriteRules` field on a mirror's source configuration and the contents of `--mirror-rewrite-file`, which is the naming you will see in every field, flag, and error message.

Most migrations need none of this. Add rules only when the target must use a different account structure, metadata model, or import policy.

Rules apply to every entry the mirror ingests, for the mirror's whole life — the initial backfill and every entry it picks up afterwards while it follows Ledger v2. They change only the target projection; Ledger v2 remains unchanged.

An entry that no rule matches is imported unchanged, which is what makes "add rules only when you must" a safe default.

Rewrite rules are immutable and there is no transformation dry-run. Test the exact ordered rule file by creating a disposable mirror, then compare its output with recorded fixtures. Any rule change requires a new mirror and a complete replay.

## Decide whether to transform

| Requirement                                          | Preferred decision                                                                                                      |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Preserve the existing accounting model               | Do not add rules.                                                                                                       |
| Rename account segments for the target model         | Use an anchored `rewriteAddress` rule after checking for address collisions.                                            |
| Normalize or type legacy metadata                    | Use `setMetadata`, `deleteMetadata`, or account-metadata actions.                                                       |
| Derive target account metadata from address segments | Use `setAccountMetadataFromAddress` on created transactions.                                                            |
| Exclude a known, approved class of source entries    | Use `drop` and maintain an explicit drop register.                                                                      |
| Correct arbitrary historical business data           | Correct Ledger v2 first, or design a separate reconciliation process. A mirror rule is not a general data-editing tool. |

Do not transform data only to make it look cleaner. Every intentional difference increases the validation surface and makes source-to-target comparisons less direct.

## Understand a rule

Rules run from top to bottom. Each rule has:

- exactly one scope;
- an optional CEL `match` expression;
- one or more typed actions;
- optional `stop: true`, which prevents later rules from running after that rule matches.

The scope determines the type of `log` in CEL and the actions the rule can carry.

| Scope                 | Use it for                                                              | Available actions                                                                                                            |
| --------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `createdTransaction`  | New transactions, postings, transaction metadata, and account metadata. | Rewrite address; set/delete transaction metadata; set/delete account metadata; derive account metadata from addresses; drop. |
| `revertedTransaction` | Reversion operations and their metadata.                                | Rewrite address; set/delete metadata; drop.                                                                                  |
| `savedMetadata`       | A Ledger v2 metadata addition or update.                                | Rewrite the target address; set/delete metadata; drop.                                                                       |
| `deletedMetadata`     | A Ledger v2 metadata deletion.                                          | Rewrite the target address; drop.                                                                                            |
| `anyVariant`          | Address rewrites or drops that must cover every supported log variant.  | Rewrite address; drop.                                                                                                       |

A rule with a different scope from the current source entry is skipped. An empty `match` means the rule matches every entry in its scope.

```mermaid
flowchart LR
    Source["Ledger v2 log entry"] --> Rule["Next rule in order"]
    Rule --> Match{"Scope and match apply?"}
    Match -- "No" --> More{"Another rule?"}
    Match -- "Yes" --> Actions["Apply actions in order"]
    Actions --> Error{"Action failed?"}
    Error -- "Yes" --> Retry["Keep cursor in place and retry the batch"]
    Error -- "No" --> Drop{"Entry dropped?"}
    Drop -- "Yes" --> Gap["Preserve the source position without a target transaction"]
    Drop -- "No" --> Stop{"stop is true?"}
    Stop -- "No" --> More
    Stop -- "Yes" --> Target["Write the transformed target operation"]
    More -- "Yes" --> Rule
    More -- "No" --> Target
```

## Write safe CEL predicates

CEL reads a scope-specific `log`. Guard optional map keys before accessing their typed value:

```cel
"kind" in log.metadata && log.metadata["kind"].string_value == "payout"
```

Use direct key access. Do not iterate metadata maps to produce a value because map iteration is not a stable ordering contract. Rules should not depend on time, randomness, network calls, or other external state.

The error behavior is deliberate:

| Failure                                        | Mirror behavior                                                                                        |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `match` cannot evaluate for one entry          | Ledger skips that rule for the entry and continues. Guard optional fields to avoid an unintended skip. |
| `valueExpr` cannot evaluate                    | Ledger rejects the batch, records the error, and retries the same batch.                               |
| An action produces an invalid address or value | Ledger rejects the batch, records the error, and retries the same batch.                               |
| A rule does not match                          | Ledger evaluates the next rule.                                                                        |
| `drop` runs                                    | Ledger records a gap for that source position and stops evaluating the entry.                          |

Ledger never skips a failing batch automatically, and it never gives up on one either. Retries back off exponentially — one second, doubling, capped at sixty — and the backoff resets on the first success. There is no attempt limit and no dead-letter path.

That applies to the failures in the table that reject the batch: a `valueExpr` that cannot evaluate, or an action producing an invalid address or value. Any of those stalls the mirror at its current cursor indefinitely, with the error visible in its status, and it will not recover on its own — fix the rule file and rebuild the mirror. A `match` that cannot evaluate is not in this category: Ledger skips that rule for the entry and carries on, which is quieter and easier to miss.

## Recipe 1: rewrite account addresses

This rule changes `payments:merchant:m_123:available` to `merchants:m_123` wherever a supported source entry carries that address:

```yaml
- anyVariant:
    actions:
      - rewriteAddress:
          pattern: "^payments:merchant:([^:]+):available$"
          replacement: "merchants:$1"
```

Use RE2-compatible patterns and anchor them with `^` and `$` when the full address must match.

Before using this recipe, prove that two distinct source accounts cannot collapse into one target account unless that merge is intentional. A rewrite affects postings and metadata targets, so test transaction creation, reversion, metadata save, and metadata deletion fixtures.

| Fixture              | Source                              | Expected target   |
| -------------------- | ----------------------------------- | ----------------- |
| Posting source       | `payments:merchant:m_123:available` | `merchants:m_123` |
| Posting destination  | `payments:merchant:m_456:available` | `merchants:m_456` |
| Non-matching account | `payments:customer:c_123:available` | Unchanged         |
| Similar suffix       | `payments:merchant:m_123:pending`   | Unchanged         |

## Recipe 2: normalize and type metadata

This rule identifies payout transactions, adds a target category, copies the reference, converts a legacy string counter to `int64`, and removes a legacy key:

```yaml
- createdTransaction:
    match: >-
      "kind" in log.metadata &&
      log.metadata["kind"].string_value == "payout"
    actions:
      - setMetadata:
          key: category
          value: external
      - setMetadata:
          key: original_reference
          valueExpr: log.reference
      - setMetadata:
          key: attempt_count
          valueExpr: log.metadata["attempt"].string_value
          type: int64
      - deleteMetadata:
          key: legacy_payout
  stop: true
```

The `value` field is a literal string. `valueExpr` evaluates against the current, already-mutated entry. `type` can coerce to `string`, signed or unsigned integer widths, `bool`, or `datetime`.

When a value cannot be parsed as the declared type, the target stores a typed null that preserves the original string for diagnosis. Include valid, missing, and invalid values in the fixture set. In this example, a missing `attempt` causes the action to fail and blocks the batch; add a separate guarded rule or omit the action when missing values are valid source data.

| Fixture           | Source metadata                                 | Expected target                                                      |
| ----------------- | ----------------------------------------------- | -------------------------------------------------------------------- |
| Valid payout      | `kind=payout`, `attempt=3`, `legacy_payout=yes` | `category=external`, `attempt_count=3` as `int64`, legacy key absent |
| Other transaction | `kind=refund`                                   | Unchanged                                                            |
| Invalid counter   | `kind=payout`, `attempt=three`                  | `attempt_count` is typed null preserving `three`                     |
| Missing counter   | `kind=payout`, no `attempt`                     | Batch blocks unless the rules handle this case explicitly            |

To derive account metadata from an address, use the created-transaction-only action:

```yaml
- createdTransaction:
    actions:
      - setAccountMetadataFromAddress:
          pattern: "^merchants:([^:]+):wallet:(\\d+)$"
          replacements:
            - key: merchant_id
              replacement: "$1"
            - key: wallet_id
              replacement: "$2"
              type: int64
```

## Recipe 3: drop an approved entry class

This rule excludes created transactions explicitly marked as internal:

```yaml
- createdTransaction:
    match: >-
      "internal" in log.metadata &&
      log.metadata["internal"].string_value == "true"
    actions:
      - drop: {}
  stop: true
```

Dropping an entry does not remove it from Ledger v2. The mirror preserves the source log position and transaction-ID progression so later history can continue.

A drop rule does not drop that transaction's reversal

A `createdTransaction` rule never sees the reversal of the transaction it dropped: a Ledger v2 reversal arrives as a separate `revertedTransaction` entry, and the metadata on that entry is the _reversal's_ own, not the original's. So a predicate keyed on the dropped transaction's metadata cannot match it.

Ledger applies the reverse postings regardless of whether the original was imported — it forces them through without requiring the original transaction to exist — so the mirror does not stall or raise an error. The reverse postings are themselves a balanced transaction, so nothing in the ledger is left unbalanced; what breaks is agreement with the source. The target carries a compensating transaction with nothing to compensate, and the affected balances diverge from Ledger v2 by the amount of the original. Validation catches it as a balance mismatch, not as a structural error.

Closing this means the dropped class has to be identifiable from **both** entry variants. A `createdTransaction` rule sees the original's `metadata`; a `revertedTransaction` rule sees only `reverted_transaction_id`, `reverse_postings`, the reversal's own `metadata`, and its timestamps — never the original's metadata. There is no registry of dropped IDs for a predicate to consult at run time, and rules are fixed when the mirror is created.

For a backfill of history that already exists, that is workable: query Ledger v2 for the IDs of the class you intend to drop before you create the mirror, and match `reverted_transaction_id` against that fixed set. It only covers originals that exist at authoring time, so a reversal arriving later still matches as long as its original was in the set. What it cannot cover is a transaction created _after_ the mirror exists and reverted while the mirror follows live writes — that ID was never available to embed.

So key the drop on something both variants carry. Posting addresses are the practical choice, because the creation carries `postings` and the reversal carries `reverse_postings`:

```yaml
- createdTransaction:
    match: >-
      log.postings.exists(p,
        p.destination.startsWith("internal:"))
    actions:
      - drop: {}
  stop: true

- revertedTransaction:
    match: >-
      log.reverse_postings.exists(p,
        p.source.startsWith("internal:"))
    actions:
      - drop: {}
  stop: true
```

The two predicates must describe the same class, and it is on you to make sure they do. Note the reversal's postings run the other way, so the address that was a `destination` on the way in is a `source` on the way back. If the class cannot be expressed as an address invariant, fall back to the fixed-ID approach above: enumerate the originals from Ledger v2 before creating the mirror and match `reverted_transaction_id` against that set. Only a transaction created after the mirror exists and reverted while it follows live writes escapes both approaches, and such a class has to be balance-neutral or reconciled downstream. Do not pair a metadata-keyed drop with an address-keyed reversal rule: they will select different sets, missing some reversals and dropping others they should not.

A dropped financial transaction changes target balances unless the dropped class is balance-neutral or its complete accounting effect is handled elsewhere. Record every expected drop and its balance impact before approving the rule.

| Fixture                            | Source                     | Expected target                                                                                                                                                                                                                                      |
| ---------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Approved internal transaction      | `internal=true`            | No target transaction; source log position appears in the drop register.                                                                                                                                                                             |
| External transaction               | `internal=false`           | Imported normally.                                                                                                                                                                                                                                   |
| Missing flag                       | No `internal` key          | Imported normally.                                                                                                                                                                                                                                   |
| Reversion of a dropped transaction | Matching reversion fixture | The recipe above is keyed on metadata, so its reversals are **not** dropped and the reverse postings reach the target. Either re-key the class on an address invariant and drop both variants, or assert that the compensating effect is acceptable. |

## Order interacting rules

Later actions see changes made by earlier actions for the same source entry. Use this intentionally:

1. normalize an address or metadata value;
2. derive additional metadata from the normalized entry;
3. stop when no later rule should apply.

Keep related rules together and add a one-sentence reason above each rule in the version-controlled file. Reordering rules changes the target projection and invalidates previous validation.

## Run an executable fixture rehearsal

There is no dry-run endpoint. Use a disposable Ledger v2 source, stop writes after seeding it, then create a disposable mirror with the exact candidate rule file.

Seed at least these source transactions and record their real transaction IDs:

| Fixture           | Source requirement                                                         | Assertion below                                                                                     |
| ----------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Matching rewrite  | Contains `SOURCE_REWRITE_ADDRESS`.                                         | The target transaction contains `TARGET_REWRITE_ADDRESS` and no longer contains the source address. |
| Non-match         | Contains `PASSTHROUGH_ADDRESS`.                                            | The target transaction keeps that address unchanged.                                                |
| Deliberate drop   | Matches the approved `drop` predicate.                                     | Reading the same transaction ID from the target returns `404`.                                      |
| Rewritten balance | Produces known input, output, and balance totals on the rewritten account. | The target account matches all three expected totals.                                               |

The harness does not seed Ledger v2 because the source write endpoint and authorization policy belong to your existing deployment. Source seeding is a required gate: do not continue with invented IDs or expected balances.

### Set the fixture and target variables

The configured `ledgerctl` profile must point to the disposable target cluster. Install Mike Farah `yq` v4 so the harness can compare the submitted YAML with the rules stored by Ledger. This example uses an OAuth2-protected HTTP source; omit the four OAuth2 flags at creation only when the fixture source intentionally allows unauthenticated log reads.

```bash
set -euo pipefail

export V2_URL="https://ledger-v2-fixture.example.com"
export V2_TOKEN="<source-read-token>"
export SOURCE_LEDGER="migration-fixture-v2"
export V2_CLIENT_ID="ledger-mirror-fixture"
export V2_CLIENT_SECRET="<source-client-secret>"
export V2_TOKEN_ENDPOINT="https://auth.example.com/oauth/token"
export V2_SCOPE="ledger:read"

export TARGET_URL="https://ledger-fixture.example.com"
export TARGET_TOKEN="<target-read-token>"
export TARGET_LEDGER="migration-rewrite-$(date -u +%Y%m%dT%H%M%SZ)"
export RULE_FILE="mirror-rules.yaml"
export MIRROR_BATCH_SIZE="100"

export MATCH_TX_ID="<matching-source-transaction-id>"
export NON_MATCH_TX_ID="<non-matching-source-transaction-id>"
export DROP_TX_ID="<dropped-source-transaction-id>"
export SOURCE_REWRITE_ADDRESS="payments:merchant:m_123:available"
export TARGET_REWRITE_ADDRESS="merchants:m_123"
export PASSTHROUGH_ADDRESS="payments:customer:c_123:available"
export FIXTURE_ASSET="USD/2"
export EXPECTED_INPUT="<expected-input>"
export EXPECTED_OUTPUT="<expected-output>"
export EXPECTED_BALANCE="<expected-balance>"
export MIRROR_WAIT_TIMEOUT_SECONDS="600"

for value in \
  V2_URL V2_TOKEN SOURCE_LEDGER \
  V2_CLIENT_ID V2_CLIENT_SECRET V2_TOKEN_ENDPOINT V2_SCOPE \
  TARGET_URL TARGET_TOKEN TARGET_LEDGER RULE_FILE MIRROR_BATCH_SIZE \
  MATCH_TX_ID NON_MATCH_TX_ID DROP_TX_ID \
  SOURCE_REWRITE_ADDRESS TARGET_REWRITE_ADDRESS PASSTHROUGH_ADDRESS \
  FIXTURE_ASSET EXPECTED_INPUT EXPECTED_OUTPUT EXPECTED_BALANCE; do
  test -n "${!value:-}" || {
    printf 'missing fixture variable: %s\n' "$value" >&2
    exit 1
  }
done

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

for transaction_id in "$MATCH_TX_ID" "$NON_MATCH_TX_ID" "$DROP_TX_ID"; do
  [[ "$transaction_id" =~ ^[0-9]+$ ]] || {
    printf 'replace every transaction ID placeholder with a numeric source ID\n' >&2
    exit 1
  }
done

for amount in "$EXPECTED_INPUT" "$EXPECTED_OUTPUT"; do
  [[ "$amount" =~ ^[0-9]+$ ]] || {
    printf 'expected input and output must be unsigned integer strings\n' >&2
    exit 1
  }
done

[[ "$EXPECTED_BALANCE" =~ ^-?[0-9]+$ ]] || {
  printf 'expected balance must be an integer string\n' >&2
  exit 1
}

test -f "$RULE_FILE"
command -v awk >/dev/null
command -v cmp >/dev/null
command -v curl >/dev/null
command -v date >/dev/null
command -v grep >/dev/null
command -v jq >/dev/null
command -v ledgerctl >/dev/null
command -v openssl >/dev/null
command -v yq >/dev/null
yq --version | grep -q 'mikefarah/yq.*version v4'
```

### Hash the rules and create the disposable mirror

```bash
for artifact in \
  mirror-rules.sha256 \
  mirror-rules.candidate.canonical.json \
  mirror-rules.candidate.canonical.sha256 \
  mirror-rules.target.canonical.json \
  mirror-rules.target.sha256; do
  test ! -e "$artifact" || {
    printf 'rule evidence already exists; do not overwrite it: %s\n' \
      "$artifact" >&2
    exit 1
  }
done

RULE_SHA256="$(openssl dgst -sha256 -r "$RULE_FILE" | awk '{print $1}')"
printf '%s  %s\n' "$RULE_SHA256" "$RULE_FILE" > mirror-rules.sha256

yq -o=json -I=0 '.' "$RULE_FILE" \
  | jq -S -c '
      def strip_proto_defaults:
        if type == "array" then
          map(strip_proto_defaults)
        elif type == "object" then
          with_entries(.value |= strip_proto_defaults)
          | with_entries(select(
              .value != null
              and .value != ""
              and .value != false
              and .value != []
            ))
        else
          .
        end;
      strip_proto_defaults
    ' \
  > mirror-rules.candidate.canonical.json

CANDIDATE_RULES_SHA256="$(openssl dgst -sha256 -r \
  mirror-rules.candidate.canonical.json | awk '{print $1}')"
printf '%s  %s\n' \
  "$CANDIDATE_RULES_SHA256" \
  mirror-rules.candidate.canonical.json \
  > mirror-rules.candidate.canonical.sha256

ledgerctl ledgers create "$TARGET_LEDGER" \
  --idempotency-key "create-mirror:$TARGET_LEDGER" \
  --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" \
  --mirror-batch-size "$MIRROR_BATCH_SIZE" \
  --mirror-rewrite-file "$RULE_FILE"
```

The command passes an idempotency key derived from the unique target name. While Ledger retains it, 24 hours by default, rerunning the identical command returns the original outcome, and a rerun with a changed rule file or flag is rejected as a key conflict instead of creating a different mirror. After every attempt, still recompute the input-file hash and read the unique target before continuing. If the command times out or loses its response, run this check before you decide to rerun it:

```bash
set -euo pipefail

: "${RULE_FILE:?set RULE_FILE}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
: "${SOURCE_LEDGER:?set SOURCE_LEDGER}"
: "${V2_URL:?set V2_URL}"
: "${V2_CLIENT_ID:?set V2_CLIENT_ID}"
: "${V2_CLIENT_SECRET:?set V2_CLIENT_SECRET}"
: "${V2_TOKEN_ENDPOINT:?set V2_TOKEN_ENDPOINT}"
: "${V2_SCOPE:?set V2_SCOPE}"
: "${MIRROR_BATCH_SIZE:?set MIRROR_BATCH_SIZE}"
[[ "$MIRROR_BATCH_SIZE" =~ ^[1-9][0-9]*$ ]]
command -v awk >/dev/null
command -v cmp >/dev/null
command -v jq >/dev/null
command -v ledgerctl >/dev/null
command -v openssl >/dev/null
test -f "$RULE_FILE"
test -f mirror-rules.sha256
test -f mirror-rules.candidate.canonical.json
test -f mirror-rules.candidate.canonical.sha256
for artifact in \
  mirror-rules.target.canonical.json \
  mirror-rules.target.sha256; do
  test ! -e "$artifact" || {
    printf 'target-rule evidence already exists; do not overwrite it: %s\n' \
      "$artifact" >&2
    exit 1
  }
done

EXPECTED_RULE_SHA256="$(awk '{print $1}' mirror-rules.sha256)"
ACTUAL_RULE_SHA256="$(openssl dgst -sha256 -r "$RULE_FILE" | awk '{print $1}')"
test "$ACTUAL_RULE_SHA256" = "$EXPECTED_RULE_SHA256"

EXPECTED_CANDIDATE_RULES_SHA256="$(awk '{print $1}' \
  mirror-rules.candidate.canonical.sha256)"
ACTUAL_CANDIDATE_RULES_SHA256="$(openssl dgst -sha256 -r \
  mirror-rules.candidate.canonical.json | awk '{print $1}')"
test "$ACTUAL_CANDIDATE_RULES_SHA256" = "$EXPECTED_CANDIDATE_RULES_SHA256"

FIXTURE_LEDGER_JSON="$(ledgerctl ledgers get "$TARGET_LEDGER" --json)"

jq -e '
  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.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.batchSize // 0) | tostring) == $ENV.MIRROR_BATCH_SIZE)
  and (((.mirrorSource.rewriteRules // []) | length) > 0)
' <<<"$FIXTURE_LEDGER_JSON" >/dev/null

jq -S -c '
  def strip_proto_defaults:
    if type == "array" then
      map(strip_proto_defaults)
    elif type == "object" then
      with_entries(.value |= strip_proto_defaults)
      | with_entries(select(
          .value != null
          and .value != ""
          and .value != false
          and .value != []
        ))
    else
      .
    end;
  .mirrorSource.rewriteRules | strip_proto_defaults
' <<<"$FIXTURE_LEDGER_JSON" \
  > mirror-rules.target.canonical.json

cmp -s \
  mirror-rules.candidate.canonical.json \
  mirror-rules.target.canonical.json

TARGET_RULES_SHA256="$(openssl dgst -sha256 -r \
  mirror-rules.target.canonical.json | awk '{print $1}')"
test "$TARGET_RULES_SHA256" = "$EXPECTED_CANDIDATE_RULES_SHA256"
printf '%s  %s\n' \
  "$TARGET_RULES_SHA256" \
  mirror-rules.target.canonical.json \
  > mirror-rules.target.sha256
```

`same_url` compares the source URL and token endpoint after applying Ledger's read-side credential redaction to the values you supplied, as described in [Verify creation and read-only behavior](https://docs.formance.com/v4.0/modules/ledger/migration/create-mirror#verify-creation-and-read-only-behavior), so a URL carrying a password or credential query parameter still matches.

The canonical form removes explicitly written protobuf defaults such as `stop: false` and `match: ""`, which the structured ledger response normally omits. It does not remove objects, so action selectors such as `drop: {}` remain part of the comparison. The `cmp` and hash assertions prove that the complete normalized rule list, including order, matches the candidate.

Keep the raw file hash and both canonical hashes with the fixture evidence. If the target exists and every source, progress, and rule check matches, creation committed; continue without another create request. If it exists with any mismatch, stop and preserve it for investigation. If the read is unavailable, retry only the read. Start a new creation attempt only after the target returns an explicit `NotFound`, using a new unique target name and fresh evidence files.

The HTTP API accepts the same ordered list as `mirrorSource.rewriteRules` in the create-ledger body.

### Wait for the frozen fixture boundary

```bash
SOURCE_HEAD_JSON="$(curl --fail --silent --show-error \
  --header "Authorization: Bearer $V2_TOKEN" \
  "$V2_URL/v2/$SOURCE_LEDGER/logs?pageSize=1")"

FIXTURE_SOURCE_HEAD="$(jq -er '
  .cursor.data
  | if type != "array" then
      error("source response has no cursor.data array")
    elif length == 0 then
      error("fixture source is empty")
    else
      (.[0].id | tostring) as $id
      | if $id | test("^[1-9][0-9]*$") then
          $id
        else
          error("newest fixture source log has an invalid id")
        end
    end
' <<<"$SOURCE_HEAD_JSON")"

MIRROR_WAIT_DEADLINE=$((SECONDS + MIRROR_WAIT_TIMEOUT_SECONDS))

while :; do
  TARGET_LEDGER_JSON="$(ledgerctl ledgers get "$TARGET_LEDGER" --json)"
  jq -e '.mirrorSyncProgress != null' <<<"$TARGET_LEDGER_JSON" >/dev/null

  TARGET_MODE="$(jq -er '.mode | split("_")[-1]' <<<"$TARGET_LEDGER_JSON")"
  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_ERROR_JSON" != "null" ]; then
    printf 'fixture mirror error: %s\n' "$TARGET_ERROR_JSON" >&2
    exit 1
  fi

  if [ "$TARGET_MODE" != "MIRROR" ]; then
    printf 'fixture target left MIRROR mode\n' >&2
    exit 1
  fi

  if [ "$TARGET_CURSOR" = "$FIXTURE_SOURCE_HEAD" ] &&
     [ "$TARGET_SOURCE_HEAD" = "$FIXTURE_SOURCE_HEAD" ] &&
     [ "$TARGET_REMAINING" = "0" ]; then
    break
  fi

  if [ "$SECONDS" -ge "$MIRROR_WAIT_DEADLINE" ]; then
    printf 'fixture mirror timed out: cursor=%s observedSource=%s head=%s remaining=%s\n' \
      "$TARGET_CURSOR" \
      "$TARGET_SOURCE_HEAD" \
      "$FIXTURE_SOURCE_HEAD" \
      "$TARGET_REMAINING" >&2
    exit 1
  fi

  sleep 5
done
```

Keep the same Bash session. Define one fail-closed boundary check and run it immediately before querying fixture results:

```bash
assert_fixture_boundary() {
  LATEST_SOURCE_HEAD_JSON="$(curl --fail --silent --show-error \
    --header "Authorization: Bearer $V2_TOKEN" \
    "$V2_URL/v2/$SOURCE_LEDGER/logs?pageSize=1")"

  LATEST_SOURCE_HEAD="$(jq -er '
    .cursor.data
    | if type != "array" then
        error("source response has no cursor.data array")
      elif length == 0 then
        error("fixture source is empty")
      else
        (.[0].id | tostring) as $id
        | if $id | test("^[1-9][0-9]*$") then
            $id
          else
            error("newest fixture source log has an invalid id")
          end
      end
  ' <<<"$LATEST_SOURCE_HEAD_JSON")"

  TARGET_LEDGER_JSON="$(ledgerctl ledgers get "$TARGET_LEDGER" --json)"
  jq -e '.mirrorSyncProgress != null' <<<"$TARGET_LEDGER_JSON" >/dev/null

  LATEST_TARGET_MODE="$(jq -er '.mode | split("_")[-1]' <<<"$TARGET_LEDGER_JSON")"
  LATEST_TARGET_CURSOR="$(jq -er '(.mirrorSyncProgress.cursor // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
  LATEST_TARGET_SOURCE_HEAD="$(jq -er '(.mirrorSyncProgress.sourceLogCount // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
  LATEST_TARGET_REMAINING="$(jq -er '(.mirrorSyncProgress.remainingLogs // 0) | tostring' <<<"$TARGET_LEDGER_JSON")"
  LATEST_TARGET_ERROR_JSON="$(jq -c '.mirrorSyncProgress.error // null' <<<"$TARGET_LEDGER_JSON")"

  if [ "$LATEST_SOURCE_HEAD" != "$FIXTURE_SOURCE_HEAD" ] ||
     [ "$LATEST_TARGET_MODE" != "MIRROR" ] ||
     [ "$LATEST_TARGET_CURSOR" != "$FIXTURE_SOURCE_HEAD" ] ||
     [ "$LATEST_TARGET_SOURCE_HEAD" != "$FIXTURE_SOURCE_HEAD" ] ||
     [ "$LATEST_TARGET_REMAINING" != "0" ] ||
     [ "$LATEST_TARGET_ERROR_JSON" != "null" ]; then
    printf 'fixture boundary changed; discard these comparison results\n' >&2
    return 1
  fi
}

assert_fixture_boundary
```

### Assert match, non-match, drop, and balances

```bash
MATCH_JSON="$(curl --fail --silent --show-error \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  "$TARGET_URL/v3/$TARGET_LEDGER/transactions/$MATCH_TX_ID")"

jq -e \
  --arg source "$SOURCE_REWRITE_ADDRESS" \
  --arg target "$TARGET_REWRITE_ADDRESS" \
  '
    .data.transaction.postings as $postings
    | (any($postings[]; .source == $target or .destination == $target))
      and (all($postings[]; .source != $source and .destination != $source))
  ' <<<"$MATCH_JSON" >/dev/null

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

jq -e \
  --arg address "$PASSTHROUGH_ADDRESS" \
  '
    .data.transaction.postings
    | any(.[]; .source == $address or .destination == $address)
  ' <<<"$NON_MATCH_JSON" >/dev/null

DROP_BODY_FILE="$(mktemp)"
DROP_STATUS="$(curl --silent --show-error \
  --output "$DROP_BODY_FILE" \
  --write-out '%{http_code}' \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  "$TARGET_URL/v3/$TARGET_LEDGER/transactions/$DROP_TX_ID")"
test "$DROP_STATUS" = "404"
jq -e '.errorCode == "TRANSACTION_NOT_FOUND"' "$DROP_BODY_FILE" >/dev/null

TARGET_REWRITE_ADDRESS_URI="$(jq -rn \
  --arg address "$TARGET_REWRITE_ADDRESS" \
  '$address | @uri')"

BALANCE_JSON="$(curl --fail --silent --show-error \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  "$TARGET_URL/v3/$TARGET_LEDGER/accounts/$TARGET_REWRITE_ADDRESS_URI?collapseColors=true")"

jq -e \
  --arg address "$TARGET_REWRITE_ADDRESS" \
  --arg asset "$FIXTURE_ASSET" \
  --arg input "$EXPECTED_INPUT" \
  --arg output "$EXPECTED_OUTPUT" \
  --arg balance "$EXPECTED_BALANCE" \
  '
    (.data.address == $address)
    and any(
      .data.volumes[];
      .asset == $asset
      and .color == ""
      and .volumes.input == $input
      and .volumes.output == $output
      and .volumes.balance == $balance
    )
  ' <<<"$BALANCE_JSON" >/dev/null
```

Every command above must exit with status `0`. A missing transaction, unexpected `200` for the dropped ID, address mismatch, or volume mismatch fails the rehearsal.

Rerun the boundary check after the result queries. This prevents the evidence bundle from combining an older source head with a newer target state:

```bash
assert_fixture_boundary
```

### Preserve the evidence

```bash
EVIDENCE_DIR="rewrite-evidence-$TARGET_LEDGER"
test ! -e "$EVIDENCE_DIR" || {
  printf 'evidence directory already exists; do not overwrite it: %s\n' \
    "$EVIDENCE_DIR" >&2
  exit 1
}
mkdir "$EVIDENCE_DIR"

cp "$RULE_FILE" "$EVIDENCE_DIR/rules.yaml"
cp mirror-rules.sha256 "$EVIDENCE_DIR/rules.sha256"
cp mirror-rules.candidate.canonical.json \
  "$EVIDENCE_DIR/candidate-rules.canonical.json"
cp mirror-rules.candidate.canonical.sha256 \
  "$EVIDENCE_DIR/candidate-rules.canonical.sha256"
jq -n \
  --arg sourceLogId "$FIXTURE_SOURCE_HEAD" \
  '{sourceLogId: $sourceLogId}' \
  > "$EVIDENCE_DIR/source-head.initial.json"
jq -n \
  --arg sourceLogId "$LATEST_SOURCE_HEAD" \
  '{sourceLogId: $sourceLogId}' \
  > "$EVIDENCE_DIR/source-head.confirmed.json"
printf '%s\n' "$TARGET_LEDGER_JSON" \
  | jq '{name, mode, mirrorSyncProgress}' \
  > "$EVIDENCE_DIR/target-progress.json"
cp mirror-rules.target.canonical.json \
  "$EVIDENCE_DIR/target-rules.canonical.json"

cmp -s \
  "$EVIDENCE_DIR/candidate-rules.canonical.json" \
  "$EVIDENCE_DIR/target-rules.canonical.json"
openssl dgst -sha256 -r "$EVIDENCE_DIR/target-rules.canonical.json" \
  > "$EVIDENCE_DIR/target-rules.sha256"
printf '%s\n' "$MATCH_JSON" > "$EVIDENCE_DIR/match-transaction.json"
printf '%s\n' "$NON_MATCH_JSON" > "$EVIDENCE_DIR/non-match-transaction.json"
printf '%s\n' "$BALANCE_JSON" > "$EVIDENCE_DIR/rewritten-balance.json"
cp "$DROP_BODY_FILE" "$EVIDENCE_DIR/drop-response.json"
```

Keep the disposable mirror until a reviewer accepts the evidence. Delete it afterward with `ledgerctl ledgers delete "$TARGET_LEDGER" --yes`; never promote a fixture mirror.

The Stack v4 preview does not surface rewrite rules in its own manifests. If you drive Ledger through the ledger operator's `Ledger` CRD directly, set `spec.mirrorSource.rewriteRules`, which the controller forwards to `ledgerctl` as `--mirror-rewrite-rule`. Otherwise create the mirror with `ledgerctl` or the HTTP API. Do not infer Stack manifest fields.

## Promotion gate for transformed mirrors

- [ ] The exact rule file and its hash are in the migration record.
- [ ] Every rule has positive, negative, missing-field, and boundary fixtures.
- [ ] Every output address is valid and collision behavior is approved.
- [ ] Typed metadata includes invalid-value behavior.
- [ ] Every dropped log and its accounting impact is explained.
- [ ] Balance, volume, reference, reversion, and metadata comparisons account for the rules.
- [ ] The production mirror uses the same rule order as the accepted rehearsal.

Continue with [Monitor the Mirror](https://docs.formance.com/v4.0/modules/ledger/migration/monitor-mirror).
