Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

75.9 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import { readAssignmentInventorySnapshot } from './assignment/assignment-inventory-snapshot.js'
import { REGIONAL_REHOME_ARRIVAL_WINDOW_MS } from './regional-rehome-abort-reason.js'
import {
  RelayAssignmentStore as BaseRelayAssignmentStore,
  type RegionalRehomeAttempt,
  REGIONAL_REHOME_QUARANTINE_FAILURES,
  REGIONAL_REHOME_QUARANTINE_MS,
  REGIONAL_REHOME_REDRAIN_SEND_LIMIT
} from './assignment-store.js'
import {
  openInMemoryRelayDatabase,
  type RelayDatabase,
  type RelayLockOptions,
  type SqlRow
} from './database.js'
import {
  REGIONAL_REHOME_SQL_FAILURES_LIMIT,
  REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT,
  REGIONAL_REHOME_SQL_FAILURES_SUSTAIN_MS
} from './regional-rehome-safety.js'
import type { RegionalRehomeSafetySnapshot } from './relay-observability.js'

const source = {
  id: 'us-c1',
  url: 'https://us-c1.relay.example.test',
  region: 'us-central1' as const,
  capacityRequests: 100,
  connectionHardCap: 1_000 as const,
  connectionUnobservedBound: 60
}
const target = {
  id: 'asia-c1',
  url: 'https://asia-c1.relay.example.test',
  region: 'asia-east2' as const,
  capacityRequests: 100,
  connectionHardCap: 1_000 as const,
  connectionUnobservedBound: 60
}
// Bystander participates only in fleet safety.
const bystander = { ...source, id: 'us-c2', url: 'https://us-c2.relay.example.test' }
const sourceIncarnation = '11111111-1111-4111-8111-111111111111'
const targetIncarnation = '22222222-2222-4222-8222-222222222222'
const bystanderIncarnation = '33333333-3333-4333-8333-333333333333'

