|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""Tests for VGI_IDLE_EXIT_SECONDS: vgi-serve --http exits cleanly when idle.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import importlib.util |
| 8 | +import os |
| 9 | +import socket |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +import threading |
| 13 | +import time |
| 14 | +import urllib.request |
| 15 | +from collections.abc import Callable, Iterator |
| 16 | +from pathlib import Path |
| 17 | +from typing import Any |
| 18 | + |
| 19 | +import pytest |
| 20 | + |
| 21 | +from vgi import idle_exit |
| 22 | +from vgi.idle_exit import ( |
| 23 | + ActivityTracker, |
| 24 | + DirectoryActivity, |
| 25 | + IdleMiddleware, |
| 26 | + IdleWatcher, |
| 27 | + idle_exit_seconds, |
| 28 | + is_exempt, |
| 29 | +) |
| 30 | + |
| 31 | +# --------------------------------------------------------------------------- |
| 32 | +# Unit tests |
| 33 | +# --------------------------------------------------------------------------- |
| 34 | + |
| 35 | + |
| 36 | +class _Clock: |
| 37 | + def __init__(self) -> None: |
| 38 | + self.now = 100.0 |
| 39 | + |
| 40 | + def __call__(self) -> float: |
| 41 | + return self.now |
| 42 | + |
| 43 | + |
| 44 | +class TestIdleExitSeconds: |
| 45 | + """Parsing VGI_IDLE_EXIT_SECONDS.""" |
| 46 | + |
| 47 | + def test_unset_or_empty_is_off(self) -> None: |
| 48 | + """No variable (or an empty one) disables idle exit.""" |
| 49 | + assert idle_exit_seconds({}) is None |
| 50 | + assert idle_exit_seconds({"VGI_IDLE_EXIT_SECONDS": " "}) is None |
| 51 | + |
| 52 | + def test_number(self) -> None: |
| 53 | + """Integers and decimals are seconds.""" |
| 54 | + assert idle_exit_seconds({"VGI_IDLE_EXIT_SECONDS": "120"}) == 120.0 |
| 55 | + assert idle_exit_seconds({"VGI_IDLE_EXIT_SECONDS": "0.5"}) == 0.5 |
| 56 | + |
| 57 | + @pytest.mark.parametrize("raw", ["0", "-3", "abc", "nan", "inf"]) |
| 58 | + def test_rejects_non_positive_or_junk(self, raw: str) -> None: |
| 59 | + """Anything but a positive finite number is a configuration error.""" |
| 60 | + with pytest.raises(ValueError, match="VGI_IDLE_EXIT_SECONDS"): |
| 61 | + idle_exit_seconds({"VGI_IDLE_EXIT_SECONDS": raw}) |
| 62 | + |
| 63 | + |
| 64 | +class TestTracker: |
| 65 | + """In-flight counting and quiet time.""" |
| 66 | + |
| 67 | + def test_quiet_time_and_in_flight(self) -> None: |
| 68 | + """Quiet time runs from the last begin/end; a request in flight is never idle.""" |
| 69 | + clock = _Clock() |
| 70 | + t = ActivityTracker(clock=clock) |
| 71 | + clock.now += 10 |
| 72 | + assert t.idle_for() == 10 |
| 73 | + t.begin() |
| 74 | + clock.now += 1000 |
| 75 | + assert t.idle_for() is None |
| 76 | + t.end() |
| 77 | + clock.now += 3 |
| 78 | + assert t.idle_for() == 3 |
| 79 | + |
| 80 | + def test_concurrent_requests(self) -> None: |
| 81 | + """Idle only once every in-flight request has finished.""" |
| 82 | + clock = _Clock() |
| 83 | + t = ActivityTracker(clock=clock) |
| 84 | + t.begin() |
| 85 | + t.begin() |
| 86 | + t.end() |
| 87 | + assert t.idle_for() is None |
| 88 | + t.end() |
| 89 | + assert t.idle_for() == 0 |
| 90 | + t.end() # an extra end never goes negative |
| 91 | + t.begin() |
| 92 | + assert t.idle_for() is None |
| 93 | + |
| 94 | + def test_state_file(self, tmp_path: Path) -> None: |
| 95 | + """With a state file, the in-flight count is published for a parent.""" |
| 96 | + f = tmp_path / "123" |
| 97 | + t = ActivityTracker(state_file=str(f)) |
| 98 | + assert f.read_text() == "0" |
| 99 | + t.begin() |
| 100 | + assert f.read_text() == "1" |
| 101 | + t.end() |
| 102 | + assert f.read_text() == "0" |
| 103 | + |
| 104 | + |
| 105 | +def _start_response(status: str, headers: list[tuple[str, str]], exc_info: Any = None) -> Callable[[bytes], None]: |
| 106 | + return lambda _b: None |
| 107 | + |
| 108 | + |
| 109 | +class TestMiddleware: |
| 110 | + """The WSGI wrapper.""" |
| 111 | + |
| 112 | + def test_health_is_exempt(self) -> None: |
| 113 | + """/health (HEAD or GET, any prefix) does not count as activity.""" |
| 114 | + assert is_exempt({"PATH_INFO": "/health", "REQUEST_METHOD": "HEAD"}) |
| 115 | + assert is_exempt({"PATH_INFO": "/vgi/health", "REQUEST_METHOD": "GET"}) |
| 116 | + assert not is_exempt({"PATH_INFO": "/vgi.v3/catalog_attach", "REQUEST_METHOD": "POST"}) |
| 117 | + clock = _Clock() |
| 118 | + t = ActivityTracker(clock=clock) |
| 119 | + app = IdleMiddleware(lambda e, s: [b"ok"], t) |
| 120 | + clock.now += 50 |
| 121 | + app({"PATH_INFO": "/health", "REQUEST_METHOD": "HEAD"}, _start_response) |
| 122 | + assert t.idle_for() == 50 |
| 123 | + |
| 124 | + def test_in_flight_until_body_closed(self) -> None: |
| 125 | + """A request stays in flight until the server closes its response iterable.""" |
| 126 | + clock = _Clock() |
| 127 | + t = ActivityTracker(clock=clock) |
| 128 | + closed: list[bool] = [] |
| 129 | + |
| 130 | + class Body: |
| 131 | + def __iter__(self) -> Iterator[bytes]: |
| 132 | + yield b"a" |
| 133 | + yield b"b" |
| 134 | + |
| 135 | + def close(self) -> None: |
| 136 | + closed.append(True) |
| 137 | + |
| 138 | + app = IdleMiddleware(lambda e, s: Body(), t) |
| 139 | + body = app({"PATH_INFO": "/vgi.v3/x", "REQUEST_METHOD": "POST"}, _start_response) |
| 140 | + assert list(body) == [b"a", b"b"] |
| 141 | + assert t.idle_for() is None |
| 142 | + clock.now += 5 |
| 143 | + body.close() # type: ignore[attr-defined] |
| 144 | + body.close() # type: ignore[attr-defined] # idempotent |
| 145 | + assert closed == [True] |
| 146 | + assert t.idle_for() == 0 |
| 147 | + |
| 148 | + def test_app_raising_ends_the_request(self) -> None: |
| 149 | + """An application error doesn't leave the request counted as in flight.""" |
| 150 | + t = ActivityTracker() |
| 151 | + |
| 152 | + def boom(e: dict[str, Any], s: Any) -> list[bytes]: |
| 153 | + raise RuntimeError("boom") |
| 154 | + |
| 155 | + with pytest.raises(RuntimeError): |
| 156 | + IdleMiddleware(boom, t)({"PATH_INFO": "/x", "REQUEST_METHOD": "POST"}, _start_response) |
| 157 | + assert t.idle_for() is not None |
| 158 | + |
| 159 | + |
| 160 | +class TestDirectoryActivity: |
| 161 | + """The granian parent's view of its children.""" |
| 162 | + |
| 163 | + def test_aggregates_children(self, tmp_path: Path) -> None: |
| 164 | + """Busy if any live child has a request in flight; else quiet since the newest mtime.""" |
| 165 | + me = str(os.getpid()) |
| 166 | + view = DirectoryActivity(str(tmp_path), started=time.time() - 100) |
| 167 | + q = view.idle_for() |
| 168 | + assert q is not None and q >= 99 |
| 169 | + (tmp_path / me).write_text("1") |
| 170 | + assert view.idle_for() is None |
| 171 | + (tmp_path / me).write_text("0") |
| 172 | + q = view.idle_for() |
| 173 | + assert q is not None and q < 5 |
| 174 | + |
| 175 | + def test_ignores_dead_children(self, tmp_path: Path) -> None: |
| 176 | + """A crashed child's stale in-flight count does not keep the server up.""" |
| 177 | + proc = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True) |
| 178 | + dead = proc.stdout.strip() |
| 179 | + (tmp_path / dead).write_text("3") |
| 180 | + (tmp_path / "junk.tmp").write_text("9") |
| 181 | + assert DirectoryActivity(str(tmp_path), started=time.time() - 100).idle_for() is not None |
| 182 | + |
| 183 | + |
| 184 | +class TestWatcher: |
| 185 | + """The timer.""" |
| 186 | + |
| 187 | + def test_fires_once_when_quiet(self) -> None: |
| 188 | + """on_idle runs once the source has been quiet for the period.""" |
| 189 | + fired = threading.Event() |
| 190 | + t = ActivityTracker() |
| 191 | + w = IdleWatcher(t, 0.2, fired.set, poll=0.02) |
| 192 | + w.start() |
| 193 | + assert fired.wait(3) |
| 194 | + w.join(1) |
| 195 | + assert not w.is_alive() |
| 196 | + |
| 197 | + def test_activity_postpones(self) -> None: |
| 198 | + """Requests keep resetting the timer; stop() ends it without firing.""" |
| 199 | + fired = threading.Event() |
| 200 | + t = ActivityTracker() |
| 201 | + w = IdleWatcher(t, 0.3, fired.set, poll=0.02) |
| 202 | + w.start() |
| 203 | + for _ in range(10): |
| 204 | + t.begin() |
| 205 | + t.end() |
| 206 | + time.sleep(0.05) |
| 207 | + assert not fired.is_set() |
| 208 | + w.stop() |
| 209 | + w.join(1) |
| 210 | + assert not fired.is_set() |
| 211 | + |
| 212 | + def test_default_poll(self) -> None: |
| 213 | + """The poll interval is a quarter of the period, clamped to [50 ms, 5 s].""" |
| 214 | + t = ActivityTracker() |
| 215 | + assert IdleWatcher(t, 120, lambda: None).poll == 5.0 |
| 216 | + assert IdleWatcher(t, 2, lambda: None).poll == 0.5 |
| 217 | + assert IdleWatcher(t, 0.01, lambda: None).poll == 0.05 |
| 218 | + |
| 219 | + def test_state_directory(self) -> None: |
| 220 | + """The private directory is exported to children and removed afterwards.""" |
| 221 | + with idle_exit.state_directory() as d: |
| 222 | + assert os.environ[idle_exit.STATE_DIR_ENV] == d |
| 223 | + assert os.path.isdir(d) |
| 224 | + tracker = idle_exit.child_tracker() |
| 225 | + assert tracker is not None |
| 226 | + assert os.path.exists(os.path.join(d, str(os.getpid()))) |
| 227 | + assert idle_exit.STATE_DIR_ENV not in os.environ |
| 228 | + assert not os.path.exists(d) |
| 229 | + assert idle_exit.child_tracker() is None |
| 230 | + |
| 231 | + |
| 232 | +# --------------------------------------------------------------------------- |
| 233 | +# vgi-serve end to end |
| 234 | +# --------------------------------------------------------------------------- |
| 235 | + |
| 236 | + |
| 237 | +def _free_port() -> int: |
| 238 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 239 | + s.bind(("127.0.0.1", 0)) |
| 240 | + return int(s.getsockname()[1]) |
| 241 | + |
| 242 | + |
| 243 | +def _serve(port: int, idle: str, *extra: str) -> subprocess.Popen[str]: |
| 244 | + env = {**os.environ, "VGI_IDLE_EXIT_SECONDS": idle} |
| 245 | + env.pop("VGI_ORCHARD_HOSTED", None) |
| 246 | + proc = subprocess.Popen( |
| 247 | + [ |
| 248 | + sys.executable, |
| 249 | + "-m", |
| 250 | + "vgi.serve", |
| 251 | + "vgi._test_fixtures.worker:ExampleWorker", |
| 252 | + "--http", |
| 253 | + "--host", |
| 254 | + "127.0.0.1", |
| 255 | + "--port", |
| 256 | + str(port), |
| 257 | + *extra, |
| 258 | + ], |
| 259 | + stdout=subprocess.PIPE, |
| 260 | + stderr=subprocess.PIPE, |
| 261 | + text=True, |
| 262 | + env=env, |
| 263 | + ) |
| 264 | + assert proc.stdout is not None |
| 265 | + assert proc.stdout.readline().strip() == f"PORT:{port}" |
| 266 | + return proc |
| 267 | + |
| 268 | + |
| 269 | +def _get(port: int, path: str, method: str = "GET") -> int: |
| 270 | + deadline = time.monotonic() + 10 |
| 271 | + while True: |
| 272 | + try: |
| 273 | + req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method) |
| 274 | + with urllib.request.urlopen(req, timeout=5) as resp: |
| 275 | + resp.read() |
| 276 | + return int(resp.status) |
| 277 | + except urllib.error.HTTPError as e: |
| 278 | + return int(e.code) |
| 279 | + except OSError: |
| 280 | + if time.monotonic() > deadline: |
| 281 | + raise |
| 282 | + time.sleep(0.1) |
| 283 | + |
| 284 | + |
| 285 | +_SERVERS = [ |
| 286 | + pytest.param((), id="waitress"), |
| 287 | + pytest.param( |
| 288 | + ("--server", "granian", "--http-workers", "2"), |
| 289 | + id="granian", |
| 290 | + marks=pytest.mark.skipif(importlib.util.find_spec("granian") is None, reason="granian extra not installed"), |
| 291 | + ), |
| 292 | +] |
| 293 | + |
| 294 | + |
| 295 | +@pytest.mark.parametrize("extra", _SERVERS) |
| 296 | +def test_serve_exits_cleanly_when_idle(extra: tuple[str, ...]) -> None: |
| 297 | + """Requests keep the server up; health checks don't; quiet for the period exits 0.""" |
| 298 | + port = _free_port() |
| 299 | + proc = _serve(port, "2", *extra) |
| 300 | + try: |
| 301 | + _get(port, "/") |
| 302 | + # Busy for well over the period: still serving. |
| 303 | + end = time.monotonic() + 4 |
| 304 | + while time.monotonic() < end: |
| 305 | + assert _get(port, "/?format=json") == 200 |
| 306 | + time.sleep(0.3) |
| 307 | + assert proc.poll() is None |
| 308 | + # Health checks only: they must not keep it alive. |
| 309 | + started = time.monotonic() |
| 310 | + while proc.poll() is None and time.monotonic() - started < 15: |
| 311 | + try: |
| 312 | + _get(port, "/health", method="HEAD") |
| 313 | + except OSError: |
| 314 | + break |
| 315 | + time.sleep(0.3) |
| 316 | + code = proc.wait(timeout=15) |
| 317 | + quiet = time.monotonic() - started |
| 318 | + assert code == 0, proc.stderr.read() if proc.stderr else "" |
| 319 | + assert 1.5 <= quiet <= 12 |
| 320 | + finally: |
| 321 | + if proc.poll() is None: |
| 322 | + proc.kill() |
| 323 | + proc.wait(timeout=5) |
| 324 | + |
| 325 | + |
| 326 | +def test_serve_rejects_bad_idle_value() -> None: |
| 327 | + """A malformed VGI_IDLE_EXIT_SECONDS stops startup with a message.""" |
| 328 | + env = {**os.environ, "VGI_IDLE_EXIT_SECONDS": "soon"} |
| 329 | + env.pop("VGI_ORCHARD_HOSTED", None) |
| 330 | + result = subprocess.run( |
| 331 | + [sys.executable, "-m", "vgi.serve", "vgi._test_fixtures.worker:ExampleWorker", "--http", "--port", "0"], |
| 332 | + capture_output=True, |
| 333 | + text=True, |
| 334 | + timeout=60, |
| 335 | + env=env, |
| 336 | + ) |
| 337 | + assert result.returncode != 0 |
| 338 | + assert "VGI_IDLE_EXIT_SECONDS" in result.stderr |
0 commit comments