mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
2 hours ago 8672f11245231e8d7eecc2054653a3e3b133f1a3
[#1208] Use the active writer's replication server for combined scale checkpoints (#1351)

The combined scale test assumed that a directory server sent its writes
through the replication server on the same node. In the [failed
scale-kept run on
#1292](https://github.com/OpenIdentityPlatform/OpenDJ/actions/runs/46504294053/job/142212123836),
the active writer on `cv-c0` sent its writes through the departing
`cv-c2`. The test spent the final 696 seconds of the load waiting for
the replication server on `cv-c0` to cover a checkpoint that kept
advancing.

The test now reads `connected-to` for the workload domain before it
pauses writers. It keeps a directory server writing through a surviving
replication server, confirms an LDAP write, and compares that server's
changelog with the departing server's positions for every origin. It
checks the route again immediately before the stop. If the writer
changes replication servers, the test confirms a new write and takes a
fresh checkpoint. If all writers use the departing server, the test
waits within the existing deadline and leaves the server running.

The checkpoint's catch-up timeout starts once the writer has confirmed
its LDAP write and the test has verified its route. If that route
changes, the test prepares a new checkpoint with its own catch-up
timeout. Writer preparation, route retries and catch-up all share the
original load deadline (`ROLLING_END`).

## Verification

- All 27 replication self-test suites from the CI workflow passed
locally. The added cases cover a remote replication server, route
changes during a checkpoint, and a topology with no surviving route.
- The deterministic timeout regression covers 80 seconds of writer
preparation followed by 860 seconds of catch-up. The checkpoint succeeds
at second 940. The test also covers the 900-second catch-up limit, an
earlier load deadline and a route change during catch-up.
- In the earlier run on three combined OpenDJ nodes under load, the
first candidate used the departing server. The test selected another
writer, verified the checkpoint on its remote replication server,
stopped the departing node, and confirmed an LDAP write while it was
down.

Related to the scaling scenario in #1208.
4 files modified
399 ■■■■■ changed files
.github/scripts/replication/disturb-scale.sh 181 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/scale-monitor.py 56 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/selftest-disturb-scale.sh 133 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/selftest-scale-monitor.py 29 ●●●●● patch | view | raw | blame | history
.github/scripts/replication/disturb-scale.sh
@@ -40,12 +40,13 @@
# The administration port is published on loopback for scale rows. A native client
# avoids starting another JVM for every checkpoint and binds only to that loopback port.
scale_monitor_search() { # <node>
scale_monitor_search() { # <node> [connected-to <monitor DN>]
  local mapping port
  mapping=$(docker port "$1" 4444/tcp) || return 1
  case $mapping in 127.0.0.1:*) port=${mapping#127.0.0.1:} ;; *) echo 'admin port is not loopback-only' >&2; return 1 ;; esac
  case $port in ''|*[!0-9]*) echo 'invalid admin port' >&2; return 1 ;; esac
  printf '%s' "$ROOT_PASSWORD" | python3 -I "$HERE/scale-monitor.py" "$port" "$ROLLING_END_MS"
  shift
  printf '%s' "$ROOT_PASSWORD" | python3 -I "$HERE/scale-monitor.py" "$port" "$ROLLING_END_MS" "$@"
}
scale_checkpoint_query() { # <node> <output> <error> <role>
@@ -270,24 +271,24 @@
# During a combined-node checkpoint, request every pause before waiting for
# the departing node and the other writers to finish their segments. Keep the
# observer's clients running while the others' high-water marks become finite.
# selected writer's clients running while the others' high-water marks become finite.
# The other writers resume after the stop, and the departing writer after its join.
scale_hold_writers() { # <observer DS> <departing DS> <down|up>
  local observer=$1 departing=$2 direction=$3 node
scale_hold_writers() { # <writer DS> <departing DS> <down|up>
  local writer=$1 departing=$2 direction=$3 node
  # On a handoff, keep the old writer running until the new one has active
  # clients. Other parked workers can stay parked throughout.
  if [ -n "$SCALE_WRITER" ]; then
    rolling_resume "$writer" || return 1
    scale_wait "$writer resumes before the handoff" rolling_clients_running "$writer" || return 1
  fi
  SCALE_HELD_WRITERS=
  rolling_request_pause "$departing" || return 1
  for node in $DS_NODES; do
    [ "$node" != "$observer" ] && [ "$node" != "$departing" ] || continue
    # The removed node is absent during scale-in, but is a writer again during scale-out.
    [ "$node" != "$writer" ] && [ "$node" != "$departing" ] || continue
    [ "$direction" != down ] || [ "$node" != "$REMOVED" ] || continue
    rolling_request_pause "$node" || return 1
    SCALE_HELD_WRITERS="$SCALE_HELD_WRITERS $node"
  done
  rolling_pause "$departing" || return 1
  for node in $SCALE_HELD_WRITERS; do rolling_pause "$node" || return 1; done
  scale_wait "$observer has active load clients" rolling_clients_running "$observer" || return 1
  mkdir -p "$OUT/scale-progress" || return 1
  scale_wait "$observer accepts a checkpoint write" scale_probe "$observer" "$departing" "checkpoint-$direction" || return 1
  for node in "$departing" $SCALE_HELD_WRITERS; do rolling_request_pause "$node" || return 1; done
  for node in "$departing" $SCALE_HELD_WRITERS; do rolling_pause "$node" || return 1; done
}
scale_release_writers() {
@@ -297,6 +298,98 @@
  [ -z "$failed" ]
}
scale_writer_connected() { # <writer> <expected endpoint>
  local endpoint
  endpoint=$(scale_monitor_search "$1" connected-to "$MONITOR_DOMAIN") && [ "$endpoint" = "$2" ]
}
# End this wait when the checkpoint is ready or the writer changes route.
# Clearing SCALE_OBSERVER tells the caller to prepare a new checkpoint before stopping.
scale_routed_checkpoint() { # <departing> <down|up> <writer> <endpoint>
  local departing=$1 key= node
  if ! scale_writer_connected "$3" "$4"; then
    SCALE_OBSERVER=
    return 0
  fi
  scale_caught_up "$SCALE_OBSERVER" "$departing" || return 1
  # Docker reads a log position from each node. Recheck the route after these
  # reads finish, just before the stop.
  if [ "$departing" = "$REMOVED" ]; then
    dns_window_open "$departing" || return 200
    window_open "dns:$departing" 180 || return 200
  else
    key="-$2-$departing"
    window_open_key "${key#-}" "dns:$REMOVED" "dns:$departing" || return 200
  fi
  scale_writer_connected "$3" "$4" && return 0
  SCALE_OBSERVER=
  # The stop did not happen. Discard these pending starts so the next attempt
  # captures a new window without excusing errors from the intervening catch-up.
  for node in $ALL_NODES; do
    rm -f "$OUT/logs/$node.window$key" || return 200
    if [ "$departing" = "$REMOVED" ]; then rm -f "$OUT/logs/$node.dns-window" || return 200; fi
  done
  return 0
}
# A combined DS may send changes through a remote RS. Keep a writer whose serving
# RS survives this stop and compare that RS against the departing changelog.
scale_prepare_routed_writer() { # <departing> <down|up> <surviving node=endpoint>...
  local departing=$1 direction=$2 writer observer= pair endpoint probe="checkpoint-$2"
  local -a candidates=("$SCALE_WRITER")
  shift 2
  for pair in "$@"; do
    [ "${pair%%=*}" = "$SCALE_WRITER" ] || candidates+=("${pair%%=*}")
  done
  for writer in "${candidates[@]}"; do
    [ -n "$writer" ] || continue
    endpoint=$(scale_monitor_search "$writer" connected-to "$MONITOR_DOMAIN") || continue
    for pair in "$@"; do
      if [ "${pair#*=}" = "$endpoint" ]; then observer=${pair%%=*}; break 2; fi
    done
  done
  if [ -z "$observer" ]; then
    SCALE_OBSERVER=
    printf 'no workload DS connects to a surviving RS before stopping %s (eligible: %s)\n' \
      "$departing" "$*" >"$OUT/scale-checkpoint/check.txt"
    return 1
  fi
  scale_checkpoint_init "$observer" "$departing" || return 200
  printf 'writer=%s observer=%s endpoint=%s departing=%s\n' "$writer" "$observer" "$endpoint" "$departing" \
    >>"$SCALE_CHECKPOINT_DIR/history.txt" || return 200
  if [ -n "$SCALE_WRITER" ]; then probe="$probe-$SCALE_CHECKPOINT_NUMBER"; fi
  if [ "$writer" != "$SCALE_WRITER" ]; then
    scale_hold_writers "$writer" "$departing" "$direction" || return 200
  fi
  scale_wait "$writer has active load clients" rolling_clients_running "$writer" || return 200
  scale_wait "$writer accepts a checkpoint write" scale_probe "$writer" "$departing" "$probe" || return 200
  SCALE_WRITER=$writer
  scale_writer_connected "$writer" "$endpoint" || return 1
  SCALE_OBSERVER=$observer
  SCALE_ENDPOINT=$endpoint
}
scale_combined_checkpoint() { # <departing> <down|up>
  local departing=$1 direction=$2 node address SCALE_OBSERVER= SCALE_ENDPOINT=
  local -a survivors=()
  SCALE_WRITER=
  mkdir -p "$OUT/scale-checkpoint" "$OUT/scale-progress" || return 1
  for node in $RS_NODES; do
    [ "$node" != "$departing" ] || continue
    [ "$direction" = up ] || [ "$node" != "$REMOVED" ] || continue
    address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NETWORK\").IPAddress}}" "$node") || return 1
    case $address in ''|*[!0-9.]*) return 1 ;; esac
    survivors+=("$node=$address:8989")
  done
  while :; do
    scale_wait "a writer confirms a write through a surviving RS" \
      scale_prepare_routed_writer "$departing" "$direction" "${survivors[@]}" || return 1
    scale_wait "$SCALE_OBSERVER reaches the checkpoint of $departing" \
      scale_routed_checkpoint "$departing" "$direction" "$SCALE_WRITER" "$SCALE_ENDPOINT" || return 1
    [ -z "$SCALE_OBSERVER" ] || return 0
  done
}
# A restart removes the old container and with it its bootstrap timings. Keep the
# Docker timestamp on each line so events from different processes can be correlated.
scale_capture_bootstrap() { # <node> <generation>
@@ -347,33 +440,33 @@
}
scale_roll() { # <node> <peer list>
  local node=$1 peers=$2 role=directory from observer= writer= candidate direction=up
  local node=$1 peers=$2 role=directory from observer= writer= candidate direction=up SCALE_WRITER=
  [ "$peers" != "$SHORT_PEERS" ] || direction=down
  for candidate in $RS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
    observer=$candidate; break
  done
  [ -n "$observer" ] || { fail "no replication server remains while rolling $node"; return 1; }
  for candidate in $DS_NODES; do
    [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
    writer=$candidate; break
  done
  [ -n "$writer" ] || { fail "no directory server remains while rolling $node"; return 1; }
  [ "$TOPOLOGY" != combined ] || role=combined
  case " $RS_ONLY " in *" $node "*) role=replication ;; esac
  SCALE_HELD_WRITERS=
  if [ "$TOPOLOGY" = combined ]; then
    scale_hold_writers "$observer" "$node" "$direction" || { scale_release_writers || :; return 1; }
  elif is_directory_node "$node"; then
    rolling_pause "$node" || return 1
    role=combined
    scale_combined_checkpoint "$node" "$direction" || { scale_release_writers || :; return 1; }
    writer=$SCALE_WRITER
  else
    for candidate in $RS_NODES; do
      [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
      observer=$candidate; break
    done
    [ -n "$observer" ] || { fail "no replication server remains while rolling $node"; return 1; }
    for candidate in $DS_NODES; do
      [ "$candidate" != "$REMOVED" ] && [ "$candidate" != "$node" ] || continue
      writer=$candidate; break
    done
    [ -n "$writer" ] || { fail "no directory server remains while rolling $node"; return 1; }
    case " $RS_ONLY " in *" $node "*) role=replication ;; esac
    if is_directory_node "$node"; then rolling_pause "$node" || return 1; fi
    case " $RS_NODES " in
      *" $node "*)
        scale_checkpoint_wait "$observer reaches a checkpoint of $node" "$observer" "$node" || return 1
        window_open_key "$direction-$node" "dns:$REMOVED" "dns:$node" || return 1 ;;
      *) window_open_key "$direction-$node" "dns:$REMOVED" || return 1 ;;
    esac
  fi
  case " $RS_NODES " in
    *" $node "*) scale_checkpoint_wait "$observer reaches a checkpoint of $node" "$observer" "$node" || { scale_release_writers || :; return 1; } ;;
  esac
  case " $RS_NODES " in
    *" $node "*) window_open_key "$direction-$node" "dns:$REMOVED" "dns:$node" || { scale_release_writers || :; return 1; } ;;
    *) window_open_key "$direction-$node" "dns:$REMOVED" || { scale_release_writers || :; return 1; } ;;
  esac
  from=$(date +%s) || { scale_release_writers || :; return 1; }
  docker stop -t 120 "$node" >/dev/null || { scale_release_writers || :; return 1; }
  scale_release_writers || return 1
