.FF.F.F                                                                  [100%]
=================================== FAILURES ===================================
__________________ test_polling_conflict_retries_before_fatal __________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x78e6d9b955b0>

    @pytest.mark.asyncio
    async def test_polling_conflict_retries_before_fatal(monkeypatch):
        """A single 409 should trigger a retry, not an immediate fatal error."""
        adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
        fatal_handler = AsyncMock()
        adapter.set_fatal_error_handler(fatal_handler)
    
        monkeypatch.setattr(
            "gateway.status.acquire_scoped_lock",
            lambda scope, identity, metadata=None: (True, None),
        )
        monkeypatch.setattr(
            "gateway.status.release_scoped_lock",
            lambda scope, identity: None,
        )
    
        captured = {}
    
        async def fake_start_polling(**kwargs):
            captured["error_callback"] = kwargs["error_callback"]
    
        updater = SimpleNamespace(
            start_polling=AsyncMock(side_effect=fake_start_polling),
            stop=AsyncMock(),
            running=True,
        )
        bot = SimpleNamespace(set_my_commands=AsyncMock(), delete_webhook=AsyncMock())
        app = SimpleNamespace(
            bot=bot,
            updater=updater,
            add_handler=MagicMock(),
            initialize=AsyncMock(),
            start=AsyncMock(),
        )
        builder = MagicMock()
        builder.token.return_value = builder
        builder.request.return_value = builder
        builder.get_updates_request.return_value = builder
        builder.build.return_value = app
        monkeypatch.setattr("gateway.platforms.telegram.Application", SimpleNamespace(builder=MagicMock(return_value=builder)))
    
        # Speed up retries for testing
        monkeypatch.setattr("asyncio.sleep", AsyncMock())
    
        ok = await adapter.connect()
    
>       assert ok is True
E       assert False is True

tests/gateway/test_telegram_conflict.py:113: AssertionError
------------------------------ Captured log call -------------------------------
ERROR    gateway.platforms.telegram:telegram.py:3225 [Telegram] Failed to connect to Telegram: diagnostic production bot identity is not authenticated
Traceback (most recent call last):
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 3047, in _connect_network
    _pin_diagnostic_production_identity(self, self._bot)
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 283, in _pin_diagnostic_production_identity
    raise RuntimeError("diagnostic production bot identity is not authenticated")
RuntimeError: diagnostic production bot identity is not authenticated
______________ test_polling_conflict_becomes_fatal_after_retries _______________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x78e6d9b8ff50>

    @pytest.mark.asyncio
    async def test_polling_conflict_becomes_fatal_after_retries(monkeypatch):
        """After exhausting retries, the conflict should become fatal."""
        adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
        fatal_handler = AsyncMock()
        adapter.set_fatal_error_handler(fatal_handler)
    
        monkeypatch.setattr(
            "gateway.status.acquire_scoped_lock",
            lambda scope, identity, metadata=None: (True, None),
        )
        monkeypatch.setattr(
            "gateway.status.release_scoped_lock",
            lambda scope, identity: None,
        )
    
        captured = {}
    
        async def fake_start_polling(**kwargs):
            captured["error_callback"] = kwargs["error_callback"]
    
        # Make start_polling fail on retries to exhaust retries
        call_count = {"n": 0}
    
        async def failing_start_polling(**kwargs):
            call_count["n"] += 1
            if call_count["n"] == 1:
                # First call (initial connect) succeeds
                captured["error_callback"] = kwargs["error_callback"]
            else:
                # Retry calls fail
                raise Exception("Connection refused")
    
        updater = SimpleNamespace(
            start_polling=AsyncMock(side_effect=failing_start_polling),
            stop=AsyncMock(),
            running=True,
        )
        bot = SimpleNamespace(set_my_commands=AsyncMock(), delete_webhook=AsyncMock())
        app = SimpleNamespace(
            bot=bot,
            updater=updater,
            add_handler=MagicMock(),
            initialize=AsyncMock(),
            start=AsyncMock(),
        )
        builder = MagicMock()
        builder.token.return_value = builder
        builder.request.return_value = builder
        builder.get_updates_request.return_value = builder
        builder.build.return_value = app
        monkeypatch.setattr("gateway.platforms.telegram.Application", SimpleNamespace(builder=MagicMock(return_value=builder)))
    
        # Speed up retries for testing
        monkeypatch.setattr("asyncio.sleep", AsyncMock())
    
        ok = await adapter.connect()
>       assert ok is True
E       assert False is True

tests/gateway/test_telegram_conflict.py:188: AssertionError
------------------------------ Captured log call -------------------------------
ERROR    gateway.platforms.telegram:telegram.py:3225 [Telegram] Failed to connect to Telegram: diagnostic production bot identity is not authenticated
Traceback (most recent call last):
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 3047, in _connect_network
    _pin_diagnostic_production_identity(self, self._bot)
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 283, in _pin_diagnostic_production_identity
    raise RuntimeError("diagnostic production bot identity is not authenticated")
