"""Tests for memory watermark pressure backoff in gap-backfill.

Note: _adaptive_sleep and _MEGA_GAP_SECONDS were removed as part of the
Stathera-only migration (all gap detection via trade-ID continuity in kintsugi).
"""

from __future__ import annotations

from unittest.mock import patch

from opendeviationbar.backfill import (
    _WATERMARK_ABORT_RATIO,
    _WATERMARK_GC_RATIO,
    _check_memory_watermark,
)


class TestCheckMemoryWatermark:
    """Test _check_memory_watermark pressure tiers."""

    def test_ok_when_below_gc_threshold(self) -> None:
        """RSS at 50% of ceiling → ok."""
        with patch(
            "opendeviationbar.resource_guard._get_process_rss_mb", return_value=500
        ):
            result = _check_memory_watermark(1024 * 1024 * 1024)  # 1 GB
            assert result == "ok"

    def test_gc_when_above_gc_threshold(self) -> None:
        """RSS at 70% of ceiling → gc."""
        ceiling = 1000 * 1024 * 1024  # 1000 MB
        rss_mb = int(ceiling * 0.70 / (1024 * 1024))
        with patch(
            "opendeviationbar.resource_guard._get_process_rss_mb", return_value=rss_mb
        ):
            result = _check_memory_watermark(ceiling)
            assert result == "gc"

    def test_abort_when_above_abort_threshold(self) -> None:
        """RSS at 95% of ceiling → abort."""
        ceiling = 1000 * 1024 * 1024  # 1000 MB
        rss_mb = int(ceiling * 0.95 / (1024 * 1024))
        with patch(
            "opendeviationbar.resource_guard._get_process_rss_mb", return_value=rss_mb
        ):
            result = _check_memory_watermark(ceiling)
            assert result == "abort"

    def test_zero_ceiling_returns_ok(self) -> None:
        """memory_max_bytes=0 → ok (avoid division by zero)."""
        with patch(
            "opendeviationbar.resource_guard._get_process_rss_mb", return_value=100
        ):
            assert _check_memory_watermark(0) == "ok"

    def test_watermark_constants(self) -> None:
        """Verify named constants match expected values."""
        assert _WATERMARK_GC_RATIO == 0.65
        assert _WATERMARK_ABORT_RATIO == 0.90