@@ -743,18 +836,18 @@
}
disturb() {
  local node from end address surviving_rs= REJOINED_WITH_NEW_ID=0
  local node from end address surviving_rs= REJOINED_WITH_NEW_ID=0 SCALE_WRITER=
  local -a return_window=("dns:$REMOVED" 180) recovery=() certificate_peers=()
  from=$(date +%s) || return 1
  SCALE_HELD_WRITERS=
  if [ "$TOPOLOGY" = combined ]; then
    scale_hold_writers "$SURVIVING_RS" "$REMOVED" down || { scale_release_writers || :; return 1; }
  elif is_directory_node "$REMOVED"; then
    rolling_pause "$REMOVED" || return 1
    scale_combined_checkpoint "$REMOVED" down || { scale_release_writers || :; return 1; }
  else
    if is_directory_node "$REMOVED"; then rolling_pause "$REMOVED" || return 1; fi
    scale_checkpoint_wait "$SURVIVING_RS reaches the departing RS checkpoint" "$SURVIVING_RS" "$REMOVED" || return 1
    dns_window_open "$REMOVED" || return 1
    window_open "dns:$REMOVED" 180 || return 1
  fi
  scale_checkpoint_wait "$SURVIVING_RS reaches the departing RS checkpoint" "$SURVIVING_RS" "$REMOVED" || { scale_release_writers || :; return 1; }
  dns_window_open "$REMOVED" || { scale_release_writers || :; return 1; }
  window_open "dns:$REMOVED" 180 || { scale_release_writers || :; return 1; }
  docker stop -t 120 "$REMOVED" >/dev/null || { scale_release_writers || :; return 1; }
  scale_release_writers || return 1
  ABSENCE_START=$(date +%s) || return 1
.github/scripts/replication/scale-monitor.py
@@ -148,14 +148,18 @@
    return '\n'.join(lines) + '\n\n'
def search(sock, password, deadline, present=b'replicationServer-database',
           attributes=(b'replicationServer-database', b'domain-name', b'last-change')):
    bind = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, bind)), deadline)