describe('regional rehome assignment state', () => {
  it('advances past a full candidate page whose destination lacks capacity', async () => {
    const context = await setup()
    for (let i = 0; i < 10; i++) {
      await activatePreferredSource(context, {
        userId: `blocked-${i}`,
        relayHostId: 'abcdefghijklmnop'
      })
    }
    context.advance(1)
    const reverse = { userId: 'healthy-reverse', relayHostId: 'abcdefghijklmnop' }
    await activateReversePreferredSource(context, reverse)
    await context.database.query(
      'UPDATE relay_cells SET capacity_requests = reserved_requests WHERE cell_id = ?',
      [target.id]
    )
    expect(await context.store.tryIdleRehome()).toMatchObject({
      userId: reverse.userId,
      sourceCellId: target.id,
      targetCellId: source.id
    })
    await context.database.close()
  })

  it('defaults optional correction off even with enabled durable control', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'cohort', relayHostId: 'abcdefghijklmnop' })
    const defaultStore = new IdleRehomeTestStore(context.database, context.now, {
      requireLiveCells: true
    })
    expect(await defaultStore.tryIdleRehome()).toBeNull()
    expect(
      await context.database.query('SELECT attempt_id FROM relay_region_rehome_attempts')
    ).toEqual([])
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    await context.database.close()
  })

  it('counts pre-existing generic migrations against the eight-migration cap', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'cap', relayHostId: 'abcdefghijklmnop' })
    for (let i = 0; i < 8; i++) {
      await context.database.query(
        `INSERT INTO relay_assignment_migrations
        (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, assignment_epoch,
         source_request_units, target_reserved_units, expires_at, created_at, updated_at)
         VALUES (?, ?, ?, ?, 1, 2, 1, 1, ?, ?, ?)`,
        [
          'generic',
          `synthetic-migration-${i}`,
          source.id,
          target.id,
          context.now() + 60_000,
          context.now(),
          context.now()
        ]
      )
    }
    expect(await context.store.tryIdleRehome()).toBeNull()
    await context.database.query(
      `UPDATE relay_assignment_migrations SET completed_at = ?
      WHERE user_id = 'generic' AND relay_host_id = 'synthetic-migration-0'`,
      [context.now()]
    )
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    const open = await context.database
      .query(`SELECT COUNT(*) AS count FROM relay_assignment_migrations
      WHERE completed_at IS NULL AND aborted_at IS NULL`)
    expect(Number(open[0]?.count)).toBe(8)
    await context.database.close()
  })

  it('does not let legacy hints certify a move', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'legacy', relayHostId: 'abcdefghijklmnop' })
    await context.database.query('DELETE FROM relay_region_decisions')
    expect(await context.store.tryIdleRehome()).toBeNull()
    await context.database.close()
  })

  it('refreshes later open attempts when an older attempt occupies the first page', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'page-1', relayHostId: 'abcdefghijklmnop' })
    const first = await context.store.tryIdleRehome()
    context.advance(10_000)
    await freshHeartbeats(context)
    await activatePreferredSource(context, { userId: 'page-2', relayHostId: 'abcdefghijklmnop' })
    const second = await context.store.tryIdleRehome()
    expect(second).not.toBeNull()
    context.advance(1_000)
    expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1)
    context.advance(1_000)
    expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1)
    const rows = await context.database.query(
      `SELECT attempt_id, updated_at FROM relay_region_rehome_attempts
      WHERE attempt_id = ?`,
      [second!.attemptId]
    )
    expect(Number(rows[0]?.updated_at)).toBe(context.now())
    await context.database.close()
  })

  it('does not open a transaction while the worker is disabled', async () => {
    const delegate = await openInMemoryRelayDatabase()
    const database = new TransactionCountingDatabase(delegate)
    const store = new IdleRehomeTestStore(database, () => 1_000_000)
    await store.inspectRegionalRehomeControl()
    database.transactionCalls = 0

    await expect(store.tryIdleRehome()).resolves.toBeNull()
    expect(database.transactionCalls).toBe(0)
    await database.close()
  })

  it('initializes a missing control row without opening a transaction', async () => {
    const delegate = await openInMemoryRelayDatabase()
    const database = new TransactionCountingDatabase(delegate)
    const store = new IdleRehomeTestStore(database, () => 1_000_000)

    await expect(store.tryIdleRehome()).resolves.toBeNull()
    expect(database.transactionCalls).toBe(0)
    await expect(store.inspectRegionalRehomeControl()).resolves.toMatchObject({
      generation: 0,
      enabled: false
    })
    await database.close()
  })

  it('uses a generation-bound durable kill switch', async () => {
    const context = await setup()
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true,
      ratePerMinute: 10
    })
    expect(await context.store.disableRegionalRehomeControl()).toBe(true)
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 2,
      enabled: false
    })
    await expect(
      context.store.applyRegionalRehomeControl({
        expectedGeneration: 1,
        enabled: true,
        notBefore: context.now(),
        ratePerMinute: 10,
        preferenceMaxAgeMs: 24 * 60 * 60_000,
        hostCooldownMs: 7 * 24 * 60 * 60_000,
        drainGraceMs: 60_000
      })
    ).rejects.toThrow('regional_rehome_generation_mismatch')
    await expect(
      context.store.applyRegionalRehomeControl({
        expectedGeneration: 2,
        enabled: true,
        notBefore: context.now(),
        ratePerMinute: 10,
        preferenceMaxAgeMs: 24 * 60 * 60_000,
        hostCooldownMs: 7 * 24 * 60 * 60_000,
        drainGraceMs: 60_000
      })
    ).resolves.toMatchObject({ generation: 3, enabled: true })
    await context.database.close()
  })

  it('moves one live preferred host and completes without disabling its source cell', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const neighbor = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }
    const sourceControl = await activatePreferredSource(context, identity)
    await activateSource(context, neighbor)

    const attempt = await context.store.tryIdleRehome()
    expect(attempt).toMatchObject({
      userId: identity.userId,
      relayHostId: identity.relayHostId,
      sourceCellId: source.id,
      sourceCellIncarnation: sourceIncarnation,
      targetCellId: target.id,
      targetCellIncarnation: targetIncarnation,
      previousEpoch: 1,
      assignmentEpoch: 2,
      sendAttempts: 1
    })
    expect(await context.store.resolve(neighbor)).toMatchObject({ cellId: source.id })
    expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
    expect(
      await context.database.query(
        'SELECT drain_outcome FROM relay_region_rehome_attempts WHERE attempt_id = ?',
        [attempt!.attemptId]
      )
    ).toEqual([{ drain_outcome: 'accepted' }])

    const targetControl = await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: 2,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
    await context.store.releaseActivity(identity, sourceControl)
    expect(await context.store.completeReadyRegionalRehomes()).toBe(1)

    expect(await context.store.resolve(identity)).toMatchObject({
      cellId: target.id,
      assignmentEpoch: 2
    })
    expect(await context.store.resolve(neighbor)).toMatchObject({ cellId: source.id })
    expect(
      await context.database.query(
        `SELECT completed_at, aborted_at FROM relay_assignment_migrations
       WHERE user_id = ? AND relay_host_id = ?`,
        [identity.userId, identity.relayHostId]
      )
    ).toEqual([{ completed_at: context.now(), aborted_at: null }])
    expect(
      await context.database.query(
        `SELECT drain_receipt_at, completed_at, aborted_at FROM relay_region_rehome_attempts`
      )
    ).toEqual([{ drain_receipt_at: context.now(), completed_at: context.now(), aborted_at: null }])
    expect(targetControl).toMatch(/^control:/)
    await context.database.close()
  })

  it('requires an advertised source capability', async () => {
    const context = await setup({ sourceProtocol: 0 })
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    expect(await context.store.tryIdleRehome()).toBeNull()
    expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await context.database.close()
  })

  it('fails fleet safety closed until source and target telemetry is fresh', async () => {
    const context = await setup()
    await context.database.query(`DELETE FROM relay_cell_rehome_safety WHERE cell_id = ?`, [
      target.id
    ])
    expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({
      requiredCells: 2,
      missingCells: 1,
      observedAt: 0
    })
    await heartbeat(context.store, source, sourceIncarnation, 3, 2, {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 2,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    })
    await heartbeat(context.store, target, targetIncarnation, 3, 2, {
      observedAt: context.now(),
      sqlFailures: 1,
      reconnects: 3,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    })
    expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({
      requiredCells: 2,
      missingCells: 0,
      observedAt: context.now(),
      sqlFailures: 1,
      reconnects: 5
    })
    await context.database.close()
  })

  it('counts only drainable cells as the rehome fleet, in every region', async () => {
    const context = await setup({ targetProtocol: 0 })

    expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({
      requiredCells: 1,
      missingCells: 0
    })
    await heartbeat(context.store, target, targetIncarnation, 3, 2)
    expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({
      requiredCells: 2,
      missingCells: 0
    })
    await context.database.close()
  })

  it('claims through the measured healthy baseline of pool micro-waits and churn', async () => {
    const context = await setup()
    const baseline = {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 42,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 2,
      databasePoolWaitersMax: 2,
      databasePoolWaitMsMax: 1
    }
    await heartbeat(context.store, source, sourceIncarnation, 3, 2, baseline)
    await heartbeat(context.store, target, targetIncarnation, 3, 2, baseline)
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })

    expect(await context.store.tryIdleRehome()).toMatchObject({
      sourceCellId: source.id,
      targetCellId: target.id
    })
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      enabled: true
    })
    await context.database.close()
  })

  it('latches off on a per-cell reconnect storm even when the fleet sum is low', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    const safety: RegionalRehomeSafetySnapshot = {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
    const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety)
    expect(candidate).toBeDefined()
    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET reconnects = 251 WHERE cell_id = ?`,
      [source.id]
    )

    const warnings = collectDisableWarnings()
    try {
      expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({
        outcome: 'deferred',
        reason: 'fleet-safety'
      })
    } finally {
      warnings.restore()
    }
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 2,
      enabled: false
    })
    expect(warnings.entries).toMatchObject([
      { reason: 'elevated_reconnects', maxReconnects: 251, controlGeneration: 2 }
    ])
    await context.database.close()
  })

  it('defers on target pool pressure without disabling, and claims once it clears', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    const safety: RegionalRehomeSafetySnapshot = {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
    const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety)
    expect(candidate).toBeDefined()
    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET database_pool_waiters_max = 17 WHERE cell_id = ?`,
      [target.id]
    )

    const warnings = collectDisableWarnings()
    try {
      expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({
        outcome: 'deferred',
        reason: 'candidate-ineligible'
      })
    } finally {
      warnings.restore()
    }
    // A scan-to-commit pool breach must skip without permanently disabling the worker.
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true
    })
    expect(warnings.entries).toEqual([])

    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET database_pool_waiters_max = 0 WHERE cell_id = ?`,
      [target.id]
    )
    expect(await context.store.tryIdleRehome()).toMatchObject({
      userId: 'user-1',
      sourceCellId: source.id,
      targetCellId: target.id
    })
    await context.database.close()
  })

  it('keeps selecting candidates while an unrelated cell is over the pool bar', async () => {
    // Fleet Math.max once let one narrow client pool empty every page.
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    await context.store.reconcileCells([source, target, bystander])
    await heartbeat(context.store, bystander, bystanderIncarnation, 3, 2, {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 150,
      databasePoolWaitersMax: 150,
      databasePoolWaitMsMax: 2_005
    })

    const safety: RegionalRehomeSafetySnapshot = {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
    expect(await context.store.selectIdleRegionalRehomeCandidates(safety)).toMatchObject([
      { sourceCellId: source.id, targetCellId: target.id }
    ])
    await context.database.close()
  })

  it('claims through ambient per-cell sql retry noise', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT}`
    )

    expect(await context.store.tryIdleRehome()).not.toBeNull()
    await context.database.close()
  })

  it('moves a live host on an asia-east2 cell back to its preferred us-central1 cell', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    await activateReversePreferredSource(context, identity)

    const attempt = await context.store.tryIdleRehome()
    expect(attempt).toMatchObject({
      userId: identity.userId,
      relayHostId: identity.relayHostId,
      preferredRegion: 'us-central1',
      sourceCellId: target.id,
      sourceCellIncarnation: targetIncarnation,
      targetCellId: source.id,
      targetCellIncarnation: sourceIncarnation,
      previousEpoch: 1,
      assignmentEpoch: 2,
      sendAttempts: 1
    })
    expect(
      await context.database.query(
        `SELECT preferred_region, source_cell_id, target_cell_id
         FROM relay_region_rehome_attempts`
      )
    ).toEqual([
      {
        preferred_region: 'us-central1',
        source_cell_id: target.id,
        target_cell_id: source.id
      }
    ])
    expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id })
    await context.database.close()
  })

  it('drops a candidate at scan time when no cell in the preferred region is usable', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    // Exclude certain skips during selection or they consume candidate-page slots.
    await context.database.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [
      target.id
    ])

    const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped')
    try {
      expect(await context.store.tryIdleRehome()).toBeNull()
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([])
    expect(
      await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`)
    ).toEqual([{ next_dispatch_at: 0 }])
    expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await context.database.close()
  })

  it('does not migrate when the last target is lost between selection and commit', async () => {
    const database = await openInMemoryRelayDatabase()
    const context = await setup({
      database,
      wrap: (delegate) =>
        hookAfterCandidateScan(delegate, async (transaction) => {
          await transaction.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [
            target.id
          ])
        })
    })
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })

    expect(await context.store.tryIdleRehome()).toBeNull()

    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true
    })
    expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await database.close()
  })

  it('leaves a host alone until its cooldown expires, then moves it back', async () => {
    const context = await setup({ hostCooldownMs: 3 * 24 * 60 * 60_000 })
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const targetControl = await completeRehomeToTarget(context, identity)
    // Pass dispatch interval so only cooldown prevents another claim.
    context.advance(10_000)
    await activateReversePreferredSource(context, identity)

    const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped')
    try {
      expect(await context.store.tryIdleRehome()).toBeNull()
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([])
    expect(await context.store.resolve(identity)).toMatchObject({ cellId: target.id })

    context.advance(3 * 24 * 60 * 60_000)
    await freshHeartbeats(context)
    await context.store.renewControlActivity(identity, {
      activityId: targetControl,
      cellId: target.id,
      expiresAt: context.now() + 90_000
    })
    await activateReversePreferredSource(context, identity)

    const attempt = await context.store.tryIdleRehome()
    expect(attempt).toMatchObject({
      preferredRegion: 'us-central1',
      sourceCellId: target.id,
      targetCellId: source.id
    })
    await context.database.close()
  })

  it('rejects a host whose attempt lands between the scan and the claim', async () => {
    const database = await openInMemoryRelayDatabase()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const context = await setup({
      database,
      wrap: (delegate) =>
        hookAfterCandidateScan(delegate, async (transaction) => {
          await transaction.query(
            `INSERT INTO relay_region_rehome_attempts
             (attempt_id, user_id, relay_host_id, preferred_region, source_cell_id,
              source_cell_incarnation, target_cell_id, target_cell_incarnation,
              previous_epoch, assignment_epoch, drain_grace_ms, send_attempts,
              created_at, updated_at)
             VALUES ('raced', ?, ?, 'asia-east2', ?, ?, ?, ?, 0, 1, 0, 0, ?, ?)`,
            [
              identity.userId,
              identity.relayHostId,
              source.id,
              sourceIncarnation,
              target.id,
              targetIncarnation,
              context.now(),
              context.now()
            ]
          )
        })
    })
    await activatePreferredSource(context, identity)

    expect(await context.store.tryIdleRehome()).toBeNull()

    expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await database.close()
  })

  it('does not scan a candidate whose preferred region has no drainable cell', async () => {
    // Without drain protocol the target could never rehome hosts back out; exclude before inventory scans.
    const context = await setup({ targetProtocol: 0 })
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })

    const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped')
    try {
      expect(await context.store.tryIdleRehome()).toBeNull()
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([])
    expect(
      await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`)
    ).toEqual([{ next_dispatch_at: 0 }])
    expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await context.database.close()
  })

  it('skips an unclean cell without latching the control off', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    await activatePreferredSource(context, {
      userId: 'user-2',
      relayHostId: 'ponmlkjihgfedcba'
    })
    // Per-cell bar can skip a candidate while fleet safety keeps the worker enabled.
    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1} WHERE cell_id = ?`,
      [target.id]
    )

    expect(await context.store.tryIdleRehome()).toBeNull()
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true
    })

    expect(
      await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`)
    ).toEqual([{ next_dispatch_at: 0 }])
    expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await context.database.close()
  })

  it('does not throttle or log an idle tick with no candidates', async () => {
    const context = await setup()

    const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped')
    try {
      expect(await context.store.tryIdleRehome()).toBeNull()
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([])
    expect(
      await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`)
    ).toEqual([{ next_dispatch_at: 0 }])
    await context.database.close()
  })

  it('pauses the claim without latching when a sql spike lands between selection and commit', async () => {
    const context = await setup()
    await activatePreferredSource(context, {
      userId: 'user-1',
      relayHostId: 'abcdefghijklmnop'
    })
    const safety: RegionalRehomeSafetySnapshot = {
      observedAt: context.now(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
    const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety)
    expect(candidate).toBeDefined()
    await context.database.query(
      `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`,
      [target.id]
    )

    expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({
      outcome: 'deferred',
      reason: 'fleet-safety'
    })
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true
    })
    expect(
      await context.database.query(`SELECT consecutive_failures FROM relay_region_rehome_worker_state`)
    ).toEqual([{ consecutive_failures: 0 }])
    expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
    await context.database.close()
  })

  it('rides out a single-stall sql spike without latching the control off', async () => {
    const context = await setup()
    // 10-06 06:16Z: one stall put the fleet sum at 396 for about a minute.
    for (let elapsed = 0; elapsed <= 90_000; elapsed += 6_000) {
      await sqlFailuresHeartbeats(context, 396)
      expect(await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))).toEqual([])
      context.advance(6_000)
    }
    await sqlFailuresHeartbeats(context, 0)
    await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' })
    expect(await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))).toHaveLength(1)
    // The next stall, ~610 s later, starts its own breach rather than extending the last one.
    context.advance(500_000)
    for (let elapsed = 0; elapsed <= 90_000; elapsed += 6_000) {
      await sqlFailuresHeartbeats(context, 396)
      await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))
      context.advance(6_000)
    }
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 1,
      enabled: true
    })
    await context.database.close()
  })

  it('latches the control off when the sql breach outlasts a stall', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' })
    const warnings = collectEventWarnings('orca_relay_regional_rehome_safety_disabled')
    try {
      for (let elapsed = 0; elapsed < REGIONAL_REHOME_SQL_FAILURES_SUSTAIN_MS; elapsed += 6_000) {
        await sqlFailuresHeartbeats(context, REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1)
        await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))
        context.advance(6_000)
      }
      expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ enabled: true })
      await sqlFailuresHeartbeats(context, REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1)
      expect(await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))).toEqual([])
    } finally {
      warnings.restore()
    }
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 2,
      enabled: false
    })
    expect(warnings.entries).toMatchObject([
      { reason: 'sql_failures', controlGeneration: 2, sustainedMs: 150_000 }
    ])
    await context.database.close()
  })

  it('still latches on a non-sql reason that fails alongside a sql spike', async () => {
    const context = await setup()
    await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' })
    const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(cleanSafety(context))
    expect(candidate).toBeDefined()
    await context.database.query(
      `UPDATE relay_cell_rehome_safety
       SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1}, control_activity_recovery_failures = 1
       WHERE cell_id = ?`,
      [target.id]
    )
    expect(await context.store.commitIdleRegionalRehome(candidate!, cleanSafety(context))).toEqual({
      outcome: 'deferred',
      reason: 'fleet-safety'
    })
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: 2,
      enabled: false
    })
    await context.database.close()
  })

  it('refreshes only the migration leases while source splices drain', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    await activatePreferredSource(context, identity)
    await context.store.acquireActivity(identity, {
      activityId: 'splice:source',
      kind: 'splice',
      cellId: source.id
    })
    await context.store.tryIdleRehome()
    const before = await context.database.query(
      `SELECT activity_id, expires_at FROM relay_assignment_activity_leases
       WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`,
      [identity.userId, identity.relayHostId]
    )
    context.advance(60_000)
    expect(await context.store.refreshRegionalRehomeLeases()).toBe(1)
    const after = await context.database.query(
      `SELECT activity_id, expires_at FROM relay_assignment_activity_leases
       WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`,
      [identity.userId, identity.relayHostId]
    )
    const beforeById = new Map(before.map((row) => [row.activity_id, row.expires_at]))
    const afterById = new Map(after.map((row) => [row.activity_id, row.expires_at]))
    expect(Number(afterById.get('migration:2'))).toBeGreaterThan(
      Number(beforeById.get('migration:2'))
    )
    expect(Number(afterById.get('control-pending:2'))).toBeGreaterThan(
      Number(beforeById.get('control-pending:2'))
    )
    expect(afterById.get('splice:source')).toBe(beforeById.get('splice:source'))
    await context.database.close()
  })

  it('stops refreshing an unregistered target and lets normal rollback retire it', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    await activatePreferredSource(context, identity)
    await context.store.tryIdleRehome()
    context.advance(6 * 60_000)
    expect(await context.store.refreshRegionalRehomeLeases()).toBe(0)
    await heartbeat(context.store, source, sourceIncarnation, 3, 2)
    expect(await context.store.abortExpiredEvacuations()).toBe(1)
    expect(await context.store.reapRegionalRehomeAttempts()).toBe(0)
    expect(await context.store.resolve(identity)).toMatchObject({
      cellId: source.id,
      assignmentEpoch: 3
    })
    expect(
      await context.database.query(
        `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts`
      )
    ).toEqual([{ completed_at: null, aborted_at: context.now() }])
    await context.database.close()
  })

  it('does not roll an unregistered target back to a stale regional source', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    await activatePreferredSource(context, identity)
    await context.store.tryIdleRehome()
    context.advance(6 * 60_000)
    await heartbeat(context.store, target, targetIncarnation, 3, 2)

    expect(await context.store.refreshRegionalRehomeLeases()).toBe(0)
    expect(await context.store.abortExpiredEvacuations()).toBe(0)
    expect(
      await context.database.query(
        `SELECT cell_id, assignment_epoch FROM relay_assignments
         WHERE user_id = ? AND relay_host_id = ?`,
        [identity.userId, identity.relayHostId]
      )
    ).toEqual([{ cell_id: target.id, assignment_epoch: 2 }])
    await context.database.close()
  })

  // Two contended candidates expose an erroneous break; the redrain lane reaches inventory through its separate fleet-safety read.
  it('completes a candidate behind two contended ones', async () => {
    const probe = new CellInventoryLockProbe()
    const context = await setup({ wrap: (database) => probe.wrap(database) })
    const identities = [
      { userId: 'user-1', relayHostId: 'abcdefghijklmnop' },
      { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' },
      { userId: 'user-3', relayHostId: 'aaaabbbbccccdddd' }
    ]
    for (const identity of identities) {
      // Dispatch is rate limited, so each claim needs its own interval.
      context.advance(60_000)
      await freshHeartbeats(context)
      const sourceControl = await activatePreferredSource(context, identity)
      const attempt = await context.store.tryIdleRehome()
      await context.store.activateControl(identity, {
        cellId: target.id,
        assignmentEpoch: 2,
        generation: 1
      })
      await context.store.markMigrationTargetRegistered(identity, {
        cellId: target.id,
        assignmentEpoch: 2
      })
      await context.store.releaseActivity(identity, sourceControl)
    }
    probe.reset()
    probe.failNoWaitTimes = 2
    const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy')

    let completed: number
    try {
      completed = await context.store.completeReadyRegionalRehomes()
    } finally {
      busy.restore()
    }

    expect(completed).toBe(1)
    expect(busy.entries).toEqual([
      {
        event: 'orca_relay_sweep_cell_inventory_busy',
        sweep: 'complete-ready-regional-rehomes',
        skipped: 2
      }
    ])
    await context.database.close()
  })

  // Only inventory contention is ordinary; other failures must propagate and count against dispatch.
  it('propagates a claim failure that is not inventory contention', async () => {
    const probe = new CellInventoryLockProbe()
    const context = await setup({ wrap: (database) => probe.wrap(database) })
    await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' })
    probe.reset()
    probe.failWith = new Error('relay_capacity_exhausted')
    const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy')

    try {
      await expect(context.store.tryIdleRehome()).rejects.toThrow('relay_capacity_exhausted')
    } finally {
      busy.restore()
    }

    expect(busy.entries).toEqual([])
    await context.database.close()
  })

  // One inventory failure abandons the transaction’s whole candidate page, so count all candidates skipped.

  it('skips a completion tick on a contended cell inventory without quarantining it', async () => {
    const probe = new CellInventoryLockProbe()
    const context = await setup({ wrap: (database) => probe.wrap(database) })
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: 2,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    await context.store.releaseActivity(identity, sourceControl)
    probe.reset()
    probe.failNoWait = true
    const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy')
    const failures = collectCandidateFailureWarnings()

    let completed: number
    try {
      completed = await context.store.completeReadyRegionalRehomes()
    } finally {
      failures.restore()
      busy.restore()
    }

    expect(completed).toBe(0)
    expect(probe.locks).not.toEqual([])
    expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true)
    expect(failures.entries).toEqual([])
    expect(busy.entries).toEqual([
      {
        event: 'orca_relay_sweep_cell_inventory_busy',
        sweep: 'complete-ready-regional-rehomes',
        skipped: 1
      }
    ])

    probe.failNoWait = false
    expect(await context.store.completeReadyRegionalRehomes()).toBe(1)
    await context.database.close()
  })

  // Inventory contention is temporary; quarantining it would hide healthy attempts from LIMIT pages for 15min.
  it('skips an abort tick on a contended cell inventory without quarantining it', async () => {
    const probe = new CellInventoryLockProbe()
    const context = await setup({ wrap: (database) => probe.wrap(database) })
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    const targetControl = await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: 2,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    await context.store.releaseActivity(identity, sourceControl)
    await context.store.releaseActivity(identity, targetControl)
    context.advance(24 * 60 * 60_000)
    await heartbeat(context.store, source, sourceIncarnation, 3, 2)
    probe.reset()
    probe.failNoWait = true
    const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy')
    const failures = collectCandidateFailureWarnings()

    let aborted: number
    try {
      aborted = await context.store.abortExpiredRegionalRehomes()
    } finally {
      failures.restore()
      busy.restore()
    }

    expect(aborted).toBe(0)
    expect(probe.locks).not.toEqual([])
    expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true)
    expect(failures.entries).toEqual([])
    expect(busy.entries).toEqual([
      {
        event: 'orca_relay_sweep_cell_inventory_busy',
        sweep: 'abort-expired-regional-rehomes',
        skipped: 1
      }
    ])

    probe.failNoWait = false
    expect(await context.store.abortExpiredRegionalRehomes()).toBe(1)
    await context.database.close()
  })

  it('rolls a host that never reached its target back to the source at the arrival window', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    await context.store.releaseActivity(identity, sourceControl)
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })

    context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS - 1)
    await freshHeartbeats(context)
    expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0)

    context.advance(1)
    await freshHeartbeats(context)
    expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(1)
    expect(await context.store.resolve(identity)).toMatchObject({
      cellId: source.id,
      assignmentEpoch: 3
    })
    expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0)
    await context.database.close()
  })

  it('leaves the durable switch alone when it rolls back an unarrived host', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    await context.store.releaseActivity(identity, sourceControl)
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    const before = await context.store.inspectRegionalRehomeControl()
    context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS)
    await freshHeartbeats(context)

    expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(1)

    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({
      generation: before.generation,
      enabled: true
    })
    const [attempt] = await context.database.query(
      'SELECT abort_reason FROM relay_region_rehome_attempts'
    )
    expect(attempt!.abort_reason).toBe('host_not_arrived')
    const preview = await context.store.previewRegionalRehomeEligibility()
    expect(preview.abortedLast24Hours).toEqual({ host_not_arrived: 1 })
    expect(
      (await readAssignmentInventorySnapshot(context.database, context.now())).regionalRehomes
    ).toMatchObject({ abortedLast24Hours: 1, hostNotArrivedLast24Hours: 1 })
    await context.database.close()
  })

  it('leaves a host that did reach its target for the completion sweep', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    // Age alone cannot abort an attempt whose target already owns the host.
    context.advance(REGIONAL_REHOME_ARRIVAL_WINDOW_MS)
    await freshHeartbeats(context)
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: 2,
      generation: 1,
      cellIncarnation: targetIncarnation
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    await context.store.releaseActivity(identity, sourceControl)

    expect(await context.store.abortUnarrivedRegionalRehomes()).toBe(0)
    expect(await context.store.completeReadyRegionalRehomes()).toBe(1)
    expect(await context.store.resolve(identity)).toMatchObject({ cellId: target.id })
    await context.database.close()
  })

  it('names the 24-hour latch in its own abort reason', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    expect(await context.store.tryIdleRehome()).not.toBeNull()
    await context.store.releaseActivity(identity, sourceControl)
    context.advance(24 * 60 * 60_000)
    await heartbeat(context.store, source, sourceIncarnation, 3, 2)

    expect(await context.store.abortExpiredRegionalRehomes()).toBe(1)

    const [attempt] = await context.database.query(
      'SELECT abort_reason FROM relay_region_rehome_attempts'
    )
    expect(attempt!.abort_reason).toBe('max_refresh_expired')
    expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ enabled: false })
    await context.database.close()
  })

  it('rolls back an inactive registered target only after the 24-hour bound', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    const targetControl = await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: 2,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: 2
    })
    await context.store.releaseActivity(identity, sourceControl)
    await context.store.releaseActivity(identity, targetControl)
    context.advance(24 * 60 * 60_000 - 1)
    await freshHeartbeats(context)
    expect(await context.store.abortExpiredRegionalRehomes()).toBe(0)
    context.advance(1)
    await heartbeat(context.store, source, sourceIncarnation, 3, context.now())
    expect(await context.store.abortExpiredRegionalRehomes()).toBe(1)
    expect(await context.store.resolve(identity)).toMatchObject({
      cellId: source.id,
      assignmentEpoch: 3
    })
    await context.database.close()
  })

  it('completes healthy candidates past a poisoned attempt and logs it', async () => {
    const context = await setup()
    const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const healthy = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }
    const poisonedSource = await activatePreferredSource(context, poisoned)
    const healthySource = await activatePreferredSource(context, healthy)
    const first = await context.store.tryIdleRehome()
    context.advance(6_000)
    const second = await context.store.tryIdleRehome()
    expect(first!.userId).toBe(poisoned.userId)
    expect(second!.userId).toBe(healthy.userId)
    for (const [identity, attempt, sourceControl] of [
      [poisoned, first, poisonedSource],
      [healthy, second, healthySource]
    ] as const) {
      await context.store.activateControl(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch,
        generation: 1
      })
      await context.store.markMigrationTargetRegistered(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch
      })
      await context.store.releaseActivity(identity, sourceControl)
    }
    // The production poison shape: the assignment moved past the attempt.
    await context.database.query(
      `UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 5
       WHERE user_id = ?`,
      [poisoned.userId]
    )
    const warnings = collectCandidateFailureWarnings()
    try {
      expect(await context.store.completeReadyRegionalRehomes()).toBe(1)
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([
      {
        event: 'orca_relay_regional_rehome_candidate_failed',
        operation: 'complete',
        attemptId: first!.attemptId,
        reason: 'regional_rehome_assignment_mismatch'
      }
    ])
    expect(
      await context.database.query(
        `SELECT completed_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`,
        [second!.attemptId]
      )
    ).toEqual([{ completed_at: context.now() }])
    await context.database.close()
  })

  it('quarantines a repeatedly failing candidate and redacts free-form errors', async () => {
    const context = await setup()
    const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const source1 = await activatePreferredSource(context, poisoned)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(poisoned, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(poisoned, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch
    })
    await context.store.releaseActivity(poisoned, source1)
    await context.database.query(
      `UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 5
       WHERE user_id = ?`,
      [poisoned.userId]
    )
    const warnings = collectCandidateFailureWarnings()
    try {
      for (let round = 0; round < REGIONAL_REHOME_QUARANTINE_FAILURES; round++) {
        expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
      }
      expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES)
      expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
      expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES)
      context.advance(REGIONAL_REHOME_QUARANTINE_MS + 1)
      await context.store.completeReadyRegionalRehomes()
      expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES + 1)
      expect(
        warnings.entries.every((entry) => entry.reason === 'regional_rehome_assignment_mismatch')
      ).toBe(true)
      context.advance(REGIONAL_REHOME_QUARANTINE_MS + 1)
      const database = context.database
      const original = database.transaction.bind(database)
      database.transaction = () => {
        throw new Error('postgresql://[email protected]/relay')
      }
      try {
        await context.store.completeReadyRegionalRehomes()
      } finally {
        database.transaction = original
      }
      const last = warnings.entries.at(-1)!
      expect(last.reason).toBe('redacted')
      expect(JSON.stringify(last)).not.toContain('secret')
    } finally {
      warnings.restore()
    }
    await context.database.close()
  })

  it('aborts healthy expired candidates past a poisoned attempt', async () => {
    const context = await setup()
    const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const healthy = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }
    const poisonedSource = await activatePreferredSource(context, poisoned)
    const healthySource = await activatePreferredSource(context, healthy)
    const first = await context.store.tryIdleRehome()
    context.advance(6_000)
    const second = await context.store.tryIdleRehome()
    for (const [identity, attempt, sourceControl] of [
      [poisoned, first, poisonedSource],
      [healthy, second, healthySource]
    ] as const) {
      const targetControl = await context.store.activateControl(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch,
        generation: 1
      })
      await context.store.markMigrationTargetRegistered(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch
      })
      await context.store.releaseActivity(identity, sourceControl)
      await context.store.releaseActivity(identity, targetControl)
    }
    await context.database.query(
      `UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 5
       WHERE user_id = ?`,
      [poisoned.userId]
    )
    context.advance(24 * 60 * 60_000)
    await freshHeartbeats(context)
    const warnings = collectCandidateFailureWarnings()
    try {
      expect(await context.store.abortExpiredRegionalRehomes()).toBe(1)
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([
      {
        event: 'orca_relay_regional_rehome_candidate_failed',
        operation: 'abort',
        attemptId: first!.attemptId,
        reason: 'regional_rehome_assignment_mismatch'
      }
    ])
    expect(
      await context.database.query(
        `SELECT aborted_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`,
        [second!.attemptId]
      )
    ).toEqual([{ aborted_at: context.now() }])
    await context.database.close()
  })

  it('keeps dual-control accounting when the drained host re-resolves mid-rehome', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    expect(await controlAccounting(context, identity)).toEqual({
      reservedControls: 2,
      controlLeases: 2
    })

    // The drained host re-resolves through the director while both the source
    // control and the target's pending control are still live.
    await context.store.assign(identity, 'asia-east2')
    expect(await controlAccounting(context, identity)).toEqual({
      reservedControls: 2,
      controlLeases: 2
    })

    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch
    })
    await context.store.releaseActivity(identity, sourceControl)
    expect(await controlAccounting(context, identity)).toEqual({
      reservedControls: 1,
      controlLeases: 1
    })

    expect(await context.store.completeReadyRegionalRehomes()).toBe(1)
    expect(
      await context.database.query(
        `SELECT completed_at FROM relay_assignment_migrations
       WHERE user_id = ? AND relay_host_id = ?`,
        [identity.userId, identity.relayHostId]
      )
    ).toEqual([{ completed_at: context.now() }])
    expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 1 })
    await context.database.close()
  })

  it('grants a host whose counter was skewed without duplicating its control', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.releaseActivity(identity, sourceControl)
    // Damage already written by a pre-fix sticky grant.
    await context.database.query(
      `UPDATE relay_assignments SET reserved_controls = 0
       WHERE user_id = ? AND relay_host_id = ?`,
      [identity.userId, identity.relayHostId]
    )

    await context.store.assign(identity, 'asia-east2')
    expect(
      await context.database.query(
        `SELECT activity_id FROM relay_assignment_activity_leases
       WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'control'`,
        [identity.userId, identity.relayHostId]
      )
    ).toEqual([{ activity_id: `control:${target.id}:1` }])
    expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 2 })
    await context.database.close()
  })

  it('repairs a skewed control counter before completing the rehome', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch
    })
    await context.store.releaseActivity(identity, sourceControl)
    // Damage already written by a pre-fix sticky grant.
    await context.database.query(
      `UPDATE relay_assignments SET reserved_controls = 0
       WHERE user_id = ? AND relay_host_id = ?`,
      [identity.userId, identity.relayHostId]
    )

    expect(await context.store.completeReadyRegionalRehomes()).toBe(1)
    expect(await controlAccounting(context, identity)).toEqual({
      reservedControls: 1,
      controlLeases: 1
    })
    expect(
      await context.database.query(
        `SELECT migration_leases FROM relay_assignments
       WHERE user_id = ? AND relay_host_id = ?`,
        [identity.userId, identity.relayHostId]
      )
    ).toEqual([{ migration_leases: 0 }])
    await context.database.close()
  })

  it('reports a repaired counter only for the candidate it repaired', async () => {
    const context = await setup()
    const skewed = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const clean = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }
    const skewedSource = await activatePreferredSource(context, skewed)
    const cleanSource = await activatePreferredSource(context, clean)
    const first = await context.store.tryIdleRehome()
    context.advance(6_000)
    const second = await context.store.tryIdleRehome()
    for (const [identity, attempt, sourceControl] of [
      [skewed, first, skewedSource],
      [clean, second, cleanSource]
    ] as const) {
      await context.store.activateControl(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch,
        generation: 1
      })
      await context.store.markMigrationTargetRegistered(identity, {
        cellId: target.id,
        assignmentEpoch: attempt!.assignmentEpoch
      })
      await context.store.releaseActivity(identity, sourceControl)
    }
    // Damage already written by a pre-fix sticky grant, on one host only.
    await context.database.query(
      `UPDATE relay_assignments SET reserved_controls = 0
       WHERE user_id = ? AND relay_host_id = ?`,
      [skewed.userId, skewed.relayHostId]
    )

    const warnings = collectCandidateFailureWarnings([
      'orca_relay_regional_rehome_activity_counts_repaired'
    ])
    try {
      expect(await context.store.completeReadyRegionalRehomes()).toBe(2)
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([
      {
        event: 'orca_relay_regional_rehome_activity_counts_repaired',
        attemptId: first!.attemptId
      }
    ])
    await context.database.close()
  })

  it('never repairs past a migration lease whose shape is wrong', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch
    })
    await context.store.releaseActivity(identity, sourceControl)
    await context.database.query(
      `UPDATE relay_assignments SET reserved_controls = 0
       WHERE user_id = ? AND relay_host_id = ?`,
      [identity.userId, identity.relayHostId]
    )
    await context.database.query(
      `UPDATE relay_assignment_migrations SET target_reserved_units = 9
       WHERE user_id = ? AND relay_host_id = ?`,
      [identity.userId, identity.relayHostId]
    )

    const warnings = collectCandidateFailureWarnings()
    try {
      expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([
      {
        event: 'orca_relay_regional_rehome_candidate_failed',
        operation: 'complete',
        attemptId: attempt!.attemptId,
        reason: 'migration_activity_lease_shape_mismatch'
      }
    ])
    expect(await controlAccounting(context, identity)).toEqual({
      reservedControls: 0,
      controlLeases: 1
    })
    await context.database.close()
  })

  it('stays silent when a repair cannot make the counts whole', async () => {
    const context = await setup()
    const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }
    const sourceControl = await activatePreferredSource(context, identity)
    const attempt = await context.store.tryIdleRehome()
    await context.store.activateControl(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch,
      generation: 1
    })
    await context.store.markMigrationTargetRegistered(identity, {
      cellId: target.id,
      assignmentEpoch: attempt!.assignmentEpoch
    })
    await context.store.releaseActivity(identity, sourceControl)
    // A vanished migration lease repairs on first assert but fails re-assert; no repaired event may escape rollback.
    await context.database.query(
      `DELETE FROM relay_assignment_activity_leases
       WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'migration'`,
      [identity.userId, identity.relayHostId]
    )

    const warnings = collectCandidateFailureWarnings([
      'orca_relay_regional_rehome_candidate_failed',
      'orca_relay_regional_rehome_activity_counts_repaired'
    ])
    try {
      expect(await context.store.completeReadyRegionalRehomes()).toBe(0)
    } finally {
      warnings.restore()
    }
    expect(warnings.entries).toEqual([
      {
        event: 'orca_relay_regional_rehome_candidate_failed',
        operation: 'complete',
        attemptId: attempt!.attemptId,
        reason: 'migration_activity_accounting_mismatch'
      }
    ])
    await context.database.close()
  })
})

class TransactionCountingDatabase implements RelayDatabase {
  transactionCalls = 0

  constructor(private readonly delegate: RelayDatabase) {}

  query(sql: string, params?: unknown[]): Promise<SqlRow[]> {
    return this.delegate.query(sql, params)
  }

  queryLocked(
    sql: string,
    params?: unknown[],
    options?: { failIfUnavailable?: boolean }
  ): Promise<SqlRow[]> {
    return this.delegate.queryLocked(sql, params, options)
  }

  transaction<T>(
    operation: (transaction: RelayDatabase) => Promise<T>,
    options?: { reportRetries?: boolean }
  ): Promise<T> {
    this.transactionCalls += 1
    return this.delegate.transaction(operation, options)
  }

  close(): Promise<void> {
    return this.delegate.close()
  }
}

type Context = Awaited<ReturnType<typeof setup>>

function collectDisableWarnings() {
  const entries: Record<string, unknown>[] = []
  const original = console.warn
  console.warn = (line: unknown, ...rest: unknown[]) => {
    try {
      const parsed = JSON.parse(line as string) as Record<string, unknown>
      if (parsed.event === 'orca_relay_regional_rehome_safety_disabled') {
        entries.push(parsed)
        return
      }
    } catch {
      // fall through to the real console for non-JSON lines
    }
    original(line, ...rest)
  }
  return {
    entries,
    restore: () => {
      console.warn = original
    }
  }
}

async function setup(
  options: {
    sourceProtocol?: number
    targetProtocol?: number
    hostCooldownMs?: number
    database?: RelayDatabase
    wrap?: (database: RelayDatabase) => RelayDatabase
  } = {}
) {
  let clock = 1_000_000
  const database = options.database ?? (await openInMemoryRelayDatabase())
  const store = new IdleRehomeTestStore(options.wrap?.(database) ?? database, () => clock, {
    regionalRehomeCohortPercent: 100,
    requireLiveCells: true,
    heartbeatTtlMs: 45_000
  })
  await store.inspectRegionalRehomeControl()
  clock += 24 * 60 * 60_000
  await store.applyRegionalRehomeControl({
    expectedGeneration: 0,
    enabled: true,
    notBefore: clock,
    ratePerMinute: 10,
    preferenceMaxAgeMs: 24 * 60 * 60_000,
    hostCooldownMs: options.hostCooldownMs ?? 7 * 24 * 60 * 60_000,
    drainGraceMs: 60 * 60_000
  })
  await store.reconcileCells([source, target])
  await heartbeat(store, source, sourceIncarnation, options.sourceProtocol ?? 3)
  await heartbeat(store, target, targetIncarnation, options.targetProtocol ?? 3)
  return {
    database,
    store,
    now: () => clock,
    advance: (milliseconds: number) => {
      clock += milliseconds
    }
  }
}

function collectEventWarnings(event: string) {
  const entries: Record<string, unknown>[] = []
  const original = console.warn
  console.warn = (line: unknown, ...rest: unknown[]) => {
    try {
      const parsed = JSON.parse(line as string) as Record<string, unknown>
      if (parsed.event === event) {
        entries.push(parsed)
        return
      }
    } catch {
      // fall through to the real console for non-JSON lines
    }
    original(line, ...rest)
  }
  return {
    entries,
    restore: () => {
      console.warn = original
    }
  }
}

function collectCandidateFailureWarnings(
  events: string[] = ['orca_relay_regional_rehome_candidate_failed']
) {
  const entries: Record<string, unknown>[] = []
  const original = console.warn
  console.warn = (line: unknown, ...rest: unknown[]) => {
    try {
      const parsed = JSON.parse(line as string) as Record<string, unknown>
      if (events.includes(parsed.event as string)) {
        entries.push(parsed)
        return
      }
    } catch {
      // fall through to the real console for non-JSON lines
    }
    original(line, ...rest)
  }
  return {
    entries,
    restore: () => {
      console.warn = original
    }
  }
}

async function controlAccounting(
  context: Context,
  identity: { userId: string; relayHostId: string }
): Promise<{ reservedControls: number; controlLeases: number }> {
  const assignment = (
    await context.database.query(
      `SELECT reserved_controls FROM relay_assignments
       WHERE user_id = ? AND relay_host_id = ?`,
      [identity.userId, identity.relayHostId]
    )
  )[0]!
  const leases = await context.database.query(
    `SELECT COUNT(*) AS controls FROM relay_assignment_activity_leases
     WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'control'`,
    [identity.userId, identity.relayHostId]
  )
  return {
    reservedControls: Number(assignment.reserved_controls),
    controlLeases: Number(leases[0]!.controls)
  }
}

async function cellReservations(context: Context): Promise<Record<string, number>> {
  const rows = await context.database.query(
    `SELECT cell_id, reserved_requests FROM relay_cells ORDER BY cell_id`
  )
  return Object.fromEntries(rows.map((row) => [String(row.cell_id), Number(row.reserved_requests)]))
}

async function freshHeartbeats(context: Context): Promise<void> {
  const safety = {
    observedAt: context.now(),
    sqlFailures: 0,
    reconnects: 0,
    controlActivityRecoveryFailures: 0,
    databasePoolWaiting: 0,
    databasePoolWaitersMax: 0,
    databasePoolWaitMsMax: 0
  }
  // The clock doubles as a strictly-increasing connection inclusion watermark.
  await heartbeat(context.store, source, sourceIncarnation, 3, context.now(), safety)
  await heartbeat(context.store, target, targetIncarnation, 3, context.now(), safety)
}

function cleanSafety(context: Context): RegionalRehomeSafetySnapshot {
  return {
    observedAt: context.now(),
    sqlFailures: 0,
    reconnects: 0,
    controlActivityRecoveryFailures: 0,
    databasePoolWaiting: 0,
    databasePoolWaitersMax: 0,
    databasePoolWaitMsMax: 0
  }
}

// Splits the fleet sum across both cells, each under the per-cell bar's scale.
async function sqlFailuresHeartbeats(context: Context, fleetSqlFailures: number): Promise<void> {
  const half = Math.floor(fleetSqlFailures / 2)
  const safety = cleanSafety(context)
  await heartbeat(context.store, source, sourceIncarnation, 3, context.now(), { ...safety, sqlFailures: half })
  await heartbeat(context.store, target, targetIncarnation, 3, context.now(), {
    ...safety,
    sqlFailures: fleetSqlFailures - half
  })
}

async function activatePreferredSource(
  context: Context,
  identity: { userId: string; relayHostId: string }
): Promise<string> {
  const assignment = await context.store.assign(identity, undefined, 'us-central1')
  const control = await context.store.activateControl(identity, {
    cellId: source.id,
    assignmentEpoch: assignment.assignmentEpoch,
    generation: 1,
    idleRegionalRehome: true,
    cellIncarnation: sourceIncarnation
  })
  await context.store.assign(identity, 'asia-east2')
  const issued = await context.store.exchangeRegionCorrection(
    identity,
    { v: 1, action: 'issue-window' },
    assignment.assignmentEpoch
  )
  await context.store.exchangeRegionCorrection(
    identity,
    {
      v: 1,
      action: 'report',
      generation: issued.window!.generation,
      assignmentEpoch: assignment.assignmentEpoch,
      policyVersion: 1,
      outcome: 'conclusive',
      measurements: { 'us-central1': 150, 'asia-east2': 50 }
    },
    assignment.assignmentEpoch
  )
  return control
}

// Hook after scan inside the claim transaction makes scan/claim races deterministic.
function hookAfterCandidateScan(
  database: RelayDatabase,
  hook: (transaction: RelayDatabase) => Promise<void>
): RelayDatabase {
  let fired = false
  const decorate = (delegate: RelayDatabase): RelayDatabase => ({
    dialect: delegate.dialect,
    query: async (sql, params) => {
      const rows = await delegate.query(sql, params)
      if (!fired && sql.includes('SELECT d.user_id, d.relay_host_id')) {
        fired = true
        await hook(delegate)
      }
      return rows
    },
    queryLocked: async (sql, params, lockOptions) =>
      await delegate.queryLocked(sql, params, lockOptions),
    transaction: async (operation, transactionOptions) =>
      await delegate.transaction(
        async (transaction) => await operation(decorate(transaction)),
        transactionOptions
      ),
    close: async () => undefined
  })
  return decorate(database)
}

async function completeRehomeToTarget(
  context: Context,
  identity: { userId: string; relayHostId: string }
): Promise<string> {
  const sourceControl = await activatePreferredSource(context, identity)
  const attempt = await context.store.tryIdleRehome()
  const targetControl = await context.store.activateControl(identity, {
    cellId: target.id,
    assignmentEpoch: attempt!.assignmentEpoch,
    generation: 1
  })
  await context.store.markMigrationTargetRegistered(identity, {
    cellId: target.id,
    assignmentEpoch: attempt!.assignmentEpoch
  })
  await context.store.releaseActivity(identity, sourceControl)
  await context.store.completeReadyRegionalRehomes()
  return targetControl
}

async function activateReversePreferredSource(
  context: Context,
  identity: { userId: string; relayHostId: string }
): Promise<string> {
  const assignment = await context.store.assign(identity, undefined, 'asia-east2')
  const control = await context.store.activateControl(identity, {
    cellId: target.id,
    assignmentEpoch: assignment.assignmentEpoch,
    generation: 1,
    idleRegionalRehome: true,
    cellIncarnation: targetIncarnation
  })
  await context.store.assign(identity, 'us-central1')
  const issued = await context.store.exchangeRegionCorrection(
    identity,
    { v: 1, action: 'issue-window' },
    assignment.assignmentEpoch
  )
  await context.store.exchangeRegionCorrection(
    identity,
    {
      v: 1,
      action: 'report',
      generation: issued.window!.generation,
      assignmentEpoch: assignment.assignmentEpoch,
      policyVersion: 1,
      outcome: 'conclusive',
      measurements: { 'us-central1': 50, 'asia-east2': 150 }
    },
    assignment.assignmentEpoch
  )
  return control
}

async function activateSource(
  context: Context,
  identity: { userId: string; relayHostId: string }
): Promise<string> {
  const assignment = await context.store.assign(identity, undefined, 'us-central1')
  return await context.store.activateControl(identity, {
    cellId: source.id,
    assignmentEpoch: assignment.assignmentEpoch,
    generation: 1
  })
}

async function heartbeat(
  store: IdleRehomeTestStore,
  cell: typeof source | typeof target,
  cellIncarnation: string,
  regionalRehomeProtocol: number,
  connectionInclusionWatermark = 1,
  regionalRehomeSafety?: RegionalRehomeSafetySnapshot
): Promise<void> {
  await store.recordCellHeartbeat({
    cellId: cell.id,
    cellUrl: cell.url,
    region: cell.region,
    cellIncarnation,
    startedAt: 900_000,
    ready: true,
    observedRequests: 0,
    totalConnections: 0,
    inFlightConnections: 0,
    reservedConnectionUnits: 0,
    enforcedConnectionUnits: 0,
    connectionInclusionWatermark,
    connectionHardCap: 1_000,
    connectionUnobservedBound: 60
  })
  await store.recordCellRegionalRehomeStatus({
    cellId: cell.id,
    cellIncarnation,
    regionalRehomeProtocol,
    safety: regionalRehomeSafety ?? {
      observedAt: 1_000_000 + 24 * 60 * 60_000,
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
  })
}

class CellInventoryLockProbe {
  readonly locks: (RelayLockOptions | undefined)[] = []
  failNoWait = false
  // Contends the first N candidates only, so the sweep must carry on past them.
  failNoWaitTimes = 0
  failWith: Error | null = null

  reset(): void {
    this.locks.length = 0
  }

  wrap(database: RelayDatabase): RelayDatabase {
    const probe = this
    const decorate = (delegate: RelayDatabase): RelayDatabase => ({
      dialect: delegate.dialect,
      query: async (sql, params) => await delegate.query(sql, params),
      queryLocked: async (sql, params, options) => {
        // The idle commit's only cell lock is its target row, so it counts too.
        if (
          sql.trim() === 'SELECT * FROM relay_cells ORDER BY cell_id ASC' ||
          sql.includes('FROM relay_cells cell')
        ) {
          probe.locks.push(options)
          if (probe.failWith) throw probe.failWith
          if (options?.failIfUnavailable && probe.failNoWaitTimes > 0) {
            probe.failNoWaitTimes--
            throw new Error('database_lock_unavailable')
          }
          if (probe.failNoWait && options?.failIfUnavailable) {
            throw new Error('database_lock_unavailable')
          }
        }
        return await delegate.queryLocked(sql, params, options)
      },
      transaction: async (operation, options) =>
        await delegate.transaction(
          async (transaction) => await operation(decorate(transaction)),
          options
        ),
      close: async () => undefined
    })
    return decorate(database)
  }
}

async function workerState(
  context: Context
): Promise<{ consecutiveFailures: number; pausedUntil: number }> {
  const row = (
    await context.database.query(
      `SELECT consecutive_failures, paused_until
       FROM relay_region_rehome_worker_state WHERE worker_id = 'global'`
    )
  )[0]!
  return {
    consecutiveFailures: Number(row.consecutive_failures),
    pausedUntil: Number(row.paused_until)
  }
}

class IdleRehomeTestStore extends BaseRelayAssignmentStore {
  private readonly fixtureDatabase: RelayDatabase
  private readonly fixtureNow: () => number
  constructor(...args: ConstructorParameters<typeof BaseRelayAssignmentStore>) {
    super(...args)
    this.fixtureDatabase = args[0]
    this.fixtureNow = args[1] ?? Date.now
  }
  async tryIdleRehome(
    processSafety?: RegionalRehomeSafetySnapshot
  ): Promise<RegionalRehomeAttempt | null> {
    const safety = processSafety ?? {
      observedAt: this.fixtureNow(),
      sqlFailures: 0,
      reconnects: 0,
      controlActivityRecoveryFailures: 0,
      databasePoolWaiting: 0,
      databasePoolWaitersMax: 0,
      databasePoolWaitMsMax: 0
    }
    for (const candidate of await this.selectIdleRegionalRehomeCandidates(safety)) {
      const result = await this.commitIdleRegionalRehome(candidate, safety)
      if (result.outcome !== 'committed') continue
      const row = (
        await this.fixtureDatabase.query(
          'SELECT * FROM relay_region_rehome_attempts WHERE attempt_id = ?',
          [candidate.attemptId]
        )
      )[0]!
      return {
        ...candidate,
        preferredRegion: row.preferred_region as RegionalRehomeAttempt['preferredRegion'],
        targetCellIncarnation: String(row.target_cell_incarnation),
        previousEpoch: Number(row.previous_epoch),
        assignmentEpoch: Number(row.assignment_epoch),
        drainGraceMs: Number(row.drain_grace_ms),
        sendAttempts: Number(row.send_attempts)
      }
    }
    return null
  }
}