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
matchexpression; - 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.
Write safe CEL predicates#
CEL reads a scope-specific log. Guard optional map keys before accessing their typed value:
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:
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:
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:
Recipe 3: drop an approved entry class#
This rule excludes created transactions explicitly marked as internal:
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:
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:
- normalize an address or metadata value;
- derive additional metadata from the normalized entry;
- 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.
Hash the rules and create the disposable mirror#
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:
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, 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#
Keep the same Bash session. Define one fail-closed boundary check and run it immediately before querying fixture results:
Assert match, non-match, drop, and balances#
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:
Preserve the evidence#
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.