def bind(sock, password, deadline):
    request = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, request)), deadline)
    tag, result = message(sock, 1, deadline)
    if tag != 0x61:
        raise LdapError('expected LDAP bind response')
    require_success(result)
def search(sock, password, deadline, present=b'replicationServer-database',
           attributes=(b'replicationServer-database', b'domain-name', b'last-change')):
    bind(sock, password, deadline)
    query = (tlv(0x04, b'cn=monitor') + tlv(0x0a, b'\x02') + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             tlv(0x87, present) + tlv(0x30, b''.join(tlv(0x04, attr) for attr in attributes)))
@@ -201,7 +205,7 @@
    return attributes
def membership_search(sock, deadline, message_id, base, scope, ldap_filter, attribute):
def attribute_search(sock, deadline, message_id, base, scope, ldap_filter, attribute):
    query = (tlv(0x04, base) + tlv(0x0a, bytes([scope])) + tlv(0x0a, b'\x00') +
             tlv(0x02, b'\x00') + tlv(0x02, b'\x00') + tlv(0x01, b'\x00') +
             ldap_filter + tlv(0x30, tlv(0x04, attribute)))
@@ -223,6 +227,16 @@
            raise LdapError('unexpected LDAP search response')
def connected_to(sock, password, deadline, domain):
    bind(sock, password, deadline)
    attribute = b'connected-to'
    entries = attribute_search(sock, deadline, 2, domain.encode('utf-8'), 1, tlv(0x87, attribute), attribute)
    values = entries[0].get('connected-to', []) if len(entries) == 1 else []
    if len(values) != 1 or not values[0]:
        raise LdapError('expected one connected-to endpoint for ' + domain)
    return values[0]
