# Cut Over and Promote

Source: https://docs.formance.com/v4.0/modules/ledger/migration/cut-over-and-promote

Stack: v4.0

Cutover changes the write authority from Ledger v2 to the target. Run it as an approved maintenance procedure with one migration lead controlling the sequence.

Promotion does not check `FOLLOWING`, remaining logs, errors, balances, or business invariants. It stops replication immediately, clears the source configuration, and makes the target writable. There is no demotion operation.

## Preconditions

Do not start the maintenance window until:

- the complete runbook has succeeded in a rehearsal;
- every Ledger v2 writer can be stopped and its owner is present;
- the target repeatedly follows the live source without an unresolved error;
- final validation commands and evidence storage are ready;
- target clients, authentication, and routing are staged;
- every target sink has completed its initial replay into a quarantined destination or consumer, follows the target, and has not repeated Ledger v2 business effects;
- stable cross-version deduplication keys, sink and consumer checkpoints, and an event activation boundary are approved;
- promotion access belongs to the named target administrator;
- the migration lead, validation owner, and incident owner are present;
- the source-resume deadline and no-go criteria are agreed.

## Assign the live roles

| Role                 | Live responsibility                                                                                         |
| -------------------- | ----------------------------------------------------------------------------------------------------------- |
| Migration lead       | Calls each step, records timestamps, and makes the go/no-go decision.                                       |
| Source administrator | Stops writers, proves the freeze, records the final source head, and can resume Ledger v2 before promotion. |
| Target administrator | Watches catch-up, promotes once, and verifies target mode.                                                  |
| Application owner    | Switches endpoint and authentication, then releases traffic.                                                |
| Validation owner     | Runs final checks and signs the evidence.                                                                   |
| Event owner          | Switches consumers and verifies one controlled event.                                                       |
| Incident owner       | Stops the procedure when a no-go condition is met.                                                          |

## Run the cutover

Keep the following commands in one Bash session. The configured `ledgerctl` profile must point to the candidate target cluster and have permission to read and promote `$TARGET_LEDGER`.

```bash
set -euo pipefail
set +x

export SOURCE_TRANSPORT="postgres" # "http" or "postgres"
export SOURCE_LEDGER="main-v2"
export TARGET_LEDGER="main-target"
export MIRROR_WAIT_TIMEOUT_SECONDS="1800"
export MIRROR_POLL_INTERVAL_SECONDS="5"

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

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

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

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

: "${SOURCE_TRANSPORT:?set SOURCE_TRANSPORT}"
: "${SOURCE_LEDGER:?set SOURCE_LEDGER}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
: "${MIRROR_WAIT_TIMEOUT_SECONDS:?set MIRROR_WAIT_TIMEOUT_SECONDS}"
: "${MIRROR_POLL_INTERVAL_SECONDS:?set MIRROR_POLL_INTERVAL_SECONDS}"
[[ "$MIRROR_WAIT_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]]
[[ "$MIRROR_POLL_INTERVAL_SECONDS" =~ ^[1-9][0-9]*$ ]]
command -v jq >/dev/null
command -v ledgerctl >/dev/null

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

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

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

    command -v psql >/dev/null

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

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

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

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

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

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

source_psql() {
  local iam_token

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

read_source_log_id() {
  local source_head_json
  local source_log_id

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

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

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

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

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

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

`V2_PG_HOST` must be the exact RDS endpoint used in the DSN, not a different alias. The RDS IAM helper generates a fresh 15-minute token for every psql process. When an assume-role ARN is set, it also obtains fresh role credentials for that invocation. Neither the token nor the temporary AWS credentials enter command-line arguments, global environment variables, or evidence files. The shared source-head function resolves the exact bucket recorded for `$SOURCE_LEDGER`, passes that server-provided name through psql's identifier quoting, and rejects absent, duplicate, or non-numeric results.

### 1. Freeze Ledger v2 writes

Stop API writers, background workers, scheduled jobs, support tools, and administrative scripts. Reject or queue new business operations according to the maintenance plan.

Prove the freeze with application metrics and Ledger v2 logs. Waiting for traffic to become quiet is not the same as blocking every writer.

### 2. Record the final source log ID

After the freeze is effective, derive `FINAL_SOURCE_LOG_ID` from the selected source. The function returns `0` for an empty source and fails if the HTTP response or PostgreSQL result is invalid:

```bash
FINAL_SOURCE_LOG_ID="$(read_source_log_id)"

