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 log and the picture cache on disk are owner-only
MangetsuCf773999ca046
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 9edb0ef..4af8b84 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1005,7 +1005,7 @@ 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. 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` | 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_HEARTBEAT_S` | `10` | Seconds between `alive` lines; `0` disables the heartbeat (the log stays on). |#### SSE keep-alive (all three servers)diff --git a/doc/logging.md b/doc/logging.mdindex 6789e1b..78b4239 100644--- a/doc/logging.md+++ b/doc/logging.md@@ -18,6 +18,22 @@ extra byte on the wire.| `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 |+**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 process+umask — a host with the common `0022` would otherwise get `0644` logs. A file that already exists with a+wider mode is tightened on the next start, because `open(..., "a")` does not change the mode of a file it+opens.++The **directory** is made `0700` when this server creates it, and a directory that already exists is left+exactly as it is. One directory is deliberately not given that mode: the shared folder where the servers+keep state for each other — `~/.cache/kyojin`, or wherever `KYOJIN_HEALTH_DIR` points+([env_vars.md](env_vars.md)) — is created with the process umask like any other shared directory on the+host, and the folders above it are created the same way when they are missing. It is not this server's to+restrict: more than one process writes there, and which of them makes it first must not change what it+looks like. Everywhere else the modes above hold, a directory of the server's own *inside* that folder+(`image-embeddings`, for instance) included, and the files inside are `0600` either way, so their contents+are not readable by others on the box.+Each server prints one line per switch at start-up, so the state is discoverable without looking for afile:@@ -134,7 +150,7 @@ tolerates comments from giving up, and tells you the server was alive if one doe## Privacy-Nothing derived from the request is written except numbers: token counts, message and image counts,+The files are owner-only (see above) and nothing derived from the request is written except numbers: token counts, message and image counts,durations, byte counts, HTTP statuses, an opaque request id, a server tag and event names. Prompt text,completion text, tool arguments and image paths from the body are never logged. Of the server's own errortext, only the exception type is logged plus a truncated message; JSON parse errors are reduced todiff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex f7a6feb..0ce30cb 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -170,7 +170,12 @@ pictures are the end of a prompt, restoring them completes the prompt again andis where the large win is (99.8 % of a 24-page prompt reused, 1.2 s against 82.0 s). Under the default `head`policy it still saves the vision pass for the pictures it holds, but the prefix is broken at the first of them.Note what it stores: the **rows derived from the input images stay on disk**, which is a privacy and disk-wear-consideration. Two knobs bound it:+consideration. Because of that its files are created `0600` whatever the process umask is, and a file left+wider by an earlier run is tightened on the next start; the directory is made `0700` only if this server has to+create it, one that already exists keeps its mode, and the shared folder above it (`~/.cache/kyojin`, or+wherever `KYOJIN_HEALTH_DIR` points) is created with the process umask — its missing parents as well — since+other processes write there too.+Two knobs bound it:`--image-cache-dir-max-gb` caps the directory and `--image-cache-dir-lock-s` caps how often a conversation canlose its place to another one.diff --git a/tools/glm/image_cache_disk.py b/tools/glm/image_cache_disk.pyindex 4dac090..91bcfd8 100644--- a/tools/glm/image_cache_disk.py+++ b/tools/glm/image_cache_disk.py@@ -32,6 +32,9 @@ import torchfrom exllamav3.tokenizer.mm_embedding import MMEmbedding, QuantizedMMRows+# The log's module holds the owner-only helpers this cache needs (servers put tools/glm on sys.path).+from serve_reqlog import restrict, secure_dir, secure_open+def dtype_name(dtype: torch.dtype) -> str:"""`torch.float32` -> "float32": what a stored payload records about the rows it holds."""@@ -101,12 +104,17 @@ class ImageEmbeddingDisk:self.stats = {"loaded": 0, "stored": 0, "dropped": 0, "skipped": 0,"written_bytes": 0, "skipped_bytes": 0, "errors": 0}try:- self.path.mkdir(parents=True, exist_ok=True)+ # Owner-only: these files are rows derived from the pictures clients sent. See+ # tools/strix_halo/serve_reqlog.py for what the modes are and why they are set explicitly.+ secure_dir(self.path)self.enabled = Truefor entry in self.path.glob("*.pt"):try:self._bytes += entry.stat().st_sizeself._files += 1+ # A file written before the owner-only rule (or by a process with a looser umask) is+ # tightened here: files are only ever written once, so nothing else would revisit it.+ restrict(entry, 0o600)except OSError:pass# A directory left over the cap by an earlier run (or a smaller cap now) is trimmed here, oldest@@ -201,6 +209,7 @@ class ImageEmbeddingDisk:os.utime(path, None) # used now: the last thing the collector takesexcept OSError:pass+ restrict(path, 0o600) # belt and braces for a file from before the ruleself.stats["loaded"] += 1return emb@@ -252,7 +261,12 @@ class ImageEmbeddingDisk:path = self._file(key, mode)tmp = path.with_suffix(".tmp")try:- torch.save(payload, tmp)+ # torch.save() would create the temp file with the process umask (0644 on a 0022 host) and+ # os.replace() moves that mode onto the final name, so the file is made owner-only here.+ fd = secure_open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)+ with os.fdopen(fd, "wb") as fh:+ torch.save(payload, fh)+ restrict(tmp, 0o600)os.replace(tmp, path)size = path.stat().st_sizeself._bytes += sizediff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 74e3aad..ab826c8 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -592,6 +592,150 @@ class SSEKeepAliveTests(unittest.TestCase):self.assertLessEqual(body.count(b"tool_calls"), 2) # once as a message, once in usageself.assertTrue(body.rstrip().endswith(b"data: [DONE]"))+ def test_the_log_file_and_its_directory_are_owner_only(self):+ """The log names every request's size, timing and outcome: owner-only, whatever the umask is.++ Checked under a umask of 0, which is where a plain `open("a")` would leave 0666 in a 0777+ directory; a file that already exists with a wider mode is tightened on the next start."""+ import stat as _stat+ import tempfile+ from serve_reqlog import ReqLog, secure_dir+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ fresh = Path(tmp.name) / "logs" / "requests.log"+ previous = os.umask(0)+ try:+ log = ReqLog(path=str(fresh), server="test")+ log.log("req_start", req="r1")+ log.close()+ self.assertEqual(_stat.S_IMODE(fresh.parent.stat().st_mode), 0o700)+ self.assertEqual(_stat.S_IMODE(fresh.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")+ again.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++ def test_every_directory_this_creates_is_owner_only(self):+ """Not just the leaf: `mkdir(parents=True, mode=...)` leaves the directories in between at 0777+ (the C implementation does not pass the mode on), which the umask clearing below would expose."""+ import stat as _stat+ import tempfile+ from serve_reqlog import secure_dir+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ leaf = Path(tmp.name) / "a" / "b" / "c"+ previous = os.umask(0)+ try:+ secure_dir(leaf)+ finally:+ os.umask(previous)+ for made in (leaf, leaf.parent, leaf.parent.parent):+ self.assertEqual(_stat.S_IMODE(made.stat().st_mode), 0o700, made)+ os.chmod(leaf.parent, 0o775) # a directory that is not ours to change+ secure_dir(leaf)+ self.assertEqual(_stat.S_IMODE(leaf.parent.stat().st_mode), 0o775)++ def test_the_shared_cache_folder_is_created_the_way_the_health_history_creates_it(self):+ """Two modules create the shared folder; whichever runs first, it must come out the same.++ `tools/startup_health.py` makes it with a plain `mkdir(parents=True, exist_ok=True)` under the+ process umask, so this server must not make it owner-only instead: that would leave a different+ directory depending on which of the two started first."""+ import stat as _stat+ import tempfile+ from serve_reqlog import secure_dir, shared_cache_dir+ with tempfile.TemporaryDirectory() as tmp:+ os.environ["KYOJIN_HEALTH_DIR"] = str(Path(tmp) / "ours")+ self.addCleanup(os.environ.pop, "KYOJIN_HEALTH_DIR", None)+ shared = shared_cache_dir()+ self.assertEqual(shared, (Path(tmp) / "ours").expanduser()) # the same expression++ def modes(umask: int) -> tuple[int, int]:+ """(ours, theirs) for one umask, each in a fresh parent so both start from nothing."""+ mine = Path(tmp) / "run-ours"+ os.environ["KYOJIN_HEALTH_DIR"] = str(mine)+ previous = os.umask(umask)+ try:+ secure_dir(shared_cache_dir()) # ours first+ (Path(tmp) / "run-theirs" / "startup-glm.json").parent.mkdir(parents=True, exist_ok=True)+ finally:+ os.umask(previous)+ return (_stat.S_IMODE(mine.stat().st_mode),+ _stat.S_IMODE((Path(tmp) / "run-theirs").stat().st_mode))++ for umask in (0o022, 0o002, 0o000):+ ours, theirs = modes(umask)+ self.assertEqual(ours, theirs, f"umask {umask:04o}: {ours:04o} != {theirs:04o}")+ self.assertEqual(modes(0o022)[0], 0o755) # and it really follows the umask++ # the folders above it are created the same way+ with tempfile.TemporaryDirectory() as deep:+ os.environ["KYOJIN_HEALTH_DIR"] = str(Path(deep) / ".cache" / "kyojin")+ previous = os.umask(0o022)+ try:+ secure_dir(shared_cache_dir())+ finally:+ os.umask(previous)+ self.assertEqual(_stat.S_IMODE((Path(deep) / ".cache").stat().st_mode), 0o755)+ self.assertEqual(_stat.S_IMODE((Path(deep) / ".cache" / "kyojin").stat().st_mode), 0o755)+ # and every level is traversable by others, which is the point of the exception+ for level in (Path(deep) / ".cache", Path(deep) / ".cache" / "kyojin"):+ self.assertTrue(_stat.S_IMODE(level.stat().st_mode) & 0o001, level)++ def test_the_health_folder_switch_names_the_shared_folder(self):+ """`KYOJIN_HEALTH_DIR` is what makes a folder the shared one, whatever it is called."""+ import stat as _stat+ import tempfile+ from serve_reqlog import secure_dir, shared_cache_dir+ with tempfile.TemporaryDirectory() as tmp:+ custom = Path(tmp) / "shared-state"+ os.environ["KYOJIN_HEALTH_DIR"] = str(custom)+ self.addCleanup(os.environ.pop, "KYOJIN_HEALTH_DIR", None)+ self.assertEqual(shared_cache_dir(), custom)+ previous = os.umask(0o022)+ try:+ secure_dir(shared_cache_dir())+ finally:+ os.umask(previous)+ self.assertEqual(_stat.S_IMODE(custom.stat().st_mode), 0o755) # shared: the umask decides+ previous = os.umask(0)+ try:+ secure_dir(custom / "image-embeddings") # ours: owner-only+ finally:+ os.umask(previous)+ self.assertEqual(_stat.S_IMODE((custom / "image-embeddings").stat().st_mode), 0o700)+ self.assertEqual(_stat.S_IMODE(custom.stat().st_mode), 0o755) # and not touched again++ def test_a_directory_of_ours_inside_the_shared_folder_is_owner_only(self):+ """The exception is the shared folder itself, not everything under it."""+ import stat as _stat+ import tempfile+ from serve_reqlog import secure_dir, shared_cache_dir+ with tempfile.TemporaryDirectory() as tmp:+ os.environ["KYOJIN_HEALTH_DIR"] = str(Path(tmp) / "kyojin")+ self.addCleanup(os.environ.pop, "KYOJIN_HEALTH_DIR", None)+ shared = shared_cache_dir()+ previous = os.umask(0o022)+ try:+ secure_dir(shared) # created the upstream way+ mode_before = _stat.S_IMODE(shared.stat().st_mode)+ secure_dir(shared / "image-embeddings") # ...and then our own directory+ finally:+ os.umask(previous)+ self.assertEqual(_stat.S_IMODE((shared / "image-embeddings").stat().st_mode), 0o700)+ self.assertEqual(_stat.S_IMODE(shared.stat().st_mode), mode_before) # not touched again++ @staticmethod+ def upstream_style_dir(path: Path) -> Path:+ """What `tools/startup_health.py` does before writing its history file."""+ (path / "startup-glm.json").parent.mkdir(parents=True, exist_ok=True)+ return path+def test_the_log_says_whether_the_server_was_writing(self):"""The accounting that separates "the client showed nothing" from "the server sent nothing".diff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.pyindex cc23b27..ba89f2a 100644--- a/tools/strix_halo/serve_reqlog.py+++ b/tools/strix_halo/serve_reqlog.py@@ -12,6 +12,17 @@ writing to a client that did not show it" from "the server had nothing to write"every 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.+**Owner-only files.** The log, and the picture cache the GLM server keeps on disk, hold material derived+from 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+would follow the process umask, `0022` on most systems, and the log would be `0644`.++Two directories are deliberately not this server's to set: one that already exists is **not** touched at+all, and the shared folder the three servers keep state in — `KYOJIN_HEALTH_DIR`, `~/.cache/kyojin` by+default (`shared_cache_dir()`) — is created with the process umask like any other shared directory, the+folders above it included: more than one process writes there, and whichever makes it first must not decide+how 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 belowKYOJIN_REQLOG_HEARTBEAT_S=10 # seconds between 'alive' lines while a job runs@@ -33,6 +44,7 @@ import functoolsimport jsonimport osimport pathlib+import statimport sysimport threadingimport time@@ -44,6 +56,88 @@ FALSE = {"0", "off", "none", "no", "false", ""}TRUE = {"1", "on", "yes", "true"}+def shared_cache_dir() -> pathlib.Path:+ """The folder the servers share for the state they keep between starts.++ `KYOJIN_HEALTH_DIR` names it; `~/.cache/kyojin` is the default. More than one module and more than one+ server write there, so it is created with the process umask like any other shared directory (see+ `secure_dir`) and never tightened."""+ return pathlib.Path(os.environ.get("KYOJIN_HEALTH_DIR") or "~/.cache/kyojin").expanduser()+++def secure_dir(path: "pathlib.Path", mode: int = 0o700) -> None:+ """Create `path`, and the directories above it that are missing, owner-only. An existing one is left+ alone, whatever its mode.++ `mode` applies to every directory this call creates, applied with the umask cleared so the requested+ mode is the mode that lands. The directories in between are created one level at a time, because+ `mkdir(parents=True, mode=...)` does not pass the mode to those (its C implementation calls+ `mkdir(path)` without one), which would leave them at `0777` with the umask cleared.++ `shared_cache_dir()` is the exception, and it is recognised here rather than passed in by the callers:+ that folder is shared, other processes write there, and whichever of them creates it first must not+ decide how it looks, so it is created with the process umask, and so are the folders above it when they+ are missing. Everything else this server creates is its own and gets `mode`: a directory *below* the+ shared folder (`image-embeddings`), and any level of a path that merely passes through it. Files are+ `0600` either way."""+ path = pathlib.Path(path)+ if path.exists() and not path.is_dir():+ # A file where a directory has to go is a broken setup, and the callers report it as such: the+ # disk cache answers "off" with the reason, the log switches itself off with a line on stderr.+ raise NotADirectoryError(f"{path} exists and is not a directory")+ shared = path == shared_cache_dir()+ # every level that is not there yet, deepest first, down to the first one that exists; decided before+ # anything is created, because a directory this call makes must not change the answer+ missing: list[pathlib.Path] = []+ probe = path+ while not probe.exists():+ missing.append(probe)+ if probe.parent == probe: # reached the filesystem root+ break+ probe = probe.parent+ # the shared folder and the levels above it are created the umask way; a directory that merely passes+ # *through* the shared folder, `<shared>/image-embeddings`, keeps `mode`+ previous = os.umask(0)+ try:+ for entry in reversed(missing): # shallowest first, so each parent exists+ if shared and (entry == path or entry in path.parents):+ os.umask(previous) # a shared folder: the umask decides, as for any+ try:+ entry.mkdir(exist_ok=True)+ except FileExistsError: # a race: somebody created it just now+ pass+ os.umask(0)+ continue+ try:+ entry.mkdir(mode=mode)+ except FileExistsError: # a race: somebody else created it just now+ pass+ finally:+ os.umask(previous)+++def secure_open(path: "pathlib.Path", flags: int, mode: int = 0o600) -> int:+ """`os.open` for a file only its owner may read, whatever the process umask is.++ Same trick as `secure_dir`: umask 0 while creating, so the mode lands as asked, and the group and+ other bits are dropped even if the caller asks for more. Opening an existing file does not change its+ mode, so a file that predates the rule is fixed by `restrict` instead."""+ previous = os.umask(0)+ try:+ return os.open(path, flags, mode & ~0o077)+ finally:+ os.umask(previous)+++def restrict(path: "pathlib.Path", mode: int) -> None:+ """Bring an existing file to `mode`, owner-only, if it is not already."""+ try:+ if stat.S_IMODE(os.stat(path).st_mode) & 0o077:+ os.chmod(path, mode)+ except OSError:+ pass++def sanitize(exc: BaseException) -> str:"""Exception type and a short message, safe to log (no request-body snippets)."""if isinstance(exc, json.JSONDecodeError):@@ -383,8 +477,14 @@ class ReqLog:self._fh = Noneif self.enabled and self.path is not None:try:- self.path.parent.mkdir(parents=True, exist_ok=True)- self._fh = self.path.open("a", encoding="utf-8")+ # 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