def membership_matches(registry, config, peer, wanted):
    if wanted not in ('present', 'absent') or not registry or not config:
        return False
@@ -240,24 +254,23 @@
def membership(sock, password, deadline, peer, wanted):
    bind = tlv(0x02, b'\x03') + tlv(0x04, b'cn=Directory Manager') + tlv(0x80, password)
    transmit(sock, tlv(0x30, tlv(0x02, b'\x01') + tlv(0x60, bind)), deadline)
    tag, result = message(sock, 1, deadline)
    if tag != 0x61:
        raise LdapError('expected LDAP bind response')
    require_success(result)
    registry = membership_search(sock, deadline, 2, b'cn=Servers,cn=admin data', 1,
                                 tlv(0x87, b'objectClass'), b'hostname')
    bind(sock, password, deadline)
    registry = attribute_search(sock, deadline, 2, b'cn=Servers,cn=admin data', 1,
                                tlv(0x87, b'objectClass'), b'hostname')
    equal = lambda value: tlv(0xa3, tlv(0x04, b'objectClass') + tlv(0x04, value))
    ldap_filter = tlv(0xa1, equal(b'ds-cfg-replication-server') + equal(b'ds-cfg-replication-domain'))
    config = membership_search(sock, deadline, 3, b'cn=config', 2, ldap_filter,
                               b'ds-cfg-replication-server')
    config = attribute_search(sock, deadline, 3, b'cn=config', 2, ldap_filter,
                              b'ds-cfg-replication-server')
    return membership_matches(registry, config, peer, wanted)
