# Fiatless money-lane alert definitions — REFERENCE CONFIGURATION.
#
# This file is a definition, not a deployment. Nothing in this repository
# installs a monitoring platform, and no claim is made that one exists. It is
# written in the Prometheus alerting-rule format because that is what the
# scrape at GET /api/v1/metrics already speaks (text exposition, version
# 0.0.4); any system that ingests that format — Prometheus, Thanos, Mimir,
# VictoriaMetrics, Grafana Alerting — can load it unchanged. Adapt the
# thresholds to the deployment's own cycle times before using it.
#
# Every rule points at a section of lane-backlog-alerts.md next to this file.
# internal/server/alerts_test.go refuses a rule whose metric this build does
# not export, whose label value no CHECK constraint admits, or whose runbook
# section does not exist — because an alert that can never fire is worse than
# no alert: it reports that someone is watching. lane-backlog-alerts.test.yml
# holds promtool unit tests for the rules that depend on time
# (promtool test rules lane-backlog-alerts.test.yml).
#
# The scrape is authenticated (scope admin:metrics) and cached for 5s server
# side, so a 15-30s scrape interval costs the database nothing.

groups:
  - name: fiatless-scrape
    rules:
      - alert: FiatlessScrapeFailing
        # Serving a partial scrape would be worse than none: an absent backlog
        # gauge reads as "backlog is zero". The collector fails the whole
        # response instead, so this is the first alert to trust.
        expr: absent(fiatless_up) == 1
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "The Fiatless scrape has stopped answering; every other alert here is now blind."
          runbook: docs/runbooks/lane-backlog-alerts.md#fiatlessscrapefailing

      - alert: FiatlessTargetDown
        # FiatlessScrapeFailing fires only once no replica answers; this names each one that stopped. Any job that
        # served fiatless_up in the last day is a Fiatless target, whatever the scrape config calls it.
        expr: up == 0 and on (job, instance) max_over_time(fiatless_up[1d])
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Prometheus cannot scrape the Fiatless replica {{ $labels.instance }}."
          runbook: docs/runbooks/lane-backlog-alerts.md#fiatlesstargetdown

      - alert: Watchdog
        # Always firing. Route it to a dead man's switch outside this stack: when it stops arriving, no alert can.
        expr: vector(1)
        labels:
          severity: watchdog
        annotations:
          summary: "The alerting pipeline is alive; this alert always fires."
          runbook: docs/runbooks/lane-backlog-alerts.md#watchdog

      - alert: ReplicaNotReady
        # /readyz answers starting or degraded; starting lasts one first cycle, so five minutes is not a rollout.
        # Tune it to the slowest lane's first cycle.
        expr: fiatless_ready == 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "A replica has answered /readyz not ready for 5 minutes."
          runbook: docs/runbooks/lane-backlog-alerts.md#replicanotready

  - name: fiatless-scanner
    rules:
      - alert: ScannerStreamStalled
        # Counts cannot see this. A scanner that stops advancing leaves every
        # count-based gauge frozen, which is indistinguishable from a chain
        # with no activity. The age runs from the last successful step: a step
        # at the head with no new block counts, a claim or a failure does not.
        expr: fiatless_chain_sync_checkpoint_age_seconds > 900
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "The {{ $labels.network }} scanner (stream {{ $labels.stream }}) has not completed a step against its node in 15 minutes."
          runbook: docs/runbooks/lane-backlog-alerts.md#scannerstreamstalled

      - alert: ScannerBehindHead
        # Freshness is not lag: a stream can advance every cycle and still fall behind the node. Payouts and sweeps
        # on the network wait while it is at least its confirmation count behind.
        # Seconds, not blocks, so one threshold fits every chain; tune it.
        expr: fiatless_chain_sync_lag_seconds > 900
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "The {{ $labels.network }} scanner (stream {{ $labels.stream }}) is more than 15 minutes behind the node's head."
          runbook: docs/runbooks/lane-backlog-alerts.md#scannerbehindhead

      - alert: ScannerHalted
        # A halt is deliberate and needs a human; it is NOT the same condition
        # as being behind, and it has its own recovery procedure.
        expr: fiatless_chain_sync_checkpoints_halted > 0
        for: 1m
        labels:
          severity: page
        annotations:
          summary: "A scanner stream is halted and will not resume on its own."
          runbook: docs/runbooks/halted-chain-recovery.md

      - alert: ChainIngestConflictsOpen
        # A node and an indexer disagreeing about the same event. Deposits are
        # not credited from a disputed observation.
        expr: fiatless_chain_ingest_conflicts > 0
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: "Open canonical ingestion conflicts between {{ $labels.sources }}."
          runbook: docs/runbooks/lane-backlog-alerts.md#chainingestconflictsopen

  - name: fiatless-lanes
    rules:
      - alert: LaneHeartbeatMissing
        # The lane-level version of ScannerStreamStalled: the recurring job
        # itself stopped reporting. /readyz already refuses traffic on this
        # condition; the alert exists because a whole deployment can be in it.
        expr: fiatless_task_heartbeat_age_seconds > 900
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Lane {{ $labels.task }} has not recorded an outcome in 15 minutes."
          runbook: docs/runbooks/lane-backlog-alerts.md#laneheartbeatmissing

      - alert: LaneFailingEveryCycle
        # A lane that fails every cycle heart-beats perfectly and does no work
        # at all. Freshness alone calls that healthy. A replica that finds the
        # lane's lease held records a heartbeat only, so replicas cannot clear
        # the count between the holder's failures.
        expr: fiatless_task_consecutive_failures >= 3
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Lane {{ $labels.task }} has failed every cycle since its last success."
          runbook: docs/runbooks/lane-backlog-alerts.md#lanefailingeverycycle

      - alert: LaneRunWedged
        # A cycle still open long past its own timeout is what a process that
        # died mid-run leaves behind.
        expr: fiatless_task_running_seconds > 1800
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Lane {{ $labels.task }} has been inside one run for over 30 minutes."
          runbook: docs/runbooks/lane-backlog-alerts.md#lanerunwedged

      - alert: LaneNeverSucceeded
        # -1 is the never-succeeded sentinel. A lane that has run since the
        # last deploy and never once completed is a broken deploy, not a
        # backlog.
        expr: fiatless_task_last_success_age_seconds == -1
        for: 30m
        labels:
          severity: page
        annotations:
          summary: "Lane {{ $labels.task }} has never completed a successful cycle."
          runbook: docs/runbooks/lane-backlog-alerts.md#laneneversucceeded

      - alert: LaneMakingNoProgress
        # A lane can heart-beat and succeed every cycle while it finishes nothing it owes. Two hours fits a
        # Bitcoin confirmation and a sweep waiting out a fee spike; tune it per lane.
        expr: fiatless_lane_stalled_seconds > 7200
        for: 10m
        labels:
          severity: ticket
        annotations:
          summary: "The {{ $labels.lane }} lane on network {{ $labels.network }} has owed work for 2 hours and finished none."
          runbook: docs/runbooks/lane-backlog-alerts.md#lanemakingnoprogress

  - name: fiatless-history
    rules:
      - alert: WalletHistoryNeverCompletes
        # The silent one. A wallet whose history sync never reaches 'completed'
        # is skipped by every consolidation query without producing an error
        # anywhere: the deployment runs a full sweep schedule, consolidates
        # nothing, and looks entirely healthy. A wallet used before Fiatless is an
        # operator's case, never swept by design, so it does not hold this open.
        expr: sum(fiatless_wallet_history_sync{status!~"completed|used_before"}) > 0
        for: 6h
        labels:
          severity: ticket
        annotations:
          summary: "Active deposit wallets have been stuck outside history status 'completed' for 6 hours."
          runbook: docs/runbooks/lane-backlog-alerts.md#wallethistorynevercompletes

      - alert: HistoryBackfillJobsDead
        # 'dead' is terminal: the job exhausted its attempts and nothing will
        # retry it. One a newer generation replaced (history-resume) is not
        # counted, so this clears once the wallet is enrolled again.
        expr: fiatless_history_backfill_jobs{status="dead"} > 0
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: "Wallet history backfill jobs have exhausted their attempts."
          runbook: docs/runbooks/lane-backlog-alerts.md#historybackfilljobsdead

  - name: fiatless-recovery
    rules:
      - alert: RecoveryHoldOpen
        # A restore, a restored dump, a failover or a move to another server changed the database, or an operator
        # declared a restore. Nothing clears it by itself.
        expr: fiatless_recovery_hold_open > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "A point-in-time recovery holds every payout, sweep and new deposit address until an operator accepts it."
          runbook: docs/runbooks/backup-restore-and-pitr.md#recovering-after-a-restore

      - alert: TreasuryBindingHalted
        # The seed derives another treasury than the bound one: the network issues no address and pays and sweeps
        # nothing until the seed returns or a re-bind and a restart. Nothing clears it by itself.
        expr: fiatless_treasury_binding_halted > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "The {{ $labels.network }} treasury is halted: this seed derives another treasury than the bound one."
          runbook: docs/runbooks/signer-binding-provisioning.md#a-start-on-another-seed-halts-the-network

  - name: fiatless-outbound
    rules:
      - alert: WithdrawalsNotLeavingTheQueue
        # Payouts alone: a sweep or gas top-up may wait queued for its gas, its funds or its quiet period
        # (LaneMakingNoProgress for the sweeps lane and DepositsNotSwept see those).
        expr: fiatless_withdrawals{status="queued", kind="payout"} > 0
        for: 30m
        labels:
          severity: page
        annotations:
          summary: "Payouts have sat queued for 30 minutes; the payout lane is not claiming them."
          runbook: docs/runbooks/lane-backlog-alerts.md#withdrawalsnotleavingthequeue

      - alert: PayoutsOverTheFeeLimit
        # A Tron token payout signed short would burn its limit, and a Bitcoin node's estimate above the ceiling is not paid.
        expr: fiatless_withdrawals_over_the_fee_limit{kind="payout"} > 0
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "Payouts on network {{ $labels.network }} wait unsigned: their network fee today is above what this deployment may sign."
          runbook: docs/runbooks/lane-backlog-alerts.md#payoutsoverthefeelimit

      - alert: PayoutNotOnChain
        # A payout the node keeps refusing stays broadcast with no case and no failing lane; this is its page.
        # An hour is a default; tune it to the slowest network's inclusion time.
        expr: fiatless_withdrawal_unlanded_seconds{kind="payout"} > 3600
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "A payout broadcast more than an hour ago is in no block on network {{ $labels.network }}."
          runbook: docs/runbooks/lane-backlog-alerts.md#payoutnotonchain

      - alert: OutboundReconciliationNeedsAnOperator
        # The lane could not decide what happened on chain and parked the case.
        # On EVM only its exact signed transaction landing closes it without a human.
        expr: fiatless_outbound_reconciliation_cases{status="operator_attention"} > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Outbound reconciliation cases are parked for human resolution."
          runbook: docs/runbooks/lane-backlog-alerts.md#outboundreconciliationneedsanoperator

      - alert: OutboundReconciliationNotResolving
        # Back-pressure spends no attempt, so a node that never answers keeps a case open instead of parking it.
        expr: sum(fiatless_outbound_reconciliation_cases{status=~"pending|retry|running"}) > 0
        for: 1h
        labels:
          severity: ticket
        annotations:
          summary: "Outbound reconciliation cases have stayed open for an hour; the node may not be answering."
          runbook: docs/runbooks/lane-backlog-alerts.md#outboundreconciliationnotresolving

      - alert: OutboundReorgCasesOpen
        expr: fiatless_outbound_reorg_cases{status="open"} > 0
        for: 15m
        labels:
          severity: page
        annotations:
          summary: "A confirmed outbound transaction was orphaned by a chain reorganisation."
          runbook: docs/runbooks/lane-backlog-alerts.md#outboundreorgcasesopen

      - alert: TreasuryNonceDrift
        # The node reports a treasury nonce pending that the gateway never allocated: a transaction its key signed
        # outside the gateway, or a provider's wrong answer. The network's payouts wait until a proof of it is below the
        # reorg depth (at once where the node keeps that state, else once an answer read at the confirmed block has
        # sunk there), and while the node cannot answer that read; a pending count the confirmed block shows stale holds
        # them too. The series is that pending count, except on the cursor path (a count at or below the gateway's next
        # nonce): there it is the account nonce the confirmed block shows above the next nonce, which holds the payouts
        # and the sweeps' gas top-ups, and a failed read there holds nothing unless an answer kept earlier shows that
        # nonce taken. A lower answer at a newer confirmed block retires a kept one, so a fixed provider ends the hold.
        expr: fiatless_evm_treasury_nonce_drift >= 0
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "Treasury nonce {{ $value }} on network {{ $labels.network }} (the node's pending count, or on the cursor path the confirmed block's account nonce) is not the gateway's; its payouts and gas top-ups wait."
          runbook: docs/runbooks/lane-backlog-alerts.md#treasurynoncedrift

      - alert: FailedPayoutLanded
        # A payout failed on a proof that none of its transactions could land, and one confirmed after all.
        expr: fiatless_treasury_incidents_unacknowledged{kind="failed_payout_landed"} > 0
        for: 1m
        labels:
          severity: page
        annotations:
          summary: "The treasury paid a payout the gateway had failed; the project's ledger still holds that money."
          runbook: docs/runbooks/lane-backlog-alerts.md#failedpayoutlanded

      - alert: TreasuryOutflowNotByTheGateway
        # Money left the treasury in a transaction the gateway did not make, or a coin a payout reserved was spent
        # elsewhere: its key signed outside the gateway. On Tron nothing else signals it.
        expr: max by (kind) (fiatless_treasury_incidents_unacknowledged{kind=~"outside_outflow|reserved_input_spent"}) > 0
        for: 1m
        labels:
          severity: page
        annotations:
          summary: "Money left a treasury in a transaction the gateway did not make ({{ $labels.kind }})."
          runbook: docs/runbooks/lane-backlog-alerts.md#treasuryincidentsunacknowledged

      - alert: TreasuryIncidentsUnacknowledged
        # Every other kind but the failed payout that landed, which pages above: settled as the chain charged, and
        # waiting for an operator to acknowledge it.
        expr: >-
          max by (kind) (fiatless_treasury_incidents_unacknowledged{
            kind!~"outside_outflow|reserved_input_spent|failed_payout_landed"}) > 0
        for: 30m
        labels:
          severity: ticket
        annotations:
          summary: "A treasury incident ({{ $labels.kind }}) waits for an operator to acknowledge it."
          runbook: docs/runbooks/lane-backlog-alerts.md#treasuryincidentsunacknowledged

      - alert: LaneItemSetAside
        # One payout, sweep, gas top-up, reconciliation case or history job failed the same way five times in a row.
        # Its lane moved on without it; nothing retries it until an operator returns it, or fails a payout for good.
        # A deposit key that derives another address is set aside at once and pages as DepositKeyDerivesAnotherAddress.
        expr: fiatless_lane_items_quarantined > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "A {{ $labels.lane }} item failed the same way five times in a row and waits for an operator."
          runbook: docs/runbooks/lane-backlog-alerts.md#laneitemsetaside

  - name: fiatless-consolidation
    rules:
      - alert: DepositsNotSwept
        # A confirmed deposit of an asset with a sweep policy that no sweep has confirmed since, nor the planner
        # found empty or below its minimum, or a Bitcoin deposit coin no consolidation took. Six hours is a default;
        # tune it to the deployment's policies and fee ceilings.
        expr: fiatless_deposit_unswept_seconds > 21600
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: "A deposit on network {{ $labels.network }} has waited 6 hours for a sweep."
          runbook: docs/runbooks/lane-backlog-alerts.md#depositsnotswept

      - alert: SweepsWaitingForNativeFunds
        # The project's native balance on the network cannot hold a queued sweep's fee ceiling. Sweeps wait unclaimed,
        # spending no attempt; the network's payouts hold their fees from the same balance.
        expr: fiatless_sweeps_waiting_for_native_funds > 0
        for: 15m
        labels:
          severity: page
        annotations:
          summary: "The project is short of native on network {{ $labels.network }}: {{ $value }} sweeps wait for their fee holds."
          runbook: docs/runbooks/lane-backlog-alerts.md#sweepswaitingfornativefunds

      - alert: SweepNotOnChain
        # A sweep or gas top-up the node keeps refusing stays broadcast; on EVM a gas top-up holds the treasury's
        # nonce, so its network's payouts queue behind it (WithdrawalsNotLeavingTheQueue).
        expr: fiatless_withdrawal_unlanded_seconds{kind=~"sweep|gas_top_up"} > 3600
        for: 5m
        labels:
          severity: ticket
        annotations:
          summary: "A {{ $labels.kind }} broadcast more than an hour ago is in no block on network {{ $labels.network }}."
          runbook: docs/runbooks/lane-backlog-alerts.md#sweepnotonchain

      - alert: DepositKeyDerivesAnotherAddress
        # Set aside at once, not after five failures: the seed or the recorded path is not the one that issued the
        # address, so nothing can sign for its money until that seed is back. Other wallets keep sweeping.
        expr: fiatless_deposit_keys_set_aside > 0
        for: 1m
        labels:
          severity: page
        annotations:
          summary: "A customer address on network {{ $labels.network }} has a key that derives another address; nothing sweeps it."
          runbook: docs/runbooks/lane-backlog-alerts.md#depositkeyderivesanotheraddress

      - alert: BitcoinConsolidationStalled
        expr: sum(fiatless_bitcoin_sweep_runs{status=~"queued|signing"}) > 0
        for: 2h
        labels:
          severity: ticket
        annotations:
          summary: "Bitcoin consolidation runs have not been broadcast in 2 hours."
          runbook: docs/runbooks/lane-backlog-alerts.md#bitcoinconsolidationstalled

      - alert: BitcoinConsolidationNotConfirming
        # The stalled rule above, extended to broadcast runs: those are resent and re-priced, so one still
        # in flight this long never confirms.
        expr: sum(fiatless_bitcoin_sweep_runs{status=~"queued|signing|broadcast"}) > 0
        for: 12h
        labels:
          severity: ticket
        annotations:
          summary: "A Bitcoin consolidation has been in flight for 12 hours without confirming."
          runbook: docs/runbooks/lane-backlog-alerts.md#bitcoinconsolidationstalled

  - name: fiatless-deposit-reconciliation
    rules:
      - alert: LedgerAboveChain
        # The ledger counts money a customer address does not hold. Nothing
        # moves by itself and there is no button: payouts could spend it.
        expr: fiatless_deposit_gap_incidents_open{kind="ledger_above_chain"} > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "The ledger counts more at a customer address than the chain holds."
          runbook: docs/runbooks/lane-backlog-alerts.md#ledgerabovechain

      - alert: DepositGapsOpen
        # Money on chain no decoded deposit accounts for. It is safe where it
        # is; an operator credits it to the customer, nothing does it alone.
        expr: fiatless_deposit_gap_incidents_open{kind="deposit_gap"} > 0
        for: 30m
        labels:
          severity: ticket
        annotations:
          summary: "A customer address holds money no decoded deposit accounts for."
          runbook: docs/runbooks/lane-backlog-alerts.md#depositgapsopen

      - alert: DepositReconciliationReadsFailing
        # A wallet the node keeps refusing is retried behind the others, so
        # the lane keeps succeeding while that wallet is never compared.
        expr: sum(fiatless_deposit_balance_read_failures) > 0
        for: 2h
        labels:
          severity: ticket
        annotations:
          summary: "Customer addresses have not been read on chain for two hours; a gap there goes unseen."
          runbook: docs/runbooks/lane-backlog-alerts.md#depositreconciliationreadsfailing

      - alert: UnrequestedArrivalsOpen
        # Money of an active asset arrived at a customer address that did not request it. Nothing credits it by
        # itself: an operator accepts it for the customer (the ledger never counting more there than the address still
        # holds) or dismisses it.
        expr: sum by (network, network_id) (fiatless_unrequested_arrivals_open) > 0
        for: 30m
        labels:
          severity: ticket
        annotations:
          summary: "A customer address on network {{ $labels.network }} received an asset it did not request."
          runbook: docs/runbooks/lane-backlog-alerts.md#unrequestedarrivalsopen

  - name: fiatless-kept-totals
    rules:
      - alert: KeptTotalDrifted
        # A total the payout gates, Home or the treasury page read is not the sum of its history: something wrote
        # past the schema's triggers. Every replica compares, so one series per table and network pages.
        expr: max by (kept, network, network_id) (fiatless_kept_totals_drifted) > 0
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "The kept {{ $labels.kept }} of network {{ $labels.network }} differs from the history it sums."
          runbook: docs/runbooks/lane-backlog-alerts.md#kepttotaldrifted

      - alert: KeptTotalsUnchecked
        # A pass runs every 15 minutes; one that cannot finish leaves a drift unseen. -1 is a replica that never
        # finished one.
        expr: fiatless_kept_totals_checked_seconds > 3600 or fiatless_kept_totals_checked_seconds < 0
        for: 30m
        labels:
          severity: ticket
        annotations:
          summary: "No pass has compared every kept total with its history for over an hour."
          runbook: docs/runbooks/lane-backlog-alerts.md#kepttotalsunchecked

  - name: fiatless-webhooks
    rules:
      - alert: OutboxNotDraining
        # Age, not count. A busy outbox is healthy; an old one is not.
        expr: fiatless_outbox_oldest_unpublished_seconds > 900
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "The oldest unpublished event is over 15 minutes old; integrators are not being called."
          runbook: docs/runbooks/lane-backlog-alerts.md#outboxnotdraining

      - alert: WebhookDeliveriesNotDraining
        # Fanned-out events wait here as deliveries, one per endpoint, and outsider dust adds one per payment. Age
        # past the attempt time: a delivery in backoff, out of attempts or to a disabled endpoint does not age.
        expr: fiatless_webhook_oldest_due_delivery_seconds > 900
        for: 10m
        labels:
          severity: page
        annotations:
          summary: "A webhook delivery has been due for over 15 minutes; integrators hear of payments and payouts late."
          runbook: docs/runbooks/lane-backlog-alerts.md#webhookdeliveriesnotdraining

      - alert: WebhookDeliveriesFailing
        # New failures only: a failed delivery stays failed after its replay, so the count never falls. It clears an
        # hour after the last new one; the right side reads 0 for a series an hour has not seen yet.
        expr: >-
          fiatless_webhook_deliveries{status="failed"}
            > (fiatless_webhook_deliveries{status="failed"} offset 1h or fiatless_webhook_deliveries{status="failed"} * 0)
        for: 5m
        labels:
          severity: ticket
        annotations:
          summary: "Webhook deliveries exhausted their attempts in the last hour."
          runbook: docs/runbooks/lane-backlog-alerts.md#webhookdeliveriesfailing