jq -n \
  --arg finalSourceLogId "$FINAL_SOURCE_LOG_ID" \
  '{finalSourceLogId: $finalSourceLogId}' \
  > final-source-head.json
printf 'final source log ID: %s\n' "$FINAL_SOURCE_LOG_ID"
```

Store `final-source-head.json` and `FINAL_SOURCE_LOG_ID` in the migration record.

### 3. Ingest the final tail

Poll the target until the complete progress tuple reaches the frozen boundary. An active mirror error fails immediately. A timeout fails with the last cursor, observed source head, remaining count, and error; it never falls through to promotion.

```bash
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")"

  printf 'mode=%s cursor=%s observedSource=%s remaining=%s error=%s\n' \
    "$TARGET_MODE" \
    "$TARGET_CURSOR" \
    "$TARGET_SOURCE_HEAD" \
    "$TARGET_REMAINING" \
    "$TARGET_ERROR_JSON"

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

  if [ "$TARGET_ERROR_JSON" != "null" ]; then
    printf 'mirror reported an active error; do not promote\n' >&2
    exit 1
  fi

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

  if [ "$SECONDS" -ge "$MIRROR_WAIT_DEADLINE" ]; then
    printf 'mirror did not reach the final source boundary before timeout\n' >&2
    exit 1
  fi

  sleep "$MIRROR_POLL_INTERVAL_SECONDS"
done
```

Confirm that the source head did not move after the freeze, then save a credential-safe target snapshot:

```bash
CONFIRMED_SOURCE_LOG_ID="$(read_source_log_id)"