def main(argv):
    if len(argv) not in (3, 6) or (len(argv) == 6 and (argv[3] != 'membership' or argv[5] not in ('present', 'absent'))):
        print('usage: scale-monitor.py <loopback port> <load deadline in milliseconds> [membership <peer> <present|absent>]', file=sys.stderr)
    args = argv[3:]
    route = len(args) == 2 and args[0] == 'connected-to'
    member = len(args) == 3 and args[0] == 'membership' and args[2] in ('present', 'absent')
    if len(argv) < 3 or (args and not (route or member)):
        print('usage: scale-monitor.py <loopback port> <load deadline in milliseconds> '
              '[connected-to <monitor DN> | membership <peer> <present|absent>]', file=sys.stderr)
        return 2
    try:
        port, load_deadline = int(argv[1]), int(argv[2]) / 1000
@@ -275,8 +288,13 @@
        context.verify_mode = ssl.CERT_NONE  # Same trust policy as the existing --trustAll search.
        with socket.create_connection(('127.0.0.1', port), timeout=remaining) as raw:
            with context.wrap_socket(raw, server_hostname='localhost') as connection:
                output = search(connection, password, deadline) if len(argv) == 3 else None
                matched = membership(connection, password, deadline, argv[4], argv[5]) if len(argv) == 6 else True
                output, matched = None, True
                if route:
                    output = connected_to(connection, password, deadline, args[1]) + '\n'
                elif member:
                    matched = membership(connection, password, deadline, args[1], args[2])
                else:
                    output = search(connection, password, deadline)
        if time.monotonic() >= deadline or time.time() >= load_deadline:
            raise TimeoutError('LDAP response completed after the deadline')
        if output is not None:
