Skip to content

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.

GLM: remove the picture files a killed write left half-written

MangetsuCb706932f37bb
diff --git a/doc/logging.md b/doc/logging.md
index 309cb1f..9c11a47 100644
--- a/doc/logging.md
+++ b/doc/logging.md
@@ -86,7 +86,7 @@ elsewhere. They go through the log's raw `log()` call, and no other server needs
|---|---|---|
| `serve_start` | once, when the server is ready | `model`, `model_id`, `pid`, `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `max_history`, `vision`, `conv_gemm`, `dense_tune`, `moe_fused`, `image_cache_mb`, `image_cache_items`, `image_cache_format`, `image_cache_policy`, `image_cache_dir`, `image_cache_dir_cap_mb`, `image_cache_dir_lock_s`, `heartbeat_s`, `sse_ping_s` |
| `img_cache` | an image request, after `job_done` | `imgs`, `hits`, `misses`, `first_missing`, `entries`, `mb`, `budget_mb`, `item_cap`, `evicted` |
-| (inside `img_cache`) | the same request, as the `disk=` report, when the disk tier is on | `env`, `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors` |
+| (inside `img_cache`) | the same request, as the `disk=` report, when the disk tier is on | `env`, `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors`, `stale_tmp` |
`img_cache` is the line for image sessions: `hits` and `misses` are the embeddings the cache already held
and the ones it re-encoded, and **`first_missing` is the index of the first picture that had to be
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 7b8916a..416c209 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -183,7 +183,10 @@ wherever `KYOJIN_HEALTH_DIR` points) is created with the process umask — its m
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 can
-lose its place to another one.
+lose its place to another one. Each picture is written to `<name>.tmp` and moved onto its name, so a file that
+is there is always complete and a process killed mid-write leaves the `.tmp` behind; the next start removes
+those (keeping any younger than five minutes, which could still be another process's write) and reports how many
+in `stale_tmp`, since they take room the cap does not count.
### Streaming format
`Content-Type: text/event-stream`. Every frame is a bare `data: {...}` line (no `event:`
diff --git a/tools/glm/image_cache_disk.py b/tools/glm/image_cache_disk.py
index 7c74fff..f36a379 100644
--- a/tools/glm/image_cache_disk.py
+++ b/tools/glm/image_cache_disk.py
@@ -36,6 +36,14 @@ from exllamav3.tokenizer.mm_embedding import MMEmbedding, QuantizedMMRows
from serve_reqlog import restrict, secure_dir, secure_open
+# A `.tmp` file is what a half-finished write leaves behind (a killed process, a full disk that was not
+# reported). It is only removed once it is this old: while it is being written it is milliseconds old,
+# and another server of the same directory cannot be ruled out by this module, so a fresh one is left in
+# peace. Five minutes is far beyond one write of one picture (a few milliseconds for a few MiB) and far
+# below the time it takes anyone to notice a crash and start again.
+STALE_TMP_S = 300.0
+
+
def content_key(path: pathlib.Path) -> str:
"""The picture key out of a file name: `<env_fingerprint>.<key>.<mode>.pt`, or `<key>.<mode>.pt`.
@@ -119,12 +127,13 @@ class ImageEmbeddingDisk:
# written_mb / skipped_mb are the numbers to watch when what matters is how much the server writes:
# a batch that would not fit is not written at all, so bytes are never written just to be deleted.
self.stats = {"loaded": 0, "stored": 0, "dropped": 0, "skipped": 0,
- "written_bytes": 0, "skipped_bytes": 0, "errors": 0}
+ "written_bytes": 0, "skipped_bytes": 0, "errors": 0, "stale_tmp": 0}
try:
# 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 = True
+ self.cleanup_stale_tmp()
for entry in self.path.glob("*.pt"):
try:
self._bytes += entry.stat().st_size
@@ -237,6 +246,38 @@ class ImageEmbeddingDisk:
self.stats["loaded"] += 1
return emb
+ def cleanup_stale_tmp(self, grace_s: float = STALE_TMP_S) -> int:
+ """Remove the `.tmp` files a write left behind, older than `grace_s`.
+
+ Every picture is written to `<name>.tmp` and moved onto its final name with `os.replace`, so a
+ `.pt` is always complete and a leftover `.tmp` can only come from a process that died mid-write
+ (`kill -9`, the OOM killer, a power cut). Nothing else looks at those files - not the cap, not the
+ set of pictures present, not the eviction order - so without this they would stay for ever, taking
+ room the cap does not know about.
+
+ A file younger than the grace period is left alone: this module cannot know whether another process
+ is writing it (the servers are one per GPU, but a stale one that was not stopped is a real way to
+ get two). A write of one picture takes milliseconds, so the grace period never covers a live one,
+ and a crash leaves a file that is already minutes old by the time anyone restarts.
+
+ Returns how many were removed; they are counted in `report()` as `stale_tmp`.
+ """
+ try:
+ entries = list(self.path.glob("*.tmp"))
+ except OSError:
+ return 0
+ now, removed = time.time(), 0
+ for entry in entries:
+ try:
+ if now - entry.stat().st_mtime < grace_s:
+ continue # young enough to be somebody's live write
+ entry.unlink()
+ removed += 1
+ except OSError:
+ pass # a file that vanished or cannot be read: not ours
+ self.stats["stale_tmp"] = self.stats.get("stale_tmp", 0) + removed
+ return removed
+
def store(self, evicted: list, mode: str, live: list | set | None = None,
protect: set | None = None) -> None:
"""Write the pictures that just left the memory cache. `evicted` is [(key, embedding, position), ...].
diff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.py
index a75ea7f..8d0ba38 100644
--- a/tools/glm/test_serve_glm_additional.py
+++ b/tools/glm/test_serve_glm_additional.py
@@ -354,6 +354,37 @@ class ImageDiskCacheTests(unittest.TestCase):
entry.rename(entry.with_name(entry.name.split(".", 1)[1]))
self.assertEqual(disk._present(), {"key1", "key2"})
+ def test_a_write_that_was_killed_leaves_a_tmp_the_next_start_removes(self):
+ """One picture is written to `<name>.tmp` and moved onto its name, so a `.pt` is always complete.
+
+ A process that dies mid-write leaves the `.tmp`, which nothing else looks at: not the cap, not the
+ set of pictures present, not the eviction order. It is removed on the next start, but only once it
+ is old enough to be certainly nobody's live write - another process could be writing it, and the
+ servers cannot rule that out from here."""
+ import tempfile
+ import time
+ from image_cache_disk import STALE_TMP_S, ImageEmbeddingDisk
+ with tempfile.TemporaryDirectory() as tmp:
+ stale = pathlib.Path(tmp) / "aaaa.deadbeef.q8.tmp"
+ stale.write_bytes(b"x" * 4096)
+ long_ago = time.time() - STALE_TMP_S - 60
+ os.utime(stale, (long_ago, long_ago))
+ fresh = pathlib.Path(tmp) / "aaaa.cafebabe.q8.tmp"
+ fresh.write_bytes(b"y" * 2048)
+
+ disk = ImageEmbeddingDisk(tmp, max_bytes=64 << 20, start_token=7, end_token=8,
+ env_fingerprint="aaaa")
+ self.assertFalse(stale.exists()) # the leftover of a killed write
+ self.assertTrue(fresh.exists()) # young: possibly somebody's live write
+ self.assertEqual(disk.report()["stale_tmp"], 1)
+ self.assertEqual(disk.report()["files"], 0) # a tmp was never one of the pictures
+
+ os.utime(fresh, (long_ago, long_ago))
+ again = ImageEmbeddingDisk(tmp, max_bytes=64 << 20, start_token=7, end_token=8,
+ env_fingerprint="aaaa")
+ self.assertFalse(fresh.exists())
+ self.assertEqual(again.report()["stale_tmp"], 1)
+
def test_the_disk_cache_needs_a_cap(self):
# `--image-cache-dir-max-gb 0` (the default) is off; any positive value is a real cap, never "unlimited".
self.assertIsNone(serve.make_image_disk(serve.IMAGE_CACHE_DIR_DEFAULT, 0, 300.0))