askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_object_sandbox_worker_log.py · 9.4 KB · 254 lines
| 1 | """A warm or spare user-code worker that dies says why, once per cause. |
| 2 | |
| 3 | The fork server once died at every start (its own RLIMIT_AS was below what a |
| 4 | free-threaded interpreter had already reserved); every call quietly took the |
| 5 | single-use path for days and nothing was logged. These tests pin the log |
| 6 | line, the rate limit, and that the fallback still answers the call. |
| 7 | """ |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import logging |
| 11 | import signal |
| 12 | import time |
| 13 | |
| 14 | import pytest |
| 15 | |
| 16 | import object_sandbox |
| 17 | from runtime_modes import configure, run_object, write_object |
| 18 | from sandbox_signals import signal_worker |
| 19 | |
| 20 | LOGGER = "dbbasic.object_sandbox" |
| 21 | SECRET = "s3cret-marker-in-the-source" |
| 22 | SOURCE = f""" |
| 23 | def GET(request): |
| 24 | return {{"ok": True, "note": "{SECRET}"}} |
| 25 | """ |
| 26 | |
| 27 | |
| 28 | @pytest.fixture(autouse=True) |
| 29 | def _clean(): |
| 30 | object_sandbox.shutdown() |
| 31 | object_sandbox._WORKER_LOG.reset() |
| 32 | yield |
| 33 | object_sandbox.shutdown() |
| 34 | object_sandbox._WORKER_LOG.reset() |
| 35 | |
| 36 | |
| 37 | @pytest.fixture |
| 38 | def unsafe_dev(monkeypatch): |
| 39 | monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV) |
| 40 | monkeypatch.delenv(object_sandbox.MEMORY_MB_ENV, raising=False) |
| 41 | |
| 42 | |
| 43 | def _lines(caplog): |
| 44 | return [r.getMessage() for r in caplog.records if r.name == LOGGER and r.levelno == logging.WARNING] |
| 45 | |
| 46 | |
| 47 | def _wait_for(caplog, text, seconds=10.0): |
| 48 | deadline = time.monotonic() + seconds |
| 49 | while time.monotonic() < deadline: |
| 50 | found = [line for line in _lines(caplog) if text in line] |
| 51 | if found: |
| 52 | return found |
| 53 | time.sleep(0.02) |
| 54 | pytest.fail(f"no warning containing {text!r}; got {_lines(caplog)}") |
| 55 | |
| 56 | |
| 57 | # -- the rate limit (every platform) --------------------------------------- |
| 58 | |
| 59 | |
| 60 | class _Clock: |
| 61 | def __init__(self): |
| 62 | self.now = 1000.0 |
| 63 | |
| 64 | def __call__(self): |
| 65 | return self.now |
| 66 | |
| 67 | |
| 68 | def test_first_occurrence_is_logged_then_one_line_a_minute_with_a_count(): |
| 69 | said = [] |
| 70 | clock = _Clock() |
| 71 | log = object_sandbox._RateLimitedLog(emit=said.append, interval=60.0, clock=clock) |
| 72 | |
| 73 | assert log.warn("fork server|exited", "fork server died") is True |
| 74 | for _ in range(500): # a crash loop |
| 75 | clock.now += 0.1 |
| 76 | assert log.warn("fork server|exited", "fork server died") is False |
| 77 | assert said == ["fork server died"] |
| 78 | |
| 79 | clock.now += 60.0 |
| 80 | assert log.warn("fork server|exited", "fork server died") is True |
| 81 | assert len(said) == 2 |
| 82 | assert "500 more like this" in said[1] |
| 83 | |
| 84 | # A quiet minute: the next one is said plainly, with no count. |
| 85 | clock.now += 61.0 |
| 86 | assert log.warn("fork server|exited", "fork server died") is True |
| 87 | assert said[2] == "fork server died" |
| 88 | |
| 89 | |
| 90 | def test_each_cause_has_its_own_limit_and_the_number_of_causes_is_bounded(): |
| 91 | said = [] |
| 92 | clock = _Clock() |
| 93 | log = object_sandbox._RateLimitedLog(emit=said.append, interval=60.0, clock=clock) |
| 94 | assert log.warn("a", "first a") |
| 95 | assert log.warn("b", "first b") |
| 96 | assert not log.warn("a", "again a") |
| 97 | assert said == ["first a", "first b"] |
| 98 | |
| 99 | for n in range(object_sandbox._MAX_LOG_CAUSES * 3): |
| 100 | log.warn(f"cause-{n}", f"line {n}") |
| 101 | assert len(log._seen) <= object_sandbox._MAX_LOG_CAUSES + 1 |
| 102 | assert len(said) <= object_sandbox._MAX_LOG_CAUSES + 1 |
| 103 | |
| 104 | |
| 105 | def test_the_hint_names_the_memory_limit_only_when_the_death_looks_like_it(): |
| 106 | hint = object_sandbox._death_hint |
| 107 | env = object_sandbox.MEMORY_MB_ENV |
| 108 | # MemoryError in the boot error or the stderr tail |
| 109 | assert env in hint(3, 30.0, False, "MemoryError: cannot allocate") |
| 110 | # SIGKILL or SIGSEGV soon after start |
| 111 | assert env in hint(-signal.SIGKILL, 0.4, True) |
| 112 | assert env in hint(-signal.SIGSEGV, 2.0, True) |
| 113 | # a failed exit within the first second, before it was ready |
| 114 | assert env in hint(3, 0.2, False) |
| 115 | # none of those |
| 116 | assert hint(-signal.SIGKILL, 600.0, True) == "" |
| 117 | assert hint(-signal.SIGTERM, 0.1, True) == "" |
| 118 | assert hint(1, 0.2, True) == "" # it was ready: user code ended it |
| 119 | assert hint(0, 0.2, False) == "" |
| 120 | assert hint(None, None, False) == "" |
| 121 | |
| 122 | |
| 123 | def test_the_line_says_which_worker_how_it_ended_and_its_limit(): |
| 124 | said = [] |
| 125 | log = object_sandbox._RateLimitedLog(emit=said.append) |
| 126 | |
| 127 | class Dead: |
| 128 | pid = 4321 |
| 129 | memory_limit = 512 * 1024 * 1024 |
| 130 | started = time.monotonic() |
| 131 | ready = True |
| 132 | |
| 133 | original = object_sandbox._WORKER_LOG |
| 134 | object_sandbox._WORKER_LOG = log |
| 135 | try: |
| 136 | object_sandbox._log_worker_death("fork server", Dead(), "stopped answering", status=-signal.SIGKILL) |
| 137 | object_sandbox._log_worker_death("spare worker", None, "failed to start", |
| 138 | detail="OSError: no launcher", config={"limits": {"as": 64 * 1024 * 1024}}) |
| 139 | finally: |
| 140 | object_sandbox._WORKER_LOG = original |
| 141 | assert "fork server (pid 4321) stopped answering: killed by SIGKILL" in said[0] |
| 142 | assert "memory limit 512 MiB" in said[0] |
| 143 | assert object_sandbox.MEMORY_MB_ENV in said[0] |
| 144 | assert "spare worker failed to start: exit status unknown, memory limit 64 MiB (OSError: no launcher)" in said[1] |
| 145 | |
| 146 | |
| 147 | # -- real workers ----------------------------------------------------------- |
| 148 | |
| 149 | |
| 150 | def test_a_fork_server_that_cannot_start_is_logged_and_the_call_still_answers( |
| 151 | tmp_path, monkeypatch, unsafe_dev, caplog): |
| 152 | _data, root = configure(monkeypatch, tmp_path) |
| 153 | write_object(root, "u_7_hello", SOURCE) |
| 154 | if not object_sandbox._FORK_SERVERS.supported(object_sandbox._boot_config()): |
| 155 | pytest.skip("warm parents are not used on this platform") |
| 156 | |
| 157 | def refuse(self, deadline): |
| 158 | raise object_sandbox._BootRefused("MemoryError: ") |
| 159 | |
| 160 | monkeypatch.setattr(object_sandbox._ForkServer, "wait_ready", refuse) |
| 161 | caplog.set_level(logging.WARNING, logger=LOGGER) |
| 162 | |
| 163 | for _ in range(3): |
| 164 | result = run_object("in_process", root, "u_7_hello") |
| 165 | assert result.ok, result.error |
| 166 | assert result.result["ok"] is True |
| 167 | |
| 168 | died = _wait_for(caplog, "fork server") |
| 169 | assert "failed to start" in died[0] |
| 170 | assert "memory limit 512 MiB" in died[0] |
| 171 | assert object_sandbox.MEMORY_MB_ENV in died[0] # the hint: its boot said MemoryError |
| 172 | assert _wait_for(caplog, "single-use path") |
| 173 | # Once per cause, however many calls follow inside the minute. |
| 174 | for _ in range(3): |
| 175 | assert run_object("in_process", root, "u_7_hello").ok |
| 176 | time.sleep(0.2) |
| 177 | lines = _lines(caplog) |
| 178 | assert len([line for line in lines if line.startswith("user-code fork server")]) == 1 |
| 179 | assert len([line for line in lines if "single-use path" in line]) == 1 |
| 180 | for line in lines: |
| 181 | assert SECRET not in line and "u_7" not in line and str(root) not in line |
| 182 | |
| 183 | |
| 184 | def test_a_killed_fork_server_is_logged_and_the_call_falls_back(tmp_path, monkeypatch, unsafe_dev, caplog): |
| 185 | _data, root = configure(monkeypatch, tmp_path) |
| 186 | write_object(root, "u_7_hello", SOURCE) |
| 187 | if not object_sandbox._FORK_SERVERS.supported(object_sandbox._boot_config()): |
| 188 | pytest.skip("warm parents are not used on this platform") |
| 189 | caplog.set_level(logging.WARNING, logger=LOGGER) |
| 190 | |
| 191 | deadline = time.monotonic() + 15 |
| 192 | pid = None |
| 193 | while pid is None and time.monotonic() < deadline: |
| 194 | assert run_object("in_process", root, "u_7_hello").ok |
| 195 | server = object_sandbox._FORK_SERVERS._servers.get("7") |
| 196 | pid = server.worker.pid if server is not None else None |
| 197 | time.sleep(0.05) |
| 198 | if pid is None: |
| 199 | pytest.fail("no fork server started") |
| 200 | assert _lines(caplog) == [] |
| 201 | |
| 202 | signal_worker(pid) |
| 203 | time.sleep(0.2) |
| 204 | result = run_object("in_process", root, "u_7_hello") |
| 205 | assert result.ok, result.error # the single-use path answered |
| 206 | |
| 207 | died = _wait_for(caplog, "fork server") |
| 208 | assert f"(pid {pid})" in died[0] |
| 209 | assert "killed by SIGKILL" in died[0] |
| 210 | assert "memory limit 512 MiB" in died[0] |
| 211 | assert object_sandbox.MEMORY_MB_ENV in died[0] # SIGKILL soon after start |
| 212 | assert _wait_for(caplog, "single-use path") |
| 213 | for line in _lines(caplog): |
| 214 | assert SECRET not in line and "u_7" not in line and str(root) not in line |
| 215 | |
| 216 | |
| 217 | def test_a_spare_that_died_waiting_is_logged_and_replaced(tmp_path, monkeypatch, unsafe_dev, caplog): |
| 218 | _data, root = configure(monkeypatch, tmp_path) |
| 219 | write_object(root, "u_7_hello", SOURCE) |
| 220 | monkeypatch.setenv(object_sandbox.WARM_USERS_ENV, "0") # spares only |
| 221 | caplog.set_level(logging.WARNING, logger=LOGGER) |
| 222 | |
| 223 | assert run_object("in_process", root, "u_7_hello").ok |
| 224 | deadline = time.monotonic() + 10 |
| 225 | while not object_sandbox._POOL._idle and time.monotonic() < deadline: |
| 226 | time.sleep(0.02) |
| 227 | spares = list(object_sandbox._POOL._idle) |
| 228 | if not spares: |
| 229 | pytest.skip("no spares are kept in this configuration") |
| 230 | for spare in spares: |
| 231 | signal_worker(spare.pid) |
| 232 | time.sleep(0.2) |
| 233 | |
| 234 | result = run_object("in_process", root, "u_7_hello") |
| 235 | assert result.ok, result.error |
| 236 | died = _wait_for(caplog, "spare worker") |
| 237 | assert "exited: killed by SIGKILL" in died[0] |
| 238 | assert "memory limit 512 MiB" in died[0] |
| 239 | |
| 240 | |
| 241 | def test_a_worker_that_cannot_be_started_is_logged(tmp_path, monkeypatch, unsafe_dev, caplog): |
| 242 | _data, root = configure(monkeypatch, tmp_path) |
| 243 | write_object(root, "u_7_hello", SOURCE) |
| 244 | monkeypatch.setenv(object_sandbox.WARM_USERS_ENV, "0") |
| 245 | caplog.set_level(logging.WARNING, logger=LOGGER) |
| 246 | |
| 247 | def no_worker(*_args, **_kwargs): |
| 248 | raise OSError("cannot fork") |
| 249 | |
| 250 | monkeypatch.setattr(object_sandbox, "_Worker", no_worker) |
| 251 | result = run_object("in_process", root, "u_7_hello") |
| 252 | assert not result.ok |
| 253 | line = _wait_for(caplog, "single-use worker failed to start")[0] |
| 254 | assert "OSError: cannot fork" in line and "memory limit 512 MiB" in line |