.github/scripts/replication/selftest-disturb-scale.sh
@@ -35,6 +35,7 @@
  ALL_NODES="$DS_NODES${RS_ONLY:+ $RS_ONLY}"
  PEERS=$(echo "$ALL_NODES" | tr ' ' ',')
  TOPOLOGY=$topology SCALE_VOLUME=$mode DISTURB_TIMEOUT=900 ROLLING_END=$((SECONDS + 900))
  NETWORK=fixture MONITOR_DOMAIN='cn=dc_example_dc_com,cn=Replication,cn=monitor'
  BASE_DN=dc=example,dc=com ROOT_PASSWORD=password
  . "$HERE/disturb-scale.sh"
  record() { printf '%s\n' "$*" >>"$OUT/calls"; }
@@ -72,7 +73,14 @@
  }
  start_server() { record "start $1 $2 $PEERS"; [ "$#" -le 2 ] || record "start-options $1 ${*:3}"; }
  admin_search() { echo 'scale checkpoint must not start an admin-search JVM' >&2; return 1; }
  scale_monitor_search() { record "search $1"; echo 'baseline'; }
  scale_monitor_search() {
    if [ "$2" = connected-to ]; then
      printf '%s:8989\n' "$(docker inspect "$1")"
    else
      record "search $1"; echo 'baseline'
    fi
  }
  scale_caught_up() { record "wait scale_caught_up $*"; [ "${FAIL_CHECKPOINT:-0}" != 1 ]; }
  window_open() { record "window $*"; }; window_close() { :; }
  window_open_key() { record "key-open $1"; shift; record "window $*"; }
  window_close_key() { record "window-close $1"; }
@@ -85,6 +93,7 @@
  record_rejoined_id() { REJOINED_WITH_NEW_ID=$new_id; record "identity $1"; }
  scale_backlog() { record "fill $REMOVED"; }
  wait_until() {
    case $3 in scale_prepare_routed_writer|scale_routed_checkpoint) "${@:3}"; return $? ;; esac
    record "wait ${*:3}"
    [ "${FAIL_CHECKPOINT:-0}" != 1 ] || [ "${3:-}" != scale_caught_up ] || return 1
    [ "${FAIL_RETURN_HISTORY:-0}" != 1 ] || [ "${3:-} ${4:-} ${5:-}" != 'scale_caught_up r2 r0' ] || return 1