RuntimeError: diagnostic production bot identity is not authenticated
__________________ test_connect_clears_webhook_before_polling __________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x78e6d9bb5700>

    @pytest.mark.asyncio
    async def test_connect_clears_webhook_before_polling(monkeypatch):
        adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
    
        monkeypatch.setattr(
            "gateway.status.acquire_scoped_lock",
            lambda scope, identity, metadata=None: (True, None),
        )
        monkeypatch.setattr(
            "gateway.status.release_scoped_lock",
            lambda scope, identity: None,
        )
    
        updater = SimpleNamespace(
            start_polling=AsyncMock(),
            stop=AsyncMock(),
            running=True,
        )
        bot = SimpleNamespace(
            delete_webhook=AsyncMock(),
            set_my_commands=AsyncMock(),
        )
        app = SimpleNamespace(
            bot=bot,
            updater=updater,
            add_handler=MagicMock(),
            initialize=AsyncMock(),
            start=AsyncMock(),
        )
        builder = MagicMock()
        builder.token.return_value = builder
        builder.request.return_value = builder
        builder.get_updates_request.return_value = builder
        builder.build.return_value = app
        monkeypatch.setattr(
            "gateway.platforms.telegram.Application",
            SimpleNamespace(builder=MagicMock(return_value=builder)),
        )
    
        ok = await adapter.connect()
    
>       assert ok is True
E       assert False is True

tests/gateway/test_telegram_conflict.py:286: AssertionError
------------------------------ Captured log call -------------------------------
ERROR    gateway.platforms.telegram:telegram.py:3225 [Telegram] Failed to connect to Telegram: diagnostic production bot identity is not authenticated
Traceback (most recent call last):
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 3047, in _connect_network
    _pin_diagnostic_production_identity(self, self._bot)
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 283, in _pin_diagnostic_production_identity
    raise RuntimeError("diagnostic production bot identity is not authenticated")
RuntimeError: diagnostic production bot identity is not authenticated
______________ test_polling_conflict_reschedule_uses_running_loop ______________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x78e6d9416c30>

    @pytest.mark.asyncio
    async def test_polling_conflict_reschedule_uses_running_loop(monkeypatch):
        """Regression for #19471.
    
        When a conflict-retry's start_polling raises and we are still below the
        retry ceiling, the handler reschedules itself via loop.create_task. The
        old code used the deprecated asyncio.get_event_loop(), which raises
        "RuntimeError: There is no current event loop in thread 'MainThread'" on
        Python 3.11+ when no loop is attached to the thread (as happens when PTB
        dispatches this error callback). That left the gateway alive but silent
        and drove the --replace crash loop. The fix uses get_running_loop(), which
        is always valid inside a coroutine. Force get_event_loop() to raise so a
        regression would surface as the original RuntimeError, not pass silently.
        """
        adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
        adapter.set_fatal_error_handler(AsyncMock())
    
        monkeypatch.setattr(
            "gateway.status.acquire_scoped_lock",
            lambda scope, identity, metadata=None: (True, None),
        )
        monkeypatch.setattr(
            "gateway.status.release_scoped_lock",
            lambda scope, identity: None,
        )
    
        captured = {}
        call_count = {"n": 0}
    
        async def failing_start_polling(**kwargs):
            call_count["n"] += 1
            if call_count["n"] == 1:
                captured["error_callback"] = kwargs["error_callback"]
            else:
                # Retry attempt fails so the handler enters the reschedule branch.
                raise Exception("Connection refused")
    
        updater = SimpleNamespace(
            start_polling=AsyncMock(side_effect=failing_start_polling),
            stop=AsyncMock(),
            running=True,
        )
        bot = SimpleNamespace(set_my_commands=AsyncMock(), delete_webhook=AsyncMock())
        app = SimpleNamespace(
            bot=bot,
            updater=updater,
            add_handler=MagicMock(),
            initialize=AsyncMock(),
            start=AsyncMock(),
        )
        builder = MagicMock()
        builder.token.return_value = builder
        builder.request.return_value = builder
        builder.get_updates_request.return_value = builder
        builder.build.return_value = app
        monkeypatch.setattr(
            "gateway.platforms.telegram.Application",
            SimpleNamespace(builder=MagicMock(return_value=builder)),
        )
        monkeypatch.setattr("asyncio.sleep", AsyncMock())
    
        ok = await adapter.connect()
>       assert ok is True
E       assert False is True

tests/gateway/test_telegram_conflict.py:376: AssertionError
------------------------------ Captured log call -------------------------------
ERROR    gateway.platforms.telegram:telegram.py:3225 [Telegram] Failed to connect to Telegram: diagnostic production bot identity is not authenticated
Traceback (most recent call last):
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 3047, in _connect_network
    _pin_diagnostic_production_identity(self, self._bot)
  File "/home/cube/projects/richard/.worktrees/nutricoach-v111-impl/gateway/platforms/telegram.py", line 283, in _pin_diagnostic_production_identity
    raise RuntimeError("diagnostic production bot identity is not authenticated")
RuntimeError: diagnostic production bot identity is not authenticated
=========================== short test summary info ============================
FAILED tests/gateway/test_telegram_conflict.py::test_polling_conflict_retries_before_fatal
FAILED tests/gateway/test_telegram_conflict.py::test_polling_conflict_becomes_fatal_after_retries
FAILED tests/gateway/test_telegram_conflict.py::test_connect_clears_webhook_before_polling
FAILED tests/gateway/test_telegram_conflict.py::test_polling_conflict_reschedule_uses_running_loop
4 failed, 3 passed in 0.65s