if [ "$CONFIRMED_SOURCE_LOG_ID" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$TARGET_CURSOR" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$TARGET_SOURCE_HEAD" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$TARGET_REMAINING" != "0" ] ||
   [ "$TARGET_ERROR_JSON" != "null" ]; then
  printf 'final source or mirror gate changed; do not promote\n' >&2
  exit 1
fi

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

Continue only when every assertion in the two blocks passes:

- `cursor` equals the final source log ID;
- `sourceLogCount` equals the same frozen ID;
- `remainingLogs` is `0`;
- no mirror error is present;
- the source head remains unchanged because writes are frozen.

`FOLLOWING` alone is not sufficient.

### 4. Run final validation

Run the critical checklist from [Validate the Migration](https://docs.formance.com/v4.0/modules/ledger/migration/validation) against the final log boundary. Store the commands, normalized results, transformation adjustments, and signatures in the migration record.

The migration lead announces `GO` only after the validation owner approves the result. Otherwise, announce `NO-GO`, do not promote, and follow the source-resume procedure.

### 5. Prepare the client and consumer switch

Confirm the staged target configuration one last time:

- target base URL or gRPC endpoint;
- target authentication issuer, audience, and scopes;
- target ledger name;
- retry and idempotency-key behavior;
- required indexes;
- target sink cursor and destination or consumer replay checkpoint;
- stable target-delivery and cross-version business-effect keys;
- Ledger v2 consumer stop point and target effect-activation boundary;
- alert and dashboard context.

A newly created target sink starts at cursor `0` and replays every supported event retained in the target global log, including mirrored Ledger v2 history. There is no sink start-cursor option in the current configuration. Do not create or enable an effecting consumer here under the assumption that it will receive only new target writes.

Before promotion, keep target delivery in quarantine and prove that it has drained through the target event boundary captured after final mirror validation. Historical messages must be durably accepted, inspected, and either matched to an existing Ledger v2 business-effect receipt or explicitly reconciled without executing the effect again. Record the sink cursor and the destination-specific consumer checkpoint together. Do not compare the target sink cursor numerically with the Ledger v2 mirror cursor; they belong to different sequence spaces.

The activation boundary belongs to the migration record and consumer workflow; it is not a value configured on the Ledger sink. If you cannot prove that every event at or below that boundary is suppressed or deduplicated, announce `NO-GO` and keep writers stopped.

Keep writers stopped until promotion, endpoint switching, and consumer activation are complete.

### 6. Promote exactly once

This is the only irreversible step in the runbook. Before you run the command, confirm the recovery position in [No-go and recovery decisions](#no-go-and-recovery-decisions): after promotion you cannot demote, and once a target-only write lands, Ledger v2 no longer holds all production state.

Use the same control surface that owns the ledger.

Do not promote from the snapshot captured before final validation. Immediately before the promotion request, reread both sides and fail unless the complete frozen boundary still holds:

```bash
PRE_PROMOTION_SOURCE_LOG_ID="$(read_source_log_id)"

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

PRE_PROMOTION_MODE="$(jq -er '.mode | split("_")[-1]' <<<"$PRE_PROMOTION_TARGET_JSON")"
PRE_PROMOTION_CURSOR="$(jq -er '(.mirrorSyncProgress.cursor // 0) | tostring' <<<"$PRE_PROMOTION_TARGET_JSON")"
PRE_PROMOTION_SOURCE_HEAD="$(jq -er '(.mirrorSyncProgress.sourceLogCount // 0) | tostring' <<<"$PRE_PROMOTION_TARGET_JSON")"
PRE_PROMOTION_REMAINING="$(jq -er '(.mirrorSyncProgress.remainingLogs // 0) | tostring' <<<"$PRE_PROMOTION_TARGET_JSON")"
PRE_PROMOTION_ERROR_JSON="$(jq -c '.mirrorSyncProgress.error // null' <<<"$PRE_PROMOTION_TARGET_JSON")"

if [ "$PRE_PROMOTION_SOURCE_LOG_ID" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$PRE_PROMOTION_MODE" != "MIRROR" ] ||
   [ "$PRE_PROMOTION_CURSOR" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$PRE_PROMOTION_SOURCE_HEAD" != "$FINAL_SOURCE_LOG_ID" ] ||
   [ "$PRE_PROMOTION_REMAINING" != "0" ] ||
   [ "$PRE_PROMOTION_ERROR_JSON" != "null" ]; then
  printf 'pre-promotion boundary changed; do not promote\n' >&2
  exit 1
fi

jq \
  --arg finalSourceLogId "$FINAL_SOURCE_LOG_ID" \
  '{
    name,
    mode,
    finalSourceLogId: $finalSourceLogId,
    mirrorSyncProgress
  }' <<<"$PRE_PROMOTION_TARGET_JSON" > pre-promotion-gate.json
```

If this check fails, return to catch-up and validation. A changed source head creates a new final boundary; it cannot be accepted by editing the evidence file.

#### Operator-owned targets

Operator-managed promotion is not supported in the Stack v4 preview. If an Operator owns the ledger resource, do not bypass its reconciliation with a direct Ledger call; wait for the published promotion workflow. The following commands apply only when `ledgerctl` or HTTP is the approved control surface for that target.

#### `ledgerctl`

Point of no return

Promotion cannot be undone: there is no demotion operation. The CLI promotion request carries no idempotency key, so a command that times out leaves the outcome unknown from the client side. Read the ledger mode after every attempt, including a timeout or an error, and never send a second promotion request on the strength of a failed first one.

Set a bounded request timeout and record the output and exit status.

When the target has `require_signatures=true`, use a `ledgerctl` profile configured with a registered signing key or add `--signing-key <seed-file> --signing-key-id <registered-key-id>` before `ledgers promote`. The CLI signs the gRPC Apply batch. A signed gRPC client is the other supported control surface; the HTTP promotion route cannot carry the required request signature. The command block below assumes the active profile supplies the signing key when required; see [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing).

```bash
export PROMOTION_TIMEOUT="30s"
: "${PROMOTION_TIMEOUT:?set PROMOTION_TIMEOUT}"

set +e
PROMOTION_OUTPUT="$(ledgerctl ledgers promote "$TARGET_LEDGER" \
  --yes \
  --timeout "$PROMOTION_TIMEOUT" 2>&1)"
PROMOTION_EXIT="$?"
set -e

printf 'promotion exit=%s\n%s\n' \
  "$PROMOTION_EXIT" \
  "$PROMOTION_OUTPUT" \
  > promotion-ledgerctl-attempt.txt

POST_PROMOTION_JSON="$(ledgerctl ledgers get "$TARGET_LEDGER" --json)"
OBSERVED_MODE="$(jq -er '
  if .mode != null then
    (.mode | split("_")[-1])
  elif .mirrorSource == null and .mirrorSyncProgress == null then
    "NORMAL"
  else
    error("cannot determine ledger mode")
  end
' <<<"$POST_PROMOTION_JSON")"

case "$OBSERVED_MODE" in
  NORMAL)
    printf 'promotion committed; do not retry\n'
    ;;
  MIRROR)
    printf 'promotion not observed; rerun every cutover gate before one retry\n' >&2
    exit 75
    ;;
  *)
    printf 'unknown ledger mode after promotion attempt: %s\n' "$OBSERVED_MODE" >&2
    exit 1
    ;;
esac
```

The current structured output can omit the zero-value `NORMAL` enum; the check accepts that only when mirror source and progress are also absent. `NORMAL` means the request committed even if the first command timed out. Do not send another promotion request.

#### HTTP API

The token needs effective `ledger:LedgerWrite` and `ledger:LedgerRead` scopes. With the default scope mapping, the virtual `ledger:write` and `ledger:read` scopes include them. Set the complete HTTP surface:

Use this HTTP workflow only when the target accepts unsigned writes. The HTTP promotion handler submits an unsigned request and is rejected when `require_signatures=true`. In that case, use the signed `ledgerctl` or gRPC workflow above; do not disable mandatory signing for cutover.

```bash
export TARGET_URL="https://ledger.example.com"
export TARGET_TOKEN="<target-read-write-token>"
export TARGET_LEDGER="main-target"
export PROMOTION_TIMEOUT_SECONDS="30"
export CUTOVER_ID="<approved-cutover-id>"
export PROMOTION_KEY="promote-$TARGET_LEDGER-$CUTOVER_ID"

: "${TARGET_URL:?set TARGET_URL}"
: "${TARGET_TOKEN:?set TARGET_TOKEN}"
: "${TARGET_LEDGER:?set TARGET_LEDGER}"
: "${PROMOTION_TIMEOUT_SECONDS:?set PROMOTION_TIMEOUT_SECONDS}"
: "${CUTOVER_ID:?set CUTOVER_ID}"
: "${PROMOTION_KEY:?set PROMOTION_KEY once for this cutover}"
[[ "$PROMOTION_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]]
test "${#PROMOTION_KEY}" -le 256
command -v curl >/dev/null
command -v jq >/dev/null

PROMOTION_BODY_FILE="$(mktemp)"
trap 'rm -f "$PROMOTION_BODY_FILE"' EXIT

set +e
PROMOTION_STATUS="$(curl --silent --show-error \
  --max-time "$PROMOTION_TIMEOUT_SECONDS" \
  --output "$PROMOTION_BODY_FILE" \
  --write-out '%{http_code}' \
  --request POST \
  --header "Authorization: Bearer $TARGET_TOKEN" \
  --header "Idempotency-Key: $PROMOTION_KEY" \
  "$TARGET_URL/v3/$TARGET_LEDGER/promote")"
PROMOTION_EXIT="$?"
set -e

printf 'curlExit=%s httpStatus=%s idempotencyKey=%s\n' \
  "$PROMOTION_EXIT" \
  "$PROMOTION_STATUS" \
  "$PROMOTION_KEY" \
  > promotion-http-attempt.txt

PROMOTION_KEY_CONFLICT="false"
if [ "$PROMOTION_STATUS" = "409" ] &&
   jq -e '.errorCode == "IDEMPOTENCY_KEY_CONFLICT"' \
     "$PROMOTION_BODY_FILE" >/dev/null 2>&1; then
  PROMOTION_KEY_CONFLICT="true"
fi

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

OBSERVED_MODE="$(jq -er '
  .data
  | if .mode != null then
      (.mode | split("_")[-1])
    elif .mirrorSource == null and .mirrorSyncProgress == null then
      "NORMAL"
    else
      error("cannot determine ledger mode")
    end
' <<<"$POST_PROMOTION_JSON")"

if [ "$PROMOTION_KEY_CONFLICT" = "true" ]; then
  printf 'promotion idempotency key belongs to different request content; stop\n' >&2
  printf 'observed target mode: %s\n' "$OBSERVED_MODE" >&2
  exit 1
fi

case "$OBSERVED_MODE" in
  NORMAL)
    printf 'promotion committed; do not retry\n'
    ;;
  MIRROR)
    printf 'promotion not observed; rerun every cutover gate before one retry\n' >&2
    exit 75
    ;;
  *)
    printf 'unknown ledger mode after promotion attempt: %s\n' "$OBSERVED_MODE" >&2
    exit 1
    ;;
esac
```

The API normally returns `201`, but the follow-up mode read decides whether the operation committed. If the POST timed out and the read reports `NORMAL`, record the timeout and continue without retrying.

The current runtime handler accepts `Idempotency-Key` on promotion even though that header is not yet described by the OpenAPI operation. Keep `PROMOTION_KEY` stable in the approved cutover record. If an ambiguous result leads to one authorized manual retry, send the same method, target URL, empty body, and key. A changed key creates a different request identity. The mode read remains authoritative regardless of the POST status or idempotency response.

`IDEMPOTENCY_KEY_CONFLICT` is not an ambiguous retry result. It means the cluster-level key is already bound to different request content. Do not reuse that key or choose another one inside the same attempt. If the target remains in `MIRROR`, start a separately approved attempt with a fresh key only after rerunning every cutover gate. If the target is already `NORMAL`, stop and investigate which request promoted it before opening traffic.

Never put promotion in an automatic retry loop. If the follow-up read reports `MIRROR`, repeat the source freeze proof, derive the final source ID again, rerun the complete mirror gate, rerun final validation, and obtain a new `GO` decision before one manual retry. For an ambiguous HTTP result without an idempotency conflict, reuse the original `PROMOTION_KEY` and exact request. If that second attempt is ambiguous or still reports `MIRROR`, stop and escalate; do not send a third request. If the follow-up read itself fails, the state is unknown and no retry is safe until mode can be read.

### 7. Switch applications and consumers

Stop the Ledger v2 consumer at its recorded checkpoint. Confirm once more that the quarantined target replay has drained through the approved activation boundary and that no event at or below it can produce an effect.

Switch the target consumer from quarantine to active processing for events after that boundary. Keep both protections in place:

- deduplicate target redelivery with the target source identity and `logSequence`;
- deduplicate cross-version business effects with the stable business key validated during rehearsal.

Only then route application traffic to the target endpoint and activate the staged target credentials. Do not recreate the sink during this step: a new sink would start again at cursor `0` and replay the retained history.

Do not reopen all traffic yet.

### 8. Send one controlled production write

Release one approved business operation with a unique reference and idempotency key. Do not add synthetic financial state merely to test the system.

Verify independently:

- the write succeeded once;
- a retry returns the same accepted result;
- the transaction is readable by ID and reference;
- affected account balances and volumes match the expected amounts;
- the audit or correlation data identifies the caller;
- the expected downstream event arrived once after deduplication.

When the operation supports a business-approved reversal, verify that procedure in rehearsal rather than improvising a production cleanup.

### 9. Reopen traffic gradually

Increase traffic according to the cutover plan while watching:

- write and read errors;
- latency and retry rate;
- idempotency or reference conflicts;
- leader and quorum health;
- disk and compaction pressure;
- index readiness and query failures;
- event delivery lag and duplicate handling;
- business reconciliation signals.

Record the promotion, first write, and full-traffic timestamps.

## No-go and recovery decisions

| Point                                       | Available action                                                                                                                                           |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Before promotion                            | Resume Ledger v2 writes, investigate, or recreate the mirror. The target is still disposable.                                                              |
| After promotion, before a target-only write | You cannot demote. You may discard the promoted target and build a new mirror from the still-frozen Ledger v2 source, subject to the maintenance decision. |
| After a target-only write                   | Ledger v2 no longer contains all production state. Routing writes back is not a data rollback. Use the incident and reconciliation plan.                   |

Do not delete the Ledger v2 source immediately. Keep it read-only for the approved forensic and retention period, with write credentials revoked or disabled.

## Close the migration

- [ ] Target mode is normal and mirror progress no longer advances.
- [ ] First controlled write, retry, read, balance, and event checks pass.
- [ ] Target replay checkpoints and the consumer activation boundary are archived.
- [ ] No mirrored event repeated a Ledger v2 business effect.
- [ ] Production traffic is fully routed to the target.
- [ ] Ledger v2 remains read-only under the retention policy.
- [ ] Final source log ID and preserved target cursor are recorded.
- [ ] Validation evidence, rule hash, approvals, and timestamps are archived.
- [ ] Temporary source credentials and network access are revoked.
- [ ] Dashboards, alerts, backups, and on-call ownership reference the target.
- [ ] The migration lead and application owner sign completion.

The preserved cursor is useful forensic context after promotion, but it is not an ongoing replication position: the promoted ledger no longer follows Ledger v2.
