# Monitor the Mirror

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

Stack: v4.0

Monitor deployment provisioning and Ledger mirror progress as separate signals. They answer different questions:

- deployment provisioning confirms that the target service and ledger were created;
- a mirror is _following_ once it has applied every source entry it has seen — formally, the cursor is at or past a non-zero source head the target has persisted;
- neither state proves that source and target business data match.

The Stack v4 preview does not define supported Operator status fields for this workflow. Keep deployment provisioning and Ledger mirror progress as separate signals; the fields below describe Ledger progress only.

## Read progress

Read the ledger's mirror progress with `ledgerctl`:

```bash
set -euo pipefail

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

ledgerctl ledgers get "$TARGET_LEDGER"
```

For automation:

```bash
set -euo pipefail

export TARGET_LEDGER="main-target"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
command -v jq >/dev/null
command -v ledgerctl >/dev/null

ledgerctl ledgers get "$TARGET_LEDGER" --json \
  | jq -e '.mirrorSyncProgress'
```

Or use HTTP:

```bash
set -euo pipefail

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

: "${TARGET_URL:?set TARGET_URL}"
: "${TARGET_TOKEN:?set TARGET_TOKEN}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
command -v curl >/dev/null
command -v jq >/dev/null

curl --fail --silent --show-error \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  "$TARGET_URL/v3/$TARGET_LEDGER" \
  | jq -e '.data.mirrorSyncProgress'
```

## Interpret the fields

| Field            | Meaning                                                                                                                                                                                                                                                                                                                                                                                                               | Healthy behavior                                                                                                                                                    |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `state`          | `MIRROR_SYNC_STATE_SYNCING` while the cursor is below the persisted source head; `MIRROR_SYNC_STATE_FOLLOWING` when the head is non-zero and `cursor >= sourceLogCount`. An empty source stays syncing. The field carries the full declared enum name, and because syncing is the enum's default value it is omitted from the JSON entirely — treat an absent `state` as syncing rather than as a contract violation. | It may alternate while Ledger v2 continues receiving writes. Following with `cursor > sourceLogCount` is anomalous.                                                 |
| `cursor`         | Highest Ledger v2 log ID successfully applied to the target.                                                                                                                                                                                                                                                                                                                                                          | Increases monotonically during replay.                                                                                                                              |
| `sourceLogCount` | Source head observed by the most recent successful source query and persisted by the target — by an ingestion batch, or on its own by an idle, caught-up worker. It is not read live at request time.                                                                                                                                                                                                                 | Advances as the worker observes new source logs. If the source is unreachable it stays stale, because a failed head query is logged but never recorded as an error. |
| `remainingLogs`  | `sourceLogCount - cursor` when the persisted source head is ahead; otherwise `0`.                                                                                                                                                                                                                                                                                                                                     | Trends down during catch-up and repeatedly returns to zero while following. A zero value does not detect `cursor > sourceLogCount`.                                 |
| `error`          | Most recent source, translation, transformation, or apply error that Ledger persisted.                                                                                                                                                                                                                                                                                                                                | The next successful poll clears it, whether or not that poll ingested any logs. An error that persists across polls means the failure is still active.              |

`mode` differs between directions: a create request takes the bare `MIRROR`, while a read returns the full `LEDGER_MODE_MIRROR` and omits the field entirely for a normal ledger. Compare reads against the full value.

Ledger refreshes the source head in memory while polling and publishes it — together with an error clear — on the next poll, including a poll that returns no logs. A worker that has never successfully read the source head publishes nothing at all, so the progress object cannot distinguish an idle healthy source from a worker that failed before its first source read.

Following compares the cursor with a source head persisted by the target. It does not refresh the source, query business invariants, compare balances, or certify promotion safety. Treat `cursor > sourceLogCount` as an inconsistent progress tuple even though the current state calculation reports `FOLLOWING` and zero remaining logs.

## Decide what state you are in

| Observation                                                      | Interpretation                                                                                                                                                                                                                                                             | Next action                                                                                                                                                                     |
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cursor increases and remaining logs decrease                     | Replay is progressing.                                                                                                                                                                                                                                                     | Continue monitoring source and target load.                                                                                                                                     |
| State alternates between following and syncing under live writes | The target catches new source tails.                                                                                                                                                                                                                                       | Confirm it repeatedly returns to zero remaining logs.                                                                                                                           |
| Cursor is unchanged and an error is present                      | The failure is still active: a successful poll would have cleared the error even with no logs to ingest.                                                                                                                                                                   | Read the error message and act on it; Ledger retries without skipping the failed entry.                                                                                         |
| All counters are unchanged and no error is visible               | The source may be idle, the worker may not be running because of initialization, leadership, or storage pressure, or the source may be unreachable for head queries — that last case is logged as `Failed to query source head` and deliberately not recorded as an error. | Read the source head directly, inspect target logs, and search them for `Failed to query source head`. For a new PostgreSQL mirror, check for `Failed to create mirror source`. |
| Following, remaining zero, no error                              | The target reached its persisted source head.                                                                                                                                                                                                                              | Compare the cursor with a fresh source read, then run independent validation; do not promote from status alone.                                                                 |
| Following with cursor greater than source head                   | The persisted progress tuple is inconsistent or stale. `remainingLogs` still reports zero.                                                                                                                                                                                 | Stop status-based automation, capture the tuple and server version, compare the source directly, and investigate before validation.                                             |
| Ledger reports `LEDGER_MODE_MIRROR`, progress missing            | The response violates the current Ledger contract: every readable mirror ledger receives a progress object, including when all counters are zero.                                                                                                                          | Stop status-based automation, capture a credential-safe response and server version, compare another read surface, and investigate serialization or runtime health.             |

