File size: 5,636 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""Exercise supervised shutdown with real HTTP event-feed connections."""

import asyncio
import socket
import threading
from pathlib import Path

import httpx
import pytest

from free_claude_code.cli import commands
from free_claude_code.config.settings import Settings
from free_claude_code.runtime.application import RestartCallback
from free_claude_code.runtime.asgi import RuntimeASGIApp
from free_claude_code.runtime.bootstrap import build_asgi_app


@pytest.mark.asyncio
@pytest.mark.parametrize("restart", [False, True])
async def test_supervisor_drains_admin_event_feed_without_forced_cancellation(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
    caplog: pytest.LogCaptureFixture,
    restart: bool,
) -> None:
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        port = listener.getsockname()[1]
    settings = Settings().model_copy(
        update={
            "host": "127.0.0.1",
            "port": port,
            "messaging_platform": "none",
            "voice_note_enabled": False,
            "open_admin_browser": False,
            "log_file": str(tmp_path / "server.log"),
        }
    )
    apps: list[RuntimeASGIApp] = []

    def create_app(settings: Settings, *, restart_callback: RestartCallback):
        app = build_asgi_app(settings, restart_callback=restart_callback)
        # Only provider discovery is external; retain the real Code, HTTP,
        # runtime cleanup, and supervisor lifecycle under investigation.
        monkeypatch.setattr(
            app.runtime.provider_manager, "start_model_list_refresh", lambda: None
        )
        apps.append(app)
        return app

    monkeypatch.setattr(commands, "load_server_settings", lambda: settings)
    monkeypatch.setattr(
        "free_claude_code.runtime.bootstrap.configure_logging",
        lambda *args, **kwargs: None,
    )
    monkeypatch.setattr("free_claude_code.runtime.bootstrap.build_asgi_app", create_app)
    monkeypatch.setattr(commands, "kill_all_best_effort", lambda: None)
    monkeypatch.setattr(commands, "SERVER_GRACEFUL_SHUTDOWN_SECONDS", 0.2)
    supervisor = commands.ServerSupervisor(console_logging=False)
    thread = threading.Thread(target=supervisor.run, daemon=True)
    thread.start()
    stream_error: Exception | None = None
    try:
        async with asyncio.timeout(5):
            while supervisor.status != commands.ServerStatus.RUNNING:
                assert thread.is_alive()
                await asyncio.sleep(0.01)
        async with httpx.AsyncClient(timeout=3, trust_env=False) as client:
            status_url = f"http://127.0.0.1:{port}/admin/api/status"
            old_instance = (await client.get(status_url)).json()["instance_id"]
            # HTTP startup precedes background Code storage initialization.
            bootstrap_url = f"http://127.0.0.1:{port}/admin/api/code/bootstrap"
            async with asyncio.timeout(30):
                while True:
                    response = await client.get(bootstrap_url)
                    assert response.status_code == 200, response.text
                    storage = response.json()["storage"]
                    if storage["state"] == "ready":
                        break
                    assert storage["state"] == "starting", storage
                    assert thread.is_alive()
                    await asyncio.sleep(0.01)
            events_url = f"http://127.0.0.1:{port}/admin/api/code/events"
            async with (
                client.stream("GET", events_url) as first,
                client.stream("GET", events_url) as second,
            ):
                streams = [first.aiter_lines(), second.aiter_lines()]
                assert first.status_code == second.status_code == 200
                for lines in streams:
                    async for line in lines:
                        if line.startswith("event: feed.ready"):
                            break
                if restart:
                    assert supervisor.request_restart()
                else:
                    supervisor.request_stop()
                for lines in streams:
                    try:
                        async for _line in lines:
                            pass
                    except httpx.HTTPError as exc:
                        stream_error = exc
            if restart:
                async with asyncio.timeout(5):
                    while (
                        len(apps) < 2
                        or supervisor.status != commands.ServerStatus.RUNNING
                    ):
                        assert thread.is_alive()
                        await asyncio.sleep(0.01)
                new_status = (await client.get(status_url)).json()
                assert new_status["status"] == "running"
                assert new_status["instance_id"] != old_instance
    finally:
        supervisor.request_stop()
        await asyncio.to_thread(thread.join, 5)
    assert not thread.is_alive()
    assert stream_error is None, f"Event feed was cut off: {stream_error}"
    assert "timeout graceful shutdown exceeded" not in caplog.text
    assert all(app.runtime.is_closed for app in apps)
    assert len(apps) == (2 if restart else 1)
    starts = [
        extra
        for record in caplog.records
        if (extra := getattr(record, "extra", {})).get("event") == "server.starting"
    ]
    assert [extra["instance_id"] for extra in starts] == [
        app.runtime.instance_id for app in apps
    ]
    assert starts[0]["instance_id"] == old_instance
    if restart:
        assert starts[1]["instance_id"] == new_status["instance_id"]