@@ -102,6 +111,84 @@
  date() { echo 400; }
  sleep() { record "sleep $*"; }
  fail() { echo "$*" >&2; return 1; }
  # d0 writes through the departing RS. d1 starts on d0, switches to d3
  # while log windows open, then switches to the departing RS during catch-up.
  if [ "$topology-$mode-$new_id" = combined-kept-0 ]; then (
    scale_monitor_search() {
      [ "$2" = connected-to ] && [ "$3" = "$MONITOR_DOMAIN" ] || return 1
      case $1 in
        d0) echo 172.18.0.11:8989 ;;
        d1)
          if [ -e "$OUT/blip" ]; then
            rm "$OUT/blip"; touch "$OUT/blipped"; echo 172.18.0.12:8989
          elif [ -e "$OUT/switched" ]; then echo 172.18.0.11:8989
          elif [ -e "$OUT/opened" ]; then echo 172.18.0.12:8989
          else echo 172.18.0.9:8989; fi ;;
        d3) echo 172.18.0.10:8989 ;;
        *) return 1 ;;
      esac
    }
    rolling_clients_running() { record "active $1"; }
    scale_probe() {
      record "write $*"
      [ "${FAIL_MOVED_WRITE:-0}" = 0 ] || [ ! -e "$OUT/opened" ]
    }
    scale_caught_up() {
      record "checkpoint $*"
      if [ "$1" = d3 ]; then touch "$OUT/switched"; fi
    }
    window_open_key() {
      local node
      for node in $ALL_NODES; do
        [ ! -e "$OUT/logs/$node.window-$1" ] || return 1
        touch "$OUT/logs/$node.window-$1"
      done
      if [ "${ROUTE_BLIP:-0}" = 1 ] && [ ! -e "$OUT/blipped" ]; then
        touch "$OUT/blip"
      else
        touch "$OUT/opened"
      fi
    }
    wait_until() {
      shift 2
      local try rc
      for try in 1 2 3 4; do
        "$@" && return 0; rc=$?
        [ "$rc" != 200 ] || return 1
      done
      return 1
    }
    started_since() { :; }; bootstrap_ended() { :; }
    if (FAIL_MOVED_WRITE=1; scale_roll d2 "$FULL_PEERS"); then
      echo 'accepted an unconfirmed write after the same DS changed serving RS' >&2; exit 1
    fi
    if grep -q '^docker stop ' "$OUT/calls"; then echo 'stopped after a failed route probe' >&2; exit 1; fi
    rm -f "$OUT/opened" "$OUT/switched"
    : >"$OUT/calls"
    ROUTE_BLIP=1 scale_roll d2 "$FULL_PEERS" || { echo 'could not roll d2 with a surviving route' >&2; exit 1; }
    awk '
      /^active d1$/ && !first { first=NR }
      /^checkpoint d0 d2$/ { observed=NR }
      /^write d1 d2 checkpoint-up/ { probes++; confirmed=NR }
      /^checkpoint d3 d2$/ { moved=NR }
      /^active d3$/ && !replacement { replacement=NR }
      /^resume d0$/ && !stopped { exit 1 }
      /^request-pause d1$/ { held=NR }
      /^checkpoint d1 d2$/ { checked=NR }
      /^docker stop -t 120 d2$/ { stopped=NR }
      /^write d3 d2 up$/ { written=NR }
      END { if (!(probes == 3 && first && first < observed && observed < confirmed && confirmed < moved &&
                  moved < replacement && replacement < held && held < checked && checked < stopped &&
                  stopped < written)) exit 1 }
    ' "$OUT/calls" || { echo 'checkpoint did not follow the active writer to a surviving RS' >&2; exit 1; }
    : >"$OUT/calls"
    # d3 is absent on scale-in. d0 and d1 both use d2, leaving no safe route.
    if scale_roll d2 "$SHORT_PEERS"; then echo 'accepted only departing routes' >&2; exit 1; fi
    if grep -Eq '^(request-pause|docker stop|checkpoint) ' "$OUT/calls"; then
      echo 'changed the topology before finding a surviving route' >&2; exit 1
    fi
  ); fi
  : >"$OUT/calls"
  # No server is stopped if the surviving RS has not reached the departing RS's checkpoint.
  if (FAIL_CHECKPOINT=1; disturb) >/dev/null 2>&1; then
    echo 'failed checkpoint was accepted' >&2; exit 1
@@ -446,6 +533,7 @@
  [ ! -e "$OUT/logs/$target.offline" ]
  # A failed observer query identifies the node and status in the checkpoint diagnostic.
  (
    . "$HERE/disturb-scale.sh"
    scale_monitor_search() { [ "$1" != observer ] || return 124; echo baseline; }
    scale_checkpoint_init observer departing
    if scale_caught_up observer departing; then echo 'failed checkpoint query accepted' >&2; exit 1; fi
@@ -465,6 +553,49 @@
    if (FAIL_PROBE=1; scale_probe_batch d2 up d0 d1 r0); then echo 'failed batch accepted' >&2; exit 1; fi
  fi
)
check_checkpoint_budget() ( # <load end> <caught up at> <expected result> <expected time> [route change at]
  local caught_up_at=$2 switch_at=${5:-} result=0
  OUT="$OUT/budget-$1-$2-$switch_at"
  mkdir -p "$OUT"
  TOPOLOGY=combined SCALE_VOLUME=kept
  . "$HERE/lib.sh"
  . "$HERE/disturb-scale.sh"
  # Use the real wait loop with a deterministic clock. Writer preparation takes 80 s.
  unset SECONDS
  SECONDS=0 ROLLING_END=$1 DISTURB_TIMEOUT=900
  sleep() { SECONDS=$((SECONDS + $1)); }
  rolling_request_pause() { :; }
  rolling_pause() { [ "$1" != "$REMOVED" ] || sleep 80; }
  rolling_clients_running() { :; }
  scale_probe() { :; }
  docker() {
    local node=${*: -1}
    [ "$1" = inspect ] && echo "172.18.0.1${node##*-c}"
  }
  scale_monitor_search() {
    if [ -n "$switch_at" ] && [ "$SECONDS" -ge "$switch_at" ]; then
      echo '172.18.0.11:8989'
    else
      echo '172.18.0.10:8989'
    fi
  }
  scale_caught_up() { [ "$SECONDS" -ge "$caught_up_at" ]; }
  dns_window_open() { :; }
  window_open() { :; }
  scale_combined_checkpoint "$REMOVED" down >"$OUT/result" 2>&1 || result=$?
  if [ "$result" != "$3" ] || [ "$SECONDS" != "$4" ]; then
    cat "$OUT/result" >&2
    echo "checkpoint with load end $1 and catch-up at $2 returned $result at $SECONDS, expected $3 at $4" >&2
    exit 1
  fi
)
check_checkpoint_budget 2580 940 0 940
check_checkpoint_budget 880 940 1 880
check_checkpoint_budget 2580 1000 1 980
# Switching RS at 900 starts a fresh checkpoint, still bounded by the same load end.
check_checkpoint_budget 2580 1700 0 1700 900
check_checkpoint_budget 1500 1700 1 1500 900
for topology in rs534 combined; do
  for mode in kept empty; do run_case "$topology" "$mode"; done