For an intentionally empty source, confirm directly that the Ledger v2 log list is empty and that `cursor`, `sourceLogCount`, and `remainingLogs` are all `0`. Do not wait for the following state in that case.

A visible error means the current poll cycle is still failing, so treat it as a live condition rather than as history: the worker clears it on its own once a poll succeeds, and it needs no synthetic financial log or manual intervention to do so. The one case that produces no error at all is a source the worker cannot query for its head, which is logged rather than recorded — so a wholly static tuple with no error still warrants a direct source read.

## Diagnose a stalled mirror

Work from non-destructive checks toward configuration changes.

1. Record the cursor, source head, error message, and error timestamp.
2. Confirm the target cluster has a leader and sufficient disk headroom.
3. Test the source path from the target environment.
4. Inspect the Ledger v2 entry immediately after the cursor.
5. Identify the rule scope and actions that apply to that entry.
6. Decide whether the source can be corrected safely or the mirror must be recreated.

| Error area        | Check                                                                                                           | Recovery                                                                        |
| ----------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| HTTP connectivity | DNS, TLS, route, source status, and `/v2/{ledger}/logs` response.                                               | Restore reachability; the worker retries automatically.                         |
| OAuth2            | Client ID, token endpoint, client secret, scopes, and token expiry.                                             | If immutable credentials must change, recreate the mirror.                      |
| PostgreSQL        | DNS, TLS mode, database, `_system.ledgers`, bucket table, `CONNECT`, schema `USAGE`, and table `SELECT` grants. | Restore access; recreate only when the stored connection configuration changes. |
| RDS IAM           | Target Ledger runtime identity, region, `rds-db:connect`, optional assume role, and TLS mode.                   | Correct IAM or recreate when region/role configuration changes.                 |
| Source log        | Log type, JSON shape, posting amount, target, timestamp, and referenced transaction.                            | Correct the source condition only with an approved Ledger v2 procedure.         |
| Transformation    | Missing field, CEL type, `valueExpr`, RE2 pattern, typed conversion, or invalid output address.                 | Correct the rule and create a new mirror. Rules cannot change in place.         |
| Target storage    | Disk pressure, write stall, compaction, and cluster availability.                                               | Restore storage headroom; ingestion resumes after the stall clears.             |
| Leadership        | Leader election or member availability.                                                                         | Restore quorum and leadership; the new leader resumes the mirror worker.        |

For a PostgreSQL source, Ledger resolves the source ledger's bucket before it starts the mirror worker. A connection, authentication, or bucket-lookup failure at this stage is written to the target Ledger logs as `Failed to create mirror source`; it may leave `cursor`, `sourceLogCount`, and `remainingLogs` at `0` with no progress error. Inspect target logs whenever a new PostgreSQL mirror remains at zero, even when `.mirrorSyncProgress.error` is absent.

## Understand retry behavior

When a source fetch, translation, rule action, or target apply fails:

- the cursor does not advance past the failed batch;
- Ledger records the error and retries with backoff;
- Ledger does not automatically discard the failing source entry;
- the next successful poll clears the recorded error and resumes progress, whether or not it ingested any logs;
- an idle poll that returns no logs still publishes the observed source head, so a visible error means the failure is still live rather than historical.

Do not promote to bypass a blocked batch. Promotion stops replication at the current cursor and makes that incomplete projection writable.

## Establish alerts

Alert on user-visible conditions rather than a single instantaneous state:

- cursor unchanged for longer than the measured healthy interval;
- remaining logs increasing across several samples;
- any mirror error that persists across retries;
- target disk pressure or write stalls;
- source authorization or TLS failures;
- target without a leader or quorum;
- production mirror no longer reporting `LEDGER_MODE_MIRROR` before the approved cutover.

Choose thresholds from the rehearsal throughput and source-write profile. A fixed lag threshold without that context can hide a slow migration or alert on normal bursts.

## Ready for validation

Proceed to [Validate the Migration](https://docs.formance.com/v4.0/modules/ledger/migration/validation) when:

- the cursor advances normally;
- the target repeatedly reaches the following state with zero remaining logs, or both ledgers are confirmed empty;
- the cursor never exceeds the persisted source head;
- a fresh Ledger v2 read confirms that the cursor reached the current source head;
- no unresolved mirror error remains;
- the exact source and rewrite configuration matches the accepted rehearsal;
- required indexes are ready;
- source and target load remain inside approved limits.

These conditions start validation. They do not replace it.

Continue with [Validate the Migration](https://docs.formance.com/v4.0/modules/ledger/migration/validation) once every condition above holds.
