Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Servers: the request log switch names a directory, one file per run
MangetsuC1be0da2b196a
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 4af8b84..67c44b1 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1005,14 +1005,15 @@ The same lane also exports `EXL3_HOST_LEAN`, `EXL3_HOST_CUTS`, `EXL3_LOAD_DEVICE| variable | default | what it does ||---|---|---|-| `KYOJIN_REQLOG` | unset = off | Path of a per-request lifecycle log, or `1`/`on`/`yes` for `~/.cache/kyojin/requests.log` (`0`/`off`/`none`/`no`/`false` disable it). Numbers and event names only, never prompt or reply text; one line per event and a heartbeat (`alive`) while a job is queued, prefilling or decoding. The file is created `0600` whatever the umask is, and an existing file left wider is tightened on the next start; a directory this server has to create is `0700`, while one that already exists keeps its own mode; the shared folder `~/.cache/kyojin`, or wherever `KYOJIN_HEALTH_DIR` points, is created with the process umask instead, its missing parents included, because more than one process writes there. For a streaming reply the heartbeat also carries the **output accounting** (`out_events`, `out_chars`, `last_out_s`) and the request ends with one `sse_summary` line, which is what tells "the client was sent nothing" from "the client showed nothing"; the event tables, the shared/GLM-only split and how to read it are in [logging.md](logging.md). Served by all three servers from one module (`tools/strix_halo/serve_reqlog.py`, with `serve_reqlog.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`): the whole request lifecycle — the request table, the id on every line, the heartbeat and the route wrapper (`Lifecycle`) — is that module's, so the three servers emit one vocabulary, which `tools/test_serve_logging.py` checks against all three at once; each server's document only points back here and to [logging.md](logging.md). |+| `KYOJIN_REQLOG_DIR` | unset = off | Directory for the per-request lifecycle log, or `1`/`on`/`yes` for `~/.cache/kyojin`. A path that ends in a file name is read as that file's **directory** (`/var/log/kyojin/requests.log` means `/var/log/kyojin`), since that is what pointing it at a log means; the log file is always `requests-<run>.log` in that directory. Every run writes its own file, `requests-<run>.log` (so the default is `~/.cache/kyojin/requests-<run>.log`), and every line carries `run=<id>`, so one run can be read without filtering the others out; the oldest runs are removed at start-up, see `KYOJIN_REQLOG_KEEP` (`0`/`off`/`none`/`no`/`false` disable it). Numbers and event names only, never prompt or reply text; one line per event and a heartbeat (`alive`) while a job is queued, prefilling or decoding. The file is created `0600` whatever the umask is, and an existing file left wider is tightened on the next start; a directory this server has to create is `0700`, while one that already exists keeps its own mode; the shared folder `~/.cache/kyojin`, or wherever `KYOJIN_HEALTH_DIR` points, is created with the process umask instead, its missing parents included, because more than one process writes there. For a streaming reply the heartbeat also carries the **output accounting** (`out_events`, `out_chars`, `last_out_s`) and the request ends with one `sse_summary` line, which is what tells "the client was sent nothing" from "the client showed nothing"; the event tables, the shared/GLM-only split and how to read it are in [logging.md](logging.md). Served by all three servers from one module (`tools/strix_halo/serve_reqlog.py`, with `serve_reqlog.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`): the whole request lifecycle — the request table, the id on every line, the heartbeat and the route wrapper (`Lifecycle`) — is that module's, so the three servers emit one vocabulary, which `tools/test_serve_logging.py` checks against all three at once; each server's document only points back here and to [logging.md](logging.md). || `KYOJIN_REQLOG_HEARTBEAT_S` | `10` | Seconds between `alive` lines; `0` disables the heartbeat (the log stays on). |+| `KYOJIN_REQLOG_KEEP` | `20` | How many runs keep their log file. Checked once, at start-up: the run files of the oldest runs are removed, so the directory holds this many (this run included). It counts only files this module writes (`requests-<run>.log`); an archive or a file an earlier layout appended to is never deleted. `0` keeps every run. |#### SSE keep-alive (all three servers)| variable | default | what it does ||---|---|---|-| `KYOJIN_SSE_PING_S` | `0` = off | Seconds a stream may go without a data event before the server writes one SSE comment line (`: waiting <n> s`), which keeps a client that only watches its socket from treating a long prefill — or a long decode nothing is being written for — as a dead server. The comment counts from the request's arrival, comes once per interval and only after that much silence: a stream that is producing text never gets one, and one that stops gets them again (a reply holding a `<tool_call>` back until its XML closes is decoded for minutes while the client hears nothing). The `role` chunk a client gets immediately does not count as output, so the whole prefill is covered. Shared by the three servers (`tools/strix_halo/serve_ping.py`, with `serve_ping.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`), read per request, reported on one start-up line. With the default nothing is written at all. Worth setting on any server that sees long prompts — an image conversation can prefill for minutes — together with a client-side timeout that is long enough; each comment is also an `sse_ping` line in the request log (`KYOJIN_REQLOG`) when that is on and the server's pinger is wired to it (GLM's is). See [logging.md](logging.md). |+| `KYOJIN_SSE_PING_S` | `0` = off | Seconds a stream may go without a data event before the server writes one SSE comment line (`: waiting <n> s`), which keeps a client that only watches its socket from treating a long prefill — or a long decode nothing is being written for — as a dead server. The comment counts from the request's arrival, comes once per interval and only after that much silence: a stream that is producing text never gets one, and one that stops gets them again (a reply holding a `<tool_call>` back until its XML closes is decoded for minutes while the client hears nothing). The `role` chunk a client gets immediately does not count as output, so the whole prefill is covered. Shared by the three servers (`tools/strix_halo/serve_ping.py`, with `serve_ping.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`), read per request, reported on one start-up line. With the default nothing is written at all. Worth setting on any server that sees long prompts — an image conversation can prefill for minutes — together with a client-side timeout that is long enough; each comment is also an `sse_ping` line in the request log (`KYOJIN_REQLOG_DIR`) when that is on and the server's pinger is wired to it (GLM's is). See [logging.md](logging.md). |#### `KYOJIN_HEALTH_DIR` (default: `~/.cache/kyojin`)diff --git a/doc/logging.md b/doc/logging.mdindex 9c11a47..f8cad37 100644--- a/doc/logging.md+++ b/doc/logging.md@@ -14,10 +14,30 @@ extra byte on the wire.| variable | default | meaning ||---|---|---|-| `KYOJIN_REQLOG` | **unset = off** | a path, or `1`/`on`/`yes` for `~/.cache/kyojin/requests.log`; `0`/`off`/`none`/`no`/`false` also disable it |+| `KYOJIN_REQLOG_DIR` | **unset = off** | the directory to write in, or `1`/`on`/`yes` for `~/.cache/kyojin`; a path ending in a file name means that file's directory; `0`/`off`/`none`/`no`/`false` also disable it |+| `KYOJIN_REQLOG_KEEP` | `20` | how many runs keep their file; the oldest are removed at start-up || `KYOJIN_REQLOG_HEARTBEAT_S` | `10` | seconds between `alive` lines while a job is queued, prefilling or decoding; `0` disables the heartbeat (the log itself stays on) || `KYOJIN_SSE_PING_S` | `0` = off | seconds a stream may go without a data event before the server writes one SSE comment line |+**One file per run.** The switch names a directory, and a run writes `requests-<run>.log` in it — the+default directory is `~/.cache/kyojin`, so the file is `~/.cache/kyojin/requests-<run>.log`, and every line+carries `run=<id>`. A path that ends in a file name is read as that file's directory+(`/var/log/kyojin/requests.log` means `/var/log/kyojin`), which is what pointing the switch at a log means;+that file itself is never written to, the run's own `requests-<run>.log` is. One run's lines can+therefore be read on their own, instead of every run of every server piling into one file that has to be+filtered by hand. At start-up the run files of the oldest runs are removed, keeping the newest+`KYOJIN_REQLOG_KEEP` of them (20 by default) — the directory is checked at start-up only, and nothing+while a run is going on. A file this module did not write, such as an archive or the plain file an earlier+layout appended to, is never deleted.++**A long-running server keeps writing.** There is no size limit: while the log is on, a run writes its+events plus one `alive` line per heartbeat interval per request that is queued, prefilling or decoding, so+a server left running for weeks grows its file for weeks. Measurements from this deployment: about 14-21+lines per request, 144 bytes a line, a few MB an hour of normal agent traffic — and much more for long+image prefills, where the heartbeat is what fills the file. Keep the switch on for the runs that need+diagnosing and turn it off for a server that is meant to stay up; if it must stay on, lower+`KYOJIN_REQLOG_KEEP` and read the run you need from its own file.+**Every file this writes is owner-only.** The log (and the picture cache the GLM server keeps on disk)holds material derived from what clients sent, so the files are created `0600` regardless of the processumask — a host with the common `0022` would otherwise get `0644` logs. A file that already exists with a@@ -38,8 +58,8 @@ Each server prints one line per switch at start-up, so the state is discoverablefile:```-serve: request log off (set KYOJIN_REQLOG=<path> to enable, numbers and event names only)-serve: request log /home/you/.cache/kyojin/requests.log (heartbeat 10 s, numbers and event names only, no prompt or reply text)+serve: request log off (set KYOJIN_REQLOG_DIR=<directory> to enable, numbers and event names only)+serve: request log /home/you/.cache/kyojin/requests-20261016T153012.log (run 20261016T153012, from KYOJIN_REQLOG_DIR, heartbeat 10 s, keeping 20 runs, numbers and event names only, no prompt or reply text)serve: SSE keep-alive: a comment line after 10 s without output (KYOJIN_SSE_PING_S)serve: SSE keep-alive off (set KYOJIN_SSE_PING_S=<seconds> to hold a silent stream open)```diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 416c209..4c87273 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -244,7 +244,7 @@ this server:* **GLM is the only server whose pinger also writes its comments to the log**, so `sse_ping` lines andthe `sse_ping_s` field of `serve_start` appear here and not on Qwen or MiMo.-Turn it on with `KYOJIN_REQLOG=<path>` (or `1`); both switches are in [doc/env_vars.md](../../doc/env_vars.md).+Turn it on with `KYOJIN_REQLOG_DIR=<directory>` (or `1`) — each run writes `requests-<run>.log` there, keeping the newest 20 runs; the switches are in [doc/env_vars.md](../../doc/env_vars.md), and what is written, per run, in [doc/logging.md](../../doc/logging.md).## Start-up progress on `/health`@@ -334,7 +334,7 @@ keep-alive timing (off by default, one comment per interval, retired at the firsrequest).`test_serve_glm_additional.py` holds the tests for what this checkout adds locally: the-request log (`KYOJIN_REQLOG`, off by default, no request text), the image cache+request log (`KYOJIN_REQLOG_DIR`, off by default, no request text), the image cache(`--image-cache-mb` / `--image-cache-items`, the defaults of the `--image-cache-dir*` options,the row format, what `img_cache` reports) and the SSE keep-alive (a comment reaches the client beforethe first token, and nothing at all with the switch off). It is a file of its own so upstream'sdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex c612525..9d66645 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -31,7 +31,7 @@ from serve_metrics import Metrics# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: one line per request# lifecycle event (numbers and event names only, never prompt or reply text) plus a heartbeat while a job# is queued or prefilling, so "the client went silent" can be lined up with what the server was doing.-# Off unless KYOJIN_REQLOG names a path; the server prints which of the two it is at start-up.+# Off unless KYOJIN_REQLOG_DIR names a directory; the server prints which of the two it is at start-up.from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize# serve_ping.py is a symlink to the shared tools/strix_halo/serve_ping.py: an SSE comment line every# KYOJIN_SSE_PING_S while a stream has nothing to send yet (off by default), so the same silence is@@ -1068,7 +1068,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())- # Request log: off unless KYOJIN_REQLOG names a path, in which case every generation request gets one line+ # Request log: off unless KYOJIN_REQLOG_DIR names a directory, in which case every generation request gets a line# per lifecycle event (numbers and event names only, never prompt or reply text) plus an 'alive' heartbeat# while it is queued or running. `inflight` is what the heartbeat walks; it holds no request content.reqlog = ReqLog.from_env(server="glm")diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 8d0ba38..3a30f7d 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -87,6 +87,15 @@ def vision_engine():return eng, calls+def run_log_file(directory) -> Path:+ """The file the last run wrote in a directory: `requests-<run>.log`, one file per run."""+ directory = Path(directory)+ if directory.suffix: # a file name handed in: its directory is what is used+ directory = directory.parent+ written = sorted(directory.glob("requests-*.log"))+ return written[-1] if written else directory / "requests-none.log"++def disk_engine(directory, budget_bytes: int = 768, mode: str = "fp32", cap_bytes: int = 0, on_disk: bool = True,lock_s: float = 0.0, policy: str = "tail", fingerprint: str = ""):"""An engine whose _embed() runs over a real memory cache *and* a real second-level cache on disk.@@ -439,18 +448,25 @@ class ImageDiskCacheTests(unittest.TestCase):class RequestLogTests(unittest.TestCase):- """KYOJIN_REQLOG: off unless asked for; when on, one line per lifecycle event, numbers and names only."""+ """KYOJIN_REQLOG_DIR: off unless asked for; when on, one line per lifecycle event, numbers and names only."""def setUp(self):self.tmp = tempfile.TemporaryDirectory()self.addCleanup(self.tmp.cleanup)- self.log_path = Path(self.tmp.name) / "requests.log"- for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S"):+ self.log_dir = Path(self.tmp.name) # the switch names a directory+ self.log_path = self.log_dir / "requests.log" # only used to assert that nothing appears+ for key in ("KYOJIN_REQLOG_DIR", "KYOJIN_REQLOG_HEARTBEAT_S"):os.environ.pop(key, None)self.addCleanup(os.environ.pop, key, None)+ def current_log(self) -> Path:+ """The file this run wrote: `<stem>-<run><suffix>` beside the base path, one file per run."""+ written = sorted(self.log_dir.glob("requests-*.log"))+ return written[-1] if written else self.log_path+def lines(self) -> list[str]:- return self.log_path.read_text(encoding="utf-8").splitlines() if self.log_path.exists() else []+ path = self.current_log()+ return path.read_text(encoding="utf-8").splitlines() if path.exists() else []def events(self) -> list[tuple[str, dict]]:"""(event name, fields) per line; the timestamp is field 0 and the event name field 1."""@@ -495,7 +511,7 @@ class RequestLogTests(unittest.TestCase):self.assertFalse(list(Path(self.tmp.name).iterdir()))def test_lifecycle_lines_share_one_id_and_never_hold_request_text(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)secret, reply = "PROMPT-SECRET-7f3a", "REPLY-SECRET-9b1c"engine = FakeEngine(reply)from aiohttp.test_utils import TestClient, TestServer@@ -527,7 +543,7 @@ class RequestLogTests(unittest.TestCase):self.assertNotIn(reply, blob)def test_stream_headers_first_content_and_done(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)from aiohttp.test_utils import TestClient, TestServerasync def check():@@ -546,7 +562,7 @@ class RequestLogTests(unittest.TestCase):self.assertLess(names.index("sse_first_content"), names.index("sse_done"))def test_refusals_are_logged_without_quoting_the_body(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)from aiohttp.test_utils import TestClient, TestServerasync def check():@@ -567,7 +583,7 @@ class RequestLogTests(unittest.TestCase):self.assertNotIn("model", reasons)def test_image_request_logs_cache_hits_misses_and_budget(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)from PIL import Imagefrom aiohttp.test_utils import TestClient, TestServereng, _ = vision_engine()@@ -614,7 +630,7 @@ class RequestLogTests(unittest.TestCase):self.assertNotIn("data:image", "\n".join(self.lines())) # the image URL is never writtendef test_heartbeat_while_a_job_runs(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.05"from aiohttp.test_utils import TestClient, TestServer@@ -638,8 +654,35 @@ class RequestLogTests(unittest.TestCase):self.assertTrue(all("elapsed_s" in f and "phase" in f for f in alive))self.assertTrue({f["phase"] for f in alive} <= {"parse", "queued", "prefill", "decode", "stream"})+ def test_the_switch_names_a_directory_and_a_file_name_means_its_directory(self):+ """`KYOJIN_REQLOG_DIR` is a directory: an operator who points it at `.../requests.log` means the+ directory that file lives in, and that file itself is never written to."""+ import tempfile+ from serve_reqlog import ReqLog, log_dir_from_env+ with tempfile.TemporaryDirectory() as tmp:+ logs = Path(tmp) / "logs"+ logs.mkdir()+ cases = {+ str(logs): logs, # a directory+ str(logs / "requests.log"): logs, # a file name: its directory+ "1": Path("~/.cache/kyojin").expanduser(), # on, default directory+ "0": None, # off+ }+ for raw, expected in cases.items():+ os.environ["KYOJIN_REQLOG_DIR"] = raw+ self.assertEqual(log_dir_from_env(), expected, raw)++ os.environ["KYOJIN_REQLOG_DIR"] = str(logs / "requests.log")+ log = ReqLog.from_env(server="glm")+ try:+ self.assertTrue(str(log.path).startswith(str(logs) + os.sep))+ self.assertTrue(log.path.name.startswith("requests-"))+ self.assertTrue(log.path.name.endswith(".log"))+ finally:+ log.close()+def test_v1_completions_is_logged_too(self):- os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(self.log_dir)from aiohttp.test_utils import TestClient, TestServerasync def check():@@ -747,23 +790,24 @@ class SSEKeepAliveTests(unittest.TestCase):from serve_reqlog import ReqLog, secure_dirtmp = tempfile.TemporaryDirectory()self.addCleanup(tmp.cleanup)- fresh = Path(tmp.name) / "logs" / "requests.log"+ base = Path(tmp.name) / "logs" / "requests.log"previous = os.umask(0)try:- log = ReqLog(path=str(fresh), server="test")+ log = ReqLog(path=str(base), server="test")log.log("req_start", req="r1")+ written = log.path # this run's own file, not the base pathlog.close()- self.assertEqual(_stat.S_IMODE(fresh.parent.stat().st_mode), 0o700)- self.assertEqual(_stat.S_IMODE(fresh.stat().st_mode), 0o600)+ self.assertEqual(_stat.S_IMODE(base.parent.stat().st_mode), 0o700)+ self.assertEqual(_stat.S_IMODE(written.stat().st_mode), 0o600)- os.chmod(fresh, 0o666) # as an earlier run would have left the file- os.chmod(fresh.parent, 0o775) # ...and the directory the deployment owns- again = ReqLog(path=str(fresh), server="test")+ os.chmod(written, 0o666) # as an earlier run would have left the file+ os.chmod(base.parent, 0o775) # ...and the directory the deployment owns+ again = ReqLog(path=str(base), server="test") # the next run: another file of its ownagain.close()finally:os.umask(previous)- self.assertEqual(_stat.S_IMODE(fresh.parent.stat().st_mode), 0o775) # left alone- self.assertEqual(_stat.S_IMODE(fresh.stat().st_mode), 0o600) # this one is ours+ self.assertEqual(_stat.S_IMODE(base.parent.stat().st_mode), 0o775) # left alone+ self.assertEqual(_stat.S_IMODE(written.stat().st_mode), 0o600) # this one is oursdef test_every_directory_this_creates_is_owner_only(self):"""Not just the leaf: `mkdir(parents=True, mode=...)` leaves the directories in between at 0777@@ -881,6 +925,44 @@ class SSEKeepAliveTests(unittest.TestCase):(path / "startup-glm.json").parent.mkdir(parents=True, exist_ok=True)return path+ def test_every_run_writes_its_own_log_and_old_runs_are_kept_by_count(self):+ """One file per run, so a run's lines can be read without filtering the other runs out.++ The switch names a base path; a run writes `<stem>-<run><suffix>` beside it and the newest+ `KYOJIN_REQLOG_KEEP` runs stay (checked once, at start-up). Files this module did not write - an+ archive, or the plain file an earlier layout appended to - are never deleted."""+ import stat as _stat+ import tempfile+ from serve_reqlog import ReqLog+ with tempfile.TemporaryDirectory() as tmp:+ base = Path(tmp) / "requests.log"+ for i in range(23): # 23 runs already on disk+ (Path(tmp) / f"requests-20260101T{i:06d}.log").write_text("old\n")+ (base).write_text("the file an earlier layout appended to\n")+ (Path(tmp) / "other-20260101T000000.log").write_text("another program\n")++ os.environ["KYOJIN_REQLOG_KEEP"] = "20"+ self.addCleanup(os.environ.pop, "KYOJIN_REQLOG_KEEP", None)+ log = ReqLog(path=str(base), server="test")+ try:+ self.assertNotEqual(log.path, base) # not the shared file any more+ self.assertTrue(log.path.name.startswith("requests-"))+ self.assertTrue(log.path.name.endswith(".log"))+ log.log("req_start", req="r1")+ line = log.path.read_text().splitlines()[0]+ self.assertIn(f"run={log.run}", line) # every line names its run+ self.assertIn("keeping 20 runs", log.describe())+ finally:+ log.close()+ kept = sorted(p.name for p in Path(tmp).glob("requests-*.log"))+ self.assertEqual(len(kept), 20) # exactly the retention, this run included+ self.assertEqual(kept[-1], log.path.name) # the newest is this run's+ self.assertIn("requests-20260101T000022.log", kept) # the newest of the old ones stays...+ self.assertNotIn("requests-20260101T000003.log", kept) # ...and the oldest go+ self.assertNotIn("requests-20260101T000000.log", kept)+ self.assertEqual(log.pruned, 4) # 23 old + this one - 20 kept+ self.assertTrue((Path(tmp) / "other-20260101T000000.log").exists())+def test_the_log_says_whether_the_server_was_writing(self):"""The accounting that separates "the client showed nothing" from "the server sent nothing".@@ -890,9 +972,9 @@ class SSEKeepAliveTests(unittest.TestCase):import tempfiletmp = tempfile.TemporaryDirectory()self.addCleanup(tmp.cleanup)- os.environ["KYOJIN_REQLOG"] = str(Path(tmp.name) / "requests.log")+ os.environ["KYOJIN_REQLOG_DIR"] = tmp.name # the switch names a directoryos.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.2"- self.addCleanup(os.environ.pop, "KYOJIN_REQLOG", None)+ self.addCleanup(os.environ.pop, "KYOJIN_REQLOG_DIR", None)self.addCleanup(os.environ.pop, "KYOJIN_REQLOG_HEARTBEAT_S", None)from aiohttp.test_utils import TestClient, TestServer@@ -913,7 +995,7 @@ class SSEKeepAliveTests(unittest.TestCase):run(check())events = []- for line in Path(os.environ["KYOJIN_REQLOG"]).read_text(encoding="utf-8").splitlines():+ for line in run_log_file(os.environ["KYOJIN_REQLOG_DIR"]).read_text(encoding="utf-8").splitlines():parts = line.split(" ")fields = {}for item in parts[2:]:diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex 992e584..5d2935a 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -67,8 +67,8 @@ The log and the stream keep-alive are shared code: switches, format, every eventoutput accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes thesame events as GLM except for `serve_start` and `img_cache` (GLM's image cache and its disk tier)and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the shared-part against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silent-stream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).+part against all three servers at once. Turn it on with `KYOJIN_REQLOG_DIR=<directory>` (or `1`) and hold a silent+stream open with `KYOJIN_SSE_PING_S=<seconds>`; a run writes its own log file (`requests-<run>.log`, newest 20 kept), and both switches are in [doc/env_vars.md](../../doc/env_vars.md).## Start-up progress on `/health`diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex e4dff6c..ce93af2 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -41,7 +41,7 @@ from serve_metrics import Metrics# not look like a hung server to a client that only watches its socket.from serve_ping import ServePing# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: off unless-# KYOJIN_REQLOG names a path. Its output accounting also feeds the end-of-stream summary here.+# KYOJIN_REQLOG_DIR names a directory. Its output accounting also feeds the end-of-stream summary here.from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitizefrom image_cache import ImageEmbeddingCache, digest@@ -516,7 +516,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:# A request copies this pinger, so its timers are its own; the start-up line reports the setting.ping = ServePing.from_env()app.update(ping=ping)- # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is bound+ # Request log: off unless KYOJIN_REQLOG_DIR names a directory (numbers and event names only). The name is bound# here, not only stored on the app: the streaming route logs from inside its own scope, and an unbound# name there raises after the reply is complete, which costs the client its connection.reqlog = ReqLog.from_env(server="mimo")diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex bff5db1..a348dd1 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -107,8 +107,8 @@ The log and the stream keep-alive are shared code: switches, format, every eventoutput accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes thesame events as GLM except for `serve_start` and `img_cache` (GLM's image cache and its disk tier)and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the shared-part against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silent-stream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).+part against all three servers at once. Turn it on with `KYOJIN_REQLOG_DIR=<directory>` (or `1`) and hold a silent+stream open with `KYOJIN_SSE_PING_S=<seconds>`; a run writes its own log file (`requests-<run>.log`, newest 20 kept), and both switches are in [doc/env_vars.md](../../doc/env_vars.md).## Start-up progress on `/health`diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 510d731..e206d9d 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -48,7 +48,7 @@ import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /to# not look like a hung server to a client that only watches its socket.from serve_ping import ServePing # noqa: E402# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: off unless-# KYOJIN_REQLOG names a path. Its output accounting also feeds the end-of-stream summary here.+# KYOJIN_REQLOG_DIR names a directory. Its output accounting also feeds the end-of-stream summary here.from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize # noqa: E402@@ -1270,7 +1270,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An# A request copies this pinger, so its timers are its own; the start-up line reports the setting.ping = ServePing.from_env()app.update(ping=ping)- # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is bound+ # Request log: off unless KYOJIN_REQLOG_DIR names a directory (numbers and event names only). The name is bound# here, not only stored on the app: the streaming routes log from inside their own scope, and an# unbound name there raises after the reply is complete, which costs the client its connection.reqlog = ReqLog.from_env(server="qwen")diff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.pyindex ba89f2a..e5db9b0 100644--- a/tools/strix_halo/serve_reqlog.py+++ b/tools/strix_halo/serve_reqlog.py@@ -8,10 +8,20 @@ compared afterwards. The heartbeat and the per-request summary carry the requestaccounting** (`out_events`, `out_chars`, `last_out_s`), which is what separates "the server waswriting to a client that did not show it" from "the server had nothing to write".-**Off unless asked for.** With KYOJIN_REQLOG unset (or 0/off/none/no/false/empty) nothing is opened and+**Off unless asked for.** With KYOJIN_REQLOG_DIR unset (or 0/off/none/no/false/empty) nothing is opened andevery call is a no-op, so a default deployment behaves exactly as before. The server prints one line atstart-up either way, so the switch stays discoverable when a request does go silent.+**One file per run.** The switch names a directory; a run writes `requests-<run>.log` in it (the default+directory is `~/.cache/kyojin`) and every line carries that run id, so the lines of one run can be read+without filtering the other runs out. A path that ends in a file name is read as that file's directory+(`/var/log/kyojin/requests.log` means `/var/log/kyojin`); that file itself is never written to - every run+writes `requests-<run>.log` in the directory. At start-up the log files of the oldest runs are removed,+keeping the newest `KYOJIN_REQLOG_KEEP` (20 by default) of them: the directory is checked once, at+start-up, and nothing is checked while a run is going on. A long-running server writes continuously+(one `alive` line per heartbeat interval per request plus the events), so a deployment that keeps a log+open for weeks should turn it off or shorten the retention rather than expect the file to stop growing.+**Owner-only files.** The log, and the picture cache the GLM server keeps on disk, hold material derivedfrom what clients sent, so the files are created `0600` and an older one is tightened on the next start(`secure_open` / `restrict` below); every directory this server creates is `0700`. Without that the mode@@ -23,7 +33,7 @@ default (`shared_cache_dir()`) — is created with the process umask like any otfolders above it included: more than one process writes there, and whichever makes it first must not decidehow it looks. A file inside is still unreadable to others at `0600`.- KYOJIN_REQLOG=~/cache/kyojin/requests.log # a path, or 1/on/yes for the default path below+ KYOJIN_REQLOG_DIR=/var/log/kyojin # a directory, or 1/on/yes for the default belowKYOJIN_REQLOG_HEARTBEAT_S=10 # seconds between 'alive' lines while a job runsPrivacy: nothing derived from the request is written except numbers — token counts, message/image@@ -51,7 +61,12 @@ import timeimport uuidfrom typing import Any-DEFAULT_PATH = "~/.cache/kyojin/requests.log"+# The switch names a directory; every run writes its own file in it, `<BASE>-<run>.log`, so that the lines of+# one run can be read without filtering the lines of every other run out of one growing file.+DEFAULT_DIR = "~/.cache/kyojin"+BASE_NAME = "requests" # fixed: the directory says where, this says what it is+RUN_STAMP = "%Y%m%dT%H%M%S"+DEFAULT_KEEP = 20 # runs kept on disk; older files are removed when a server startsFALSE = {"0", "off", "none", "no", "false", ""}TRUE = {"1", "on", "yes", "true"}@@ -455,39 +470,84 @@ def refusal_text(exc: Any) -> str:return text or type(exc).__name__+def log_dir_from_env(environ: Any = None) -> pathlib.Path | None:+ """The directory to write logs in, or None when logging is off.++ `KYOJIN_REQLOG_DIR` names a *directory*. A path that ends in a file is read as that file's directory+ (`/var/log/kyojin/requests.log` means `/var/log/kyojin`), because that is what an operator has in mind+ when they point the switch at a log, and that file is never written to: every run writes its own+ `<BASE_NAME>-<run>.log` in the directory.+ """+ env = os.environ if environ is None else environ+ raw = str(env.get("KYOJIN_REQLOG_DIR", "") or "").strip()+ if not raw or raw.lower() in FALSE:+ return None+ if raw.lower() in TRUE:+ return pathlib.Path(DEFAULT_DIR).expanduser()+ target = pathlib.Path(raw).expanduser()+ directory = target if (target.is_dir() or target.name in ("", ".", "..")) else target.parent+ return directory if str(directory) else pathlib.Path(".")++class ReqLog:- """Append-only event log. Every method is safe to call when logging is disabled or broken."""+ """Append-only event log, one file per run. Safe when logging is disabled or broken."""def __init__(self, path: str | None = None, heartbeat_s: float | None = None,server: str | None = None) -> None:- raw = os.environ.get("KYOJIN_REQLOG", "") if path is None else path- raw = raw.strip()self.server = server- self.enabled = raw.lower() not in FALSE- if self.enabled and raw.lower() in TRUE:- raw = DEFAULT_PATH- self.path: pathlib.Path | None = pathlib.Path(raw).expanduser() if self.enabled else None+ if path is None:+ self.directory = log_dir_from_env()+ self.enabled = self.directory is not None+ else:+ # an explicit path is a directory too, with the same rule (a file name means its directory)+ raw = str(path).strip()+ self.enabled = raw.lower() not in FALSE+ target = pathlib.Path(raw).expanduser() if self.enabled else None+ if target is None or raw.lower() in TRUE:+ self.directory = pathlib.Path(DEFAULT_DIR).expanduser() if self.enabled else None+ else:+ self.directory = target if (target.is_dir() or target.name in ("", ".", "..")) else target.parent+ self.base_path = self.directory / BASE_NAME if self.directory is not None else None+ self.run = time.strftime(RUN_STAMP) if self.enabled else None+ # one file per start, so a file is one run; the fixed base name is what the retention matches on+ self.path = (self.base_path.with_name(f"{self.base_path.name}-{self.run}.log")+ if self.base_path is not None else None)if heartbeat_s is None:try:heartbeat_s = float(os.environ.get("KYOJIN_REQLOG_HEARTBEAT_S", "10") or 10)except ValueError:heartbeat_s = 10.0self.heartbeat_s = max(0.0, heartbeat_s)+ try:+ self.keep = int(os.environ.get("KYOJIN_REQLOG_KEEP", DEFAULT_KEEP) or DEFAULT_KEEP)+ except ValueError:+ self.keep = DEFAULT_KEEPself._lock = threading.Lock()+ self.pruned = 0self._fh = None- if self.enabled and self.path is not None:- try:- # Owner-only: the log names every request's size, timing and outcome, and it is derived- # from what clients sent (see the module docstring). The file mode applies when the file- # is created; an older one is tightened here too. A shared folder (the deployment's- # ~/.cache/kyojin) keeps the mode the deployment gave it.- secure_dir(self.path.parent)- fd = secure_open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND)- self._fh = os.fdopen(fd, "a", encoding="utf-8")- restrict(self.path, 0o600)- except OSError as exc:- print(f"serve: request log off ({type(exc).__name__}: {exc})", file=sys.stderr, flush=True)- self.enabled, self._fh = False, None+ self.open()++ def open(self) -> bool:+ """Open this run's file (the constructor calls it). A failure leaves the log off, never raises."""+ if not self.enabled or self.path is None or self._fh is not None:+ return self._fh is not None+ try:+ # Owner-only: the log names every request's size, timing and outcome, and it is derived+ # from what clients sent (see the module docstring). The file mode applies when the file+ # is created; an older one is tightened here too. A shared folder (the deployment's+ # ~/.cache/kyojin) keeps the mode the deployment gave it.+ secure_dir(self.path.parent)+ # This run's file is created before pruning, so that the directory holds exactly `keep` of them+ # at every start (and not `keep` plus the one that just appeared)+ fd = secure_open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND)+ self._fh = os.fdopen(fd, "a", encoding="utf-8")+ restrict(self.path, 0o600)+ self.pruned = self.prune_old_runs()+ return True+ except OSError as exc:+ print(f"serve: request log off ({type(exc).__name__}: {exc})", file=sys.stderr, flush=True)+ self.enabled, self._fh = False, None+ return False@classmethoddef from_env(cls, server: str | None = None) -> "ReqLog":@@ -496,9 +556,35 @@ class ReqLog:def describe(self) -> str:"""One start-up line, so an operator can tell whether the log is on without looking for a file."""if self._fh is None or self.path is None:- return "request log off (set KYOJIN_REQLOG=<path> to enable, numbers and event names only)"- return (f"request log {self.path} (heartbeat {self.heartbeat_s:g} s, "- f"numbers and event names only, no prompt or reply text)")+ return "request log off (set KYOJIN_REQLOG_DIR=<directory> to enable, numbers and event names only)"+ pruned = f", {self.pruned} older removed" if self.pruned else ""+ return (f"request log {self.path} (run {self.run}, heartbeat {self.heartbeat_s:g} s, "+ f"keeping {self.keep} runs{pruned}, numbers and event names only, no prompt or reply text)")++ def prune_old_runs(self) -> int:+ """Remove the log files of the oldest runs, keeping the newest `keep` beside the base path.++ Runs are ordered by the stamp in their name, not by their dates, so a file that was copied around+ keeps its place in the order. Only files this module writes are candidates - `<stem>-<stamp><suffix>`+ - so an archive (a renamed or compressed one, say) is never deleted, and the base file of an earlier+ layout (a plain `requests.log` someone appended to) is left where it is. Called once, at start-up:+ nothing is checked while a run is going on, so the request path pays nothing for this.+ """+ if self.directory is None or self.keep <= 0:+ return 0+ try:+ candidates = sorted(self.directory.glob(f"{BASE_NAME}-*.log"))+ except OSError:+ return 0+ doomed = candidates[:max(0, len(candidates) - self.keep)] # this run is one of them+ removed = 0+ for entry in doomed:+ try:+ entry.unlink()+ removed += 1+ except OSError:+ pass+ return removeddef log(self, event: str, **fields: Any) -> None:if self._fh is None:@@ -509,6 +595,8 @@ class ReqLog:parts = [f"{stamp}.{ms:03d}", event]if self.server:parts.append(f"srv={self.server}")+ if self.run:+ parts.append(f"run={self.run}")for key, value in fields.items():if value is None:continuediff --git a/tools/test_serve_logging.py b/tools/test_serve_logging.pyindex 2b738ad..49dd8e2 100644--- a/tools/test_serve_logging.py+++ b/tools/test_serve_logging.py@@ -98,8 +98,17 @@ def load_server(name: str):sys.path.remove(str(here))+def run_log_file(directory: Path) -> Path:+ """The file the last run wrote in a directory: `requests-<run>.log`, one file per run."""+ if directory.suffix: # a file name handed in: its directory is what is used+ directory = directory.parent+ written = sorted(directory.glob("requests-*.log"))+ return written[-1] if written else directory / "requests-none.log"++def parse_log(path: Path) -> dict[str, dict[str, set[str]]]:"""{request id: {event: fields}}; the heartbeat's own lines land under the key '-' if untagged."""+ path = run_log_file(path) # one file per run: read the one this battery wroteout: dict[str, dict[str, set[str]]] = {}for line in path.read_text(encoding="utf-8").splitlines():parts = line.split(" ")@@ -128,13 +137,13 @@ def run_battery(name: str, log_path: Path) -> dict[str, dict[str, set[str]]]:finally:await client.close()- os.environ["KYOJIN_REQLOG"] = str(log_path)+ os.environ["KYOJIN_REQLOG_DIR"] = str(log_path.parent) # the switch names a directoryos.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.2"os.environ["KYOJIN_SSE_PING_S"] = "0.2"try:asyncio.run(go())finally:- for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S", "KYOJIN_SSE_PING_S"):+ for key in ("KYOJIN_REQLOG_DIR", "KYOJIN_REQLOG_HEARTBEAT_S", "KYOJIN_SSE_PING_S"):os.environ.pop(key, None)return parse_log(log_path)