done
.github/scripts/replication/selftest-scale-monitor.py
@@ -57,15 +57,16 @@
class MonitorTest(unittest.TestCase):
    def exchange(self, responses, timeout=3):
    def exchange(self, responses, timeout=3, search=monitor.search, args=()):
        client, server = socket.socketpair()
        errors = []
        self.requests = []
        def respond():
            try:
                monitor.read_frame(server, time.monotonic() + 3)
                self.requests.append(monitor.read_frame(server, time.monotonic() + 3))
                server.sendall(responses[0])
                if len(responses) > 1:
                    monitor.read_frame(server, time.monotonic() + 3)
                    self.requests.append(monitor.read_frame(server, time.monotonic() + 3))
                    for data in responses[1:]:
                        for i in range(0, len(data), 3):
                            server.sendall(data[i:i + 3])
@@ -78,7 +79,7 @@
        thread = threading.Thread(target=respond)
        thread.start()
        try:
            return monitor.search(client, b'password', time.monotonic() + timeout)
            return search(client, b'password', time.monotonic() + timeout, *args)
        finally:
            client.close()
            thread.join(4)
@@ -92,6 +93,26 @@
        self.assertIn('dn:: ', text)
        self.assertTrue(text.endswith('\n\n'))
    def test_connected_to_reads_only_the_workload_domain(self):
        domain = 'cn=dc_example_dc_com,cn=Replication,cn=monitor'
        def route(entries, code=0):
            responses = [msg(1, 0x61, ldap_result(0))]
            responses.extend(msg(2, 0x64, member_entry(b'cn=DS,' + domain.encode(),
                             {b'connected-to': values})) for values in entries)
            responses.append(msg(2, 0x65, ldap_result(code)))
            return self.exchange(responses, search=monitor.connected_to, args=(domain,))
        endpoint = b'172.18.0.10:8989'
        self.assertEqual(route([[endpoint]]), endpoint.decode())
        query = list(monitor.fields(self.requests[1]))[1][1]
        fields = list(monitor.fields(query))
        self.assertEqual(fields[:2], [(0x04, domain.encode()), (0x0a, bytes([1]))])
        self.assertEqual(fields[-2:], [(0x87, b'connected-to'), (0x30, wrap(0x04, b'connected-to'))])
        for entries, code in [([], 0), ([[endpoint], [endpoint]], 0), ([[endpoint, endpoint]], 0),
                              ([[b'']], 0), ([[endpoint]], 3)]:
            with self.subTest(entries=entries, code=code), self.assertRaises(monitor.LdapError):
                route(entries, code)
    def test_rejects_bind_failure(self):
        with self.assertRaises(monitor.LdapError):
            self.exchange([msg(1, 0x61, ldap_result(49))])