Disk KV: aligned-staircase churn + slot eviction evict the very checkpoint the next turn needs — long conversations collapse into cold prefill (repro + scripts inlined)

Aperta
#1,186 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
c, python

Direzione di ricerca

Start by reading kv_cache_store_current() and ds4_kvstore_entry_eviction_score() in ds4_kvstore.c, then trace how live and superseding entries affect eviction. Run the inlined repro_checkpoint_churn.py against a fresh server and compare checkpoint retention and prefill behavior. Done means a chosen retention policy prevents useful recovery checkpoints from being evicted under the repro workload without introducing regressions.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

Under agent-style workloads (one long conversation + short auxiliary requests), the disk KV tier is self-defeating in two regimes, with one root cause: when a deeper checkpoint is written, the supersede rule deliberately makes the predecessor the first eviction victim (KV_CACHE_CONTINUED_PREFIX_MIN_FACTOR = 0.05) — but prefix-preserving forks and slot-recovery reloads are exactly the case where the shallower predecessor is the correct restore point.

  • Steady-state regime (requests stay on their live slot): the disk tier is nearly write-only — 98% of 203 checkpoint files written in an 84.9 h production window were never read; 332 GiB written (~93 GiB/day SSD wear).
  • Slot-contention regime (aux requests evict the long conversation's live slot): the disk tier should absorb the miss, but the successor-step eviction above has already removed the needed checkpoints — the conversation falls back to the shallowest survivor and re-prefills ~80–150K tokens every turn (107–195 s/turn in our repro, vs 12–22 s/turn at similar depth with an intact frontier).

The eviction side already has lineage awareness (kv_cache_incoming_supersedes_continued()) — but it draws the wrong conclusion from it ("deeper supersedes shallower" is only true for requests that keep the deeper prefix), and the score function receives the live frontier (live_tokens is passed at ds4_kvstore.c:1058) only to discard it on the second line ((void)live;). We suggest keeping the lineage concept but flipping which member of the lineage survives.

All numbers below are reproducible: one production log + one scripted minimal reproduction — scripts and the repro summary are inlined at the end of this issue; the repro log evidence is in the first comment.

Environment

  • ds4-server @ 0aaea5a (upstream main), macOS, Apple M5 Max, 128 GB RAM
  • Model: Qwen3.8-Flash-Next Q4 (+ vision tower in production; text-only in repro)
  • --ctx 262144 --batched-session 4 --prefill-chunk 4096 --mtp
  • Disk KV defaults: --kv-cache-continued-interval-tokens 10000 (effective step 10240 after rounding to boundary_align_tokens 2048), --kv-cache-min-tokens 512, --kv-cache-cold-max-tokens 30000; budget 32 GiB (production) / 8 GiB (repro)
  • Workload: personal agent harness — one long tool-loop conversation, short aux requests (title generation, translations, summaries) between turns, occasional prefix-preserving forks (undo/retry semantics)

Minimal reproduction (newer, stronger evidence)

repro_checkpoint_churn.py (inlined below, stdlib Python): grows one conversation deterministically to ~158K tokens in ~10K-token turns with 2 unique 0.7–1K-token aux requests between turns, on a fresh server with an 8 GiB disk budget; then replays a truncated prefix + new tail (undo semantics).

Per-turn result (prompt / cached / wall seconds):

turn  7:  61338 / 51200 /  12.2s   <- healthy: aligned staircase reloads
turn  8:  70096 / 51200 /  22.9s   <- cached stalls: newer checkpoints already churned
turn  9:  78859 / 51200 /  36.1s
turn 10:  87622 /  8192 / 107.3s   <- collapse: only the 8192 cold checkpoint survives
turn 11:  96368 /  8192 / 118.0s
...
turn 18: 157692 /  8192 / 194.6s
fork (prefix of turn 11, 96388 tok):  cached=8192, 111.0s   <- ~88K tokens re-prefilled

log_stats: 174 evictions / 69 unique files / 64 zero-hit (93%) / 18 disk hits / staircase evicted at 40960, 51200, …, 153600 (all exactly continued_interval_tokens-aligned). Duration ≈ 28 min of serving.

Write volume needs two measures: the dedup-by-sha, evicted-only figure is 90.4 GiB, but summing the kv cache stored events gives ≈294 GiB written in 28 min — the same aligned depth is re-written 11–12 times because after the live slot is displaced, the re-prefill crosses the same alignment boundary again. Three amplification factors stack up:

  1. the step itself: KV footprint is 33.3 KiB/token (engine's own memory: KV 8.33 GiB / ctx 262144 line), so each 10240 step ≈ 333 MiB;
  2. same-depth rewrites: 10240×11, 20480×11 … 61440×12 store events — 35 GiB of distinct steps becomes 236 GiB of writes (reason=continued alone: 120 stores, 7,587,840 checkpoint tokens);
  3. shallow anchors: 19 reason=cold aux checkpoints — 23,687 tokens of content, 2.8 GiB of writes (per-checkpoint payload floor ~134 MiB, measured on a 681-token checkpoint).

Relative to the final 157,692-token frontier: 48× checkpoint tokens written counting the continued stores alone (7.59M; 58× across all reasons) and 10.2× prefill compute (1.61M prefill tokens, 1598 s of pure prompt time).

The three-step collapse chain, directly in the log
  1. An aux request (681 tokens) is routed to the conversation's slot and evicts its live checkpoint — even though it is marked protected:
11:34:38 slot 3: request reuses nothing; evicting checkpoint (52588 tokens, idle 83 s, protected)
11:34:38 ds4-server: live kv cache miss live=52588 prompt=681 common=40 vision=match reason=token-mismatch
  1. Persisting the evicted state to disk fills the budget, and the eviction scoring deliberately picks the predecessor staircase step first — the supersede penalty (KV_CACHE_CONTINUED_PREFIX_MIN_FACTOR 0.05 + 0.45×decayed-hits, applied by kv_cache_incoming_supersedes_continued()) marks it as "superseded" by the deeper write. That is the self-eviction cycle, and it is policy, not accident:
11:34:38 ds4-server: kv cache evicted reason=disk-cache-full tokens=71680 hits=0 size=2267.88 MiB
11:34:38 ds4-server: kv cache stored tokens=52588 trimmed=0 reason=evict size=1825.67 MiB
  1. The next main-conversation request finds no live slot and no deep checkpoint; the deepest surviving prefix match is the 8192-token cold-start checkpoint (hit 11× in this run), so it re-prefills ~80–150K tokens every turn.

The same cycle is visible purely in the store path, no aux needed: stored tokens=30720 reason=continued at 11:35:12 is immediately preceded by evicted tokens=20480 hits=0 at 11:35:11 — each staircase step evicts its predecessor within ~13 s of being written, i.e. within one turn.

Note the repro also shows the read side works well: 18 disk hits, ~50–260 ms loads, incl. the same 51200 checkpoint hit 3×. The problem is not lookup or load cost — it is retention.

Production observation (84.9 h, same engine, 32 GiB budget)

The other regime — the harness mostly keeps conversations on their live slot, so disk is rarely read:

metric value
checkpoint files written & later evicted 203 unique (264 eviction events)
evicted with hits=0 199 / 203 (98.0%)
GiB written — dedup lower bound (unique evicted) 195.8 GiB
GiB written — by store events (true SSD wear) 332.0 GiB ≈ 93 GiB/day (continued 257.2, evict 64.7, cold 10.1)
disk hits logged in this window 1

(The hits counter in the eviction header is a lifetime count — files in the disk dir persist across server restarts, so hits=8 may include loads logged in earlier windows. The 98% zero-hit share is computed on that lifetime counter, so it is if anything an underestimate of waste.)

The single hit:

kv cache hit text tokens=92160 text=326157 quant=4 key=token-text load=498.9 ms

a 92,160-token checkpoint restored in 499 ms for a request carrying 326,157 bytes of visible text (at the measured 2.4–3.7 bytes/token, roughly the same depth — i.e. a slot-recovery reload, not a deep prefix match). The clean deep-prefix-match evidence is in the repro: turn 8 restored a 51200-token checkpoint into a 70,096-token prompt, 51200→3×, plus the 8192 fallback hit 11×. (Note text= is bytes, not tokens.)

The four files that ever got hits (hits=8 @101307 tok, 6 @190946, 3 @49091, 1 @92160) were still all eventually evicted with reason=disk-cache-full.

Staircase + frontier stores

Deep files (≥40K tokens) split into two kinds: 38 exact 10240-aligned reason=continued steps — one long conversation's staircase — and 11 unaligned frontier stores (reason=evict / key=thinking-visible, written at the exact frontier when a slot is displaced). Notably the three most-reused files (hits 8/6/3) are all unaligned frontier stores: the tier's actual value concentrates in frontier stores while its budget is consumed by the staircase. Same-depth rewrites happen in production too even without full collapse (40960 stored 9×, 51200 8×, …). One 190K conversation therefore wrote ~19 aligned steps + frontier dumps ≈ 60 GiB of distinct checkpoints; a budget that cannot hold two adjacent steps can never benefit from the tier.

Shallow anchor noise

Short aux requests land in the cold-anchor path (--kv-cache-cold-max-tokens, default 30000 — prompts below this get a first-prompt checkpoint; 0 disables the path). Production: 70 reason=cold stores, 80,368 tokens of content → 10.1 GiB of files (payload floor ~129–147 MiB each, measured 134 MiB on a 681-token checkpoint), 146/146 files <20K tokens were zero-hit. And anchors are stickier than continued steps in the scoring (KV_CACHE_ANCHOR_REASON_SCORE_FACTOR = 2.0, ds4_kvstore.c:56) — so single-shot aux checkpoints occupy budget longer than deep recovery checkpoints that actually get reused.

Mechanism trace (function names, not line numbers)

  • kv_cache_store_current() → aligned continued saves every continued_interval_tokens (effective step = interval rounded up to boundary_align_tokens) from min_tokens (512) upward; cold anchors for prompts ≤ cold_max_tokens (30000); reason=evict frontier stores when a slot's state is displaced — which aux requests trigger against the main conversation's slot despite protected.
  • ds4_kvstore_entry_eviction_score() — receives live (the currently growing conversation's tokens, passed through from the store path at ds4_kvstore.c:1058) and discards it: the function body starts (void)live;. The supersede penalty applied by kv_cache_incoming_supersedes_continued() demotes the superseded continued step to ×0.05 score — i.e. the predecessor is intentionally the first victim whenever a deeper step is stored.
  • qwen4_session_save_payload() — payloads include the recurrent-state snapshot, so a deep checkpoint restore is a complete, cheap reload (~0.5 s). All machinery for valuable deep restores exists; only the retention policy is missing.
  • Lookup is prefix-match (repro turn 8: 51200→70096; 8192 fallback ×11), so a sparse set of deep checkpoints per lineage already serves prefix-preserving forks.

What we are asking

Question first: are the linear aligned interval and the supersede rule intended to stay as-is for 262K-context conversations? As shipped, the disk tier is net-negative for our workload — we disabled it entirely in production.

Any of the following would flip the tradeoff positive, roughly in order of patch size:

  1. Use the live parameter that is already passed into ds4_kvstore_entry_eviction_score() — the frontier of the conversation currently growing is right there in the call stack and discarded on the function's second line. A first use could be: never take a supersede penalty on the deepest checkpoint of a live lineage (the one the next turn's recovery would need).
  2. Lineage-deepest retention: exempt the deepest N (1–2) continued checkpoints per lineage from budget eviction (anchors and other reasons unaffected). This directly breaks the self-eviction cycle: the newest step would demote its predecessor's predecessor, never the checkpoint the next turn might need.
  3. Geometric interval per lineage: start at continued_interval_tokens, grow the step (e.g. ×1.5) per checkpoint of the same lineage, so a 200K conversation leaves ~8–10 steps instead of ~19 — cutting amplification factor 1 at the source — and fork recovery stays within ~1.5× of ideal depth. (This also reduces factor 2, since fewer boundaries get re-crossed after displacement.)
  4. Cold-anchor default review: the path has a knob (--kv-cache-cold-max-tokens 0 disables), so this is a defaults/docs question, not a feature: with a ~134 MiB payload floor, a default that checkpoints every prompt ≤30K tokens trades 10 GiB of near-zero-hit files per 3.5 days for what our data shows is single-shot-request reuse we never observed (146/146 zero-hit). Maybe the floor should scale the cutoff, or the docs should warn.
  5. One-line logging improvement: the evicted line hard-codes reason=disk-cache-full and omits the entry's store reason (cold/continued/evict/shutdown), while the stored line omits file=. As-is, a log cannot attribute churn to shallow anchors vs deep steps without correlating sizes. Adding the entry reason to the evict line and file= to the store line would make future tuning discussions data-backed.
Scope note

This targets prefix-preserving forks (undo / retry / resume / branch-again) and slot-recovery reloads: the new prompt keeps the old prefix and changes the tail — exactly what deep checkpoint prefix-match serves. It does not help history-rewriting compression (no shared prefix to match); we reduced those on the harness side separately.

Related

#1170 (keep the checkpoint the next request loads when storing an evict snapshot — same cycle, store-side angle), #986 (age eviction value), #814 (cold checkpoints vs live dumps ordering), #711 (fixed payload cost bias — our ~130 MiB floor), #985 (preserve live KV across tool replay).

Reproduction

repro_checkpoint_churn.py (inlined below): starts a dedicated server (--kv-disk-space-mb 8192, free port, refuses to run if the main port is busy), grows the conversation, interleaves aux requests, performs the fork, stops the server and prints JSON (turn table, log_stats incl. staircase_tokens, fork result). ≈30 min on M5 Max (our run: 28 min, 18 turns to 157,692 tokens).

Observed on 0aaea5a (full summary.json inlined below): staircase 40960–153600 all evicted; 64/69 zero-hit; 90.4 GiB dedup lower bound (≈294 GiB by store events); turns 10–18 pinned to cached=8192 at 107–195 s; fork cached=8192 at 111 s. The server's own startup line confirms the effective parameters: min=512, cold_max=30000, continued=10000, trim=32, align=2048.

analyze_checkpoint_log.py (inlined below) regenerates every production number above from a raw server.log.

Workaround status

We disabled disk KV in production (--kv-disk-dir off) pending a retention policy like the above; live in-memory slot reuse is unaffected. With depth-aware retention we would gladly re-enable it — the reused files (frontier stores hit 8×/6× in production; the 51200 step hit 3× and the 0.5 s restores in the repro) show exactly the value the current policy throws away.


repro_checkpoint_churn.py
#!/usr/bin/env python3
"""Minimal reproduction: disk KV checkpoint churn under a long agent
conversation + short auxiliary requests.

What it does
  1. Starts a dedicated ds4-server with disk KV enabled and a deliberately
     small budget (default 8 GiB) on a free port.
  2. Grows ONE conversation (deterministic filler, like an agent tool loop)
     past --target-tokens (default 150000), interleaving short unique
     auxiliary requests (~1-2K tokens each) between turns, like an agent
     harness doing title/translation/summary side calls.
  3. After the frontier peaks, replays a truncated prefix with a new tail
     (a prefix-preserving fork, i.e. /undo or retry semantics) and measures
     prefill seconds + usage.prompt_tokens_details.cached_tokens.
  4. Stops the server, parses its log + kv dir, prints a JSON summary.

Observed on ds4 0aaea5a (M5 Max, 8 GiB budget, ~158K tokens, 2026-10-06):
  - the long conversation writes one checkpoint per 10240-token aligned
    step ("staircase"); each step evicts its predecessor (hits=0) within
    ~13 s of being written (self-eviction cycle);
  - aux requests evict the conversation's live slot (even while marked
    "protected"), forcing per-turn disk reloads;
  - once the budget can no longer hold two adjacent steps, every turn
    falls back to the shallowest surviving checkpoint (8192 tokens in our
    run, hit 11x) and re-prefills the rest (107-195 s/turn);
  - the fork likewise restores only the 8192 checkpoint (cached_tokens=8192)
    and re-prefills ~88K tokens;
  - the read side itself is fast (18 hits, ~50-260 ms loads) - the problem
    is retention, not lookup.

Prerequisite: the main ds4 server must be stopped (single 128 GB machine,
model alone is ~70 GiB resident). The script refuses to start if the port
is taken or the main engine is still listening on 8000.

Usage:
  python3 repro_checkpoint_churn.py --model /path/to/Qwen3.8-Flash-Next-Q4.gguf \
      [--binary ./ds4-server] [--dry-run] [--out-dir repro-run]

Stdlib only. Python 3.9+.
"""
import argparse
import json
import os
import random
import re
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

WORDS = (
    "the context window cache prefix attention token memory layer head "
    "query value weight gradient batch session checkpoint eviction policy "
    "scheduler decode prefill slot frontier transcript reasoning summary "
    "tool result document segment anchor lineage budget reclaim aligned"
).split()


def filler(seed, n_tokens):
    """Deterministic ~n_tokens worth of English-ish words for seed."""
    rng = random.Random(seed)
    out = []
    for _ in range(int(n_tokens * 0.85)):  # ~1.2 tokens/word safety margin
        out.append(rng.choice(WORDS))
    out.append(f"[filler-seed-{seed}]")
    return " ".join(out)


def port_open(port, host="127.0.0.1"):
    with socket.socket() as s:
        s.settimeout(0.4)
        return s.connect_ex((host, port)) == 0


KV_CFG_RE = re.compile(r"KV disk cache .*continued=(\d+).*align=(\d+)")


def continued_step(text):
    """Token step the engine aligns continued checkpoint saves to.

    The startup line prints the raw option (default 10000), but the store
    rounds it up to boundary_align (default 2048), so a default launch
    writes at multiples of 10240. Deriving it keeps the staircase filter
    correct if the launch changes either option.
    """
    m = KV_CFG_RE.search(text)
    if not m:
        return 10240
    step, align = int(m.group(1)), int(m.group(2))
    if step <= 0:
        return 0
    if align > 0:
        step = -(-step // align) * align
    return step


def chat(url, messages, max_tokens=24):
    body = json.dumps({
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": 0.0,
        "stream": False,
    }).encode()
    req = urllib.request.Request(
        url + "/v1/chat/completions", data=body,
        headers={"Content-Type": "application/json"})
    t0 = time.monotonic()
    try:
        with urllib.request.urlopen(req, timeout=1800) as resp:
            data = json.loads(resp.read())
    except urllib.error.HTTPError as e:
        sys.exit(f"request failed: HTTP {e.code}: "
                 f"{e.read().decode(errors='ignore')[:400]}")
    dt = time.monotonic() - t0
    ch = data["choices"][0]
    usage = data.get("usage", {})
    details = usage.get("prompt_tokens_details") or {}
    return {
        "seconds": round(dt, 3),
        "prompt_tokens": usage.get("prompt_tokens"),
        "cached_tokens": details.get("cached_tokens"),
        "content": (ch.get("message") or {}).get("content") or "",
    }


def wait_ready(log_path, proc, timeout=240):
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if proc.poll() is not None:
            sys.exit(f"server exited early (code {proc.returncode}); "
                     f"see {log_path}")
        try:
            if "listening on" in log_path.read_text(errors="ignore"):
                return
        except FileNotFoundError:
            pass
        time.sleep(1.0)
    sys.exit(f"server not ready in {timeout}s; see {log_path}")


def parse_log(log_path):
    text = Path(log_path).read_text(errors="ignore")
    ev = re.findall(
        r"kv cache evicted reason=(\S+) tokens=(\d+) hits=(\d+) "
        r"size=([\d.]+) MiB file=(\S+)", text)
    hits = re.findall(r"kv cache hit .*tokens=(\d+)", text)
    files = {}
    for r, t, h, s, f in ev:
        files.setdefault(f, []).append((int(t), int(h), float(s)))
    zero = sum(1 for v in files.values() if max(h for _, h, _ in v) == 0)
    gib = sum(max(s for _, _, s in v) for v in files.values()) / 1024
    step = continued_step(text)
    stair = sorted({t for v in files.values()
                    for t, _, _ in v
                    if step > 0 and t >= 4 * step and t % step == 0})
    return {
        "continued_step_tokens": step,
        "eviction_events": len(ev),
        "unique_files_evicted": len(files),
        "zero_hit_files": zero,
        "evicted_gib": round(gib, 1),
        "disk_hits": len(hits),
        "staircase_tokens": stair,
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--binary", default="./ds4-server")
    ap.add_argument("--model", required=True)
    ap.add_argument("--ctx", type=int, default=262144)
    ap.add_argument("--sessions", type=int, default=4)
    ap.add_argument("--port", type=int, default=8010)
    ap.add_argument("--budget-mb", type=int, default=8192)
    ap.add_argument("--target-tokens", type=int, default=150000)
    ap.add_argument("--turn-tokens", type=int, default=10000)
    ap.add_argument("--aux-requests", type=int, default=18)
    ap.add_argument("--fork-at-turn", type=int, default=0,
                    help="fork from this turn's prefix (0 = ~2/3 depth)")
    ap.add_argument("--out-dir", default="repro-run")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    out = Path(args.out_dir).resolve()
    out.mkdir(parents=True, exist_ok=True)
    kv_dir = out / "kv"
    log_path = out / "server.log"

    if not Path(args.binary).exists():
        sys.exit(f"binary not found: {args.binary}")
    if not Path(args.model).exists():
        sys.exit(f"model not found: {args.model}")

    plan = [
        f"start ds4-server on 127.0.0.1:{args.port} "
        f"ctx={args.ctx} sessions={args.sessions} "
        f"kv-disk-dir={kv_dir} budget={args.budget_mb} MiB",
        f"grow one conversation to ~{args.target_tokens} tokens in "
        f"~{args.turn_tokens}-token turns",
        f"interleave {args.aux_requests} unique short (0.8-2.5K tok) "
        "aux requests",
        "fork: replay truncated prefix + new tail, measure cold prefill",
        "stop server, parse log + kv dir, print JSON summary",
    ]
    if args.dry_run:
        print("dry run, planned steps:")
        for p in plan:
            print("  -", p)
        return

    if port_open(args.port):
        sys.exit(f"port {args.port} already in use")
    if port_open(8000):
        sys.exit("main engine is listening on :8000 — stop it first "
                 "(model is ~70 GiB resident; two instances won't fit)")

    kv_dir.mkdir(exist_ok=True)
    cmd = [
        args.binary, "-m", args.model,
        "--ctx", str(args.ctx),
        "--host", "127.0.0.1", "--port", str(args.port),
        "--prefill-chunk", "4096", "--mtp",
        "--batched-session", str(args.sessions),
        "--kv-disk-dir", str(kv_dir),
        "--kv-disk-space-mb", str(args.budget_mb),
    ]
    logf = open(log_path, "wb")
    # ds4-server resolves Metal sources (metal/*.metal) relative to the cwd;
    # run it from the binary's directory like the packaged launchers do.
    proc = subprocess.Popen(cmd, stdout=logf, stderr=subprocess.STDOUT,
                            cwd=os.path.dirname(os.path.abspath(args.binary)))
    url = f"http://127.0.0.1:{args.port}"
    summary = {"cmd": cmd, "turns": [], "aux": [], "fork": None}
    try:
        wait_ready(log_path, proc)
        system = [{"role": "system",
                   "content": "You are a terse assistant. Reply with at "
                              "most a few words."}]
        messages = list(system)
        snapshots = []
        turn = 0
        aux_done = 0
        while True:
            turn += 1
            messages.append({"role": "user",
                             "content": filler(turn, args.turn_tokens)})
            snapshots.append([dict(m) for m in messages])
            r = chat(url, messages, max_tokens=16)
            summary["turns"].append({"turn": turn, **r})
            print(f"turn {turn}: prompt={r['prompt_tokens']} "
                  f"cached={r['cached_tokens']} {r['seconds']}s", flush=True)
            messages.append({"role": "assistant",
                             "content": r["content"] or "ok"})
            if r["prompt_tokens"] is None:
                sys.exit("server reported no usage.prompt_tokens; the "
                         "frontier can't be tracked, aborting instead of "
                         "looping forever")
            if r["prompt_tokens"] >= args.target_tokens:
                break
            # aux noise: unique short requests, like harness side calls
            for i in range(min(2, args.aux_requests - aux_done)):
                a = chat(url, [{"role": "user", "content":
                                f"Translate exactly, output only the "
                                f"translation:\n{filler(900000 + turn * 10 + i, 700 + 400 * (i % 3))}"}],
                         max_tokens=8)
                summary["aux"].append({"turn": turn, "aux": i, **a})
                aux_done += 1

        fork_at = args.fork_at_turn or max(1, int(turn * 0.66))
        prefix = snapshots[min(fork_at, len(snapshots)) - 1]
        time.sleep(3)  # let in-flight checkpoint stores land
        fork_msgs = [dict(m) for m in prefix] + [
            {"role": "user",
             "content": "FORK (undo semantics): summarize the documents "
                        "so far in one sentence."}]
        f = chat(url, fork_msgs, max_tokens=32)
        summary["fork"] = {"from_turn": fork_at, **f}
        print(f"fork from turn {fork_at}: prompt={f['prompt_tokens']} "
              f"cached={f['cached_tokens']} {f['seconds']}s", flush=True)
    finally:
        proc.send_signal(signal.SIGTERM)
        try:
            proc.wait(timeout=60)
        except subprocess.TimeoutExpired:
            proc.kill()
        logf.close()

    summary["log_stats"] = parse_log(log_path)
    kv_files = sorted(kv_dir.glob("*.kv"))
    summary["kv_dir_final"] = {
        "files": len(kv_files),
        "gib": round(sum(f.stat().st_size for f in kv_files) / 2**30, 2),
    }
    (out / "summary.json").write_text(json.dumps(summary, indent=2))
    print("\n=== summary ===")
    print(json.dumps(summary["log_stats"], indent=2))
    print(json.dumps(summary["kv_dir_final"], indent=2))
    print(f"full summary: {out / 'summary.json'}")


if __name__ == "__main__":
    main()

analyze_checkpoint_log.py
#!/usr/bin/env python3
"""Analyze ds4-server logs for disk KV checkpoint economics.

Usage: python3 analyze_checkpoint_log.py <server.log> [<server.log> ...]

Reports, per log:
  - checkpoint files written-and-evicted, zero-hit share
  - total GiB written to disk KV (sum of unique evicted file sizes)
  - disk KV hits ("kv cache hit" lines)
  - eviction reason histogram
  - live KV cache misses (reason histogram, common-prefix distribution)
  - "death staircase": evicted deep checkpoints at 10240-aligned token
    counts (continued-interval saves from one long conversation)
  - zero-hit share per depth bucket

Stdlib only. Deterministic output suitable for pasting into an issue.
"""
import collections
import re
import statistics
import sys

EV_RE = re.compile(
    r"kv cache evicted reason=(\S+) tokens=(\d+) hits=(\d+) "
    r"size=([\d.]+) MiB file=(\S+)")
HIT_RE = re.compile(r"kv cache hit .*tokens=(\d+) text=(\d+).*load=([\d.]+) ms")
MISS_RE = re.compile(
    r"live kv cache miss.* live=(\d+) prompt=(\d+) common=(\d+) "
    r"vision=(\S+) reason=(\S+)")
TS_RE = re.compile(r"^(\d{4}) (\d\d):(\d\d):(\d\d) ")
KV_CFG_RE = re.compile(r"KV disk cache .*continued=(\d+).*align=(\d+)")


def continued_step(text):
    """Token step the engine aligns continued checkpoint saves to.

    The startup line prints the raw option (default 10000), but the store
    rounds it up to boundary_align (default 2048), so a default launch
    writes at multiples of 10240. Reading it from the log keeps the
    staircase filter correct for whatever the launch actually used.
    """
    m = KV_CFG_RE.search(text)
    if not m:
        return 10240
    step, align = int(m.group(1)), int(m.group(2))
    if step <= 0:
        return 0
    if align > 0:
        step = -(-step // align) * align
    return step


def bucket(t):
    if t < 20_000:
        return "<20K"
    if t < 80_000:
        return "20-80K"
    if t < 150_000:
        return "80-150K"
    return ">150K"


def analyze(path):
    text = open(path, errors="ignore").read()
    evs = EV_RE.findall(text)
    hits = HIT_RE.findall(text)
    misses = MISS_RE.findall(text)

    files = collections.defaultdict(list)
    for reason, toks, h, size, f in evs:
        files[f].append((reason, int(toks), int(h), float(size)))

    reasons = collections.Counter(r for r, _, _, _, _ in evs)
    zero = {f: v for f, v in files.items() if max(h for _, _, h, _ in v) == 0}
    total_gib = sum(max(s for _, _, _, s in v) for v in files.values()) / 1024
    zero_gib = sum(max(s for _, _, _, s in v) for v in zero.values()) / 1024

    step = continued_step(text)
    stair = sorted(
        {(t, h, s) for v in files.values() for _, t, h, s in v
         if step > 0 and t >= 4 * step and t % step == 0})

    depth = collections.defaultdict(list)
    for v in files.values():
        t = max(t for _, t, _, _ in v)
        depth[bucket(t)].append(max(h for _, _, h, _ in v))

    common_dist = [int(c) for _, _, c, _, _ in misses]

    ts = [TS_RE.match(l) for l in text.splitlines() if TS_RE.match(l)]
    span = ""
    if ts:
        a, b = ts[0], ts[-1]

        def secs(m):
            day = int(m.group(1)) % 100
            return (day * 86400 + int(m.group(2)) * 3600
                    + int(m.group(3)) * 60 + int(m.group(4)))
        delta = secs(b) - secs(a)
        if delta < 0:  # crossed a month boundary
            delta += 31 * 86400
        span = f"log span >= {delta / 3600:.1f} h"
        if delta >= 3600:  # a per-day rate from a minutes-long log is noise
            span += f", write rate ~{total_gib / (delta / 86400.0):.0f} GiB/day"

    print(f"== {path}")
    print(f"  eviction events: {len(evs)}  unique files: {len(files)}  "
          f"reasons: {dict(reasons)}")
    print(f"  zero-hit files: {len(zero)}/{len(files)} "
          f"({100.0 * len(zero) / max(len(files), 1):.1f}%)")
    print(f"  written (unique evicted): {total_gib:.1f} GiB, "
          f"of which zero-hit: {zero_gib:.1f} GiB")
    if span:
        print(f"  {span}")
    print(f"  disk hits: {len(hits)}")
    for t, txt, load in hits:
        # The log's text= field is the stored prefix in BYTES (ds4_kvstore
        # header text_bytes), not tokens.
        print(f"    hit: restored {t} checkpoint tokens, prompt prefix "
              f"{txt} text bytes, load={load} ms")
    nz = sorted({(h, t) for v in files.values()
                 for _, t, h, _ in v if h > 0}, reverse=True)
    if nz:
        print(f"  nonzero-hit survivors (hits, tokens): {nz[:8]}")
    if stair:
        print(f"  death staircase ({step}-aligned deep evictions, "
              f"tokens/hits/MiB):")
        print(f"    {[(t, h, f'{s:.0f}') for t, h, s in stair[:14]]}")
    for b in ("<20K", "20-80K", "80-150K", ">150K"):
        hs = depth.get(b)
        if hs:
            print(f"  depth {b}: n={len(hs)} "
                  f"zero-hit={sum(1 for h in hs if h == 0)}/{len(hs)}")
    if misses:
        med = int(statistics.median(common_dist)) if common_dist else 0
        one = sum(1 for c in common_dist if c <= 1)
        print(f"  live kv misses: {len(misses)} "
              f"(common<=1: {one}, median common: {med})")
    print()


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    for p in sys.argv[1:]:
        analyze(p)

repro summary.json (sanitized paths)
{
  "cmd": [
    "<ds4-repo>/ds4-server",
    "-m",
    "<ds4-repo>/gguf/Qwen3.8-Flash-Next-Q4.gguf",
    "--ctx",
    "262144",
    "--host",
    "127.0.0.1",
    "--port",
    "8010",
    "--prefill-chunk",
    "4096",
    "--mtp",
    "--batched-session",
    "4",
    "--kv-disk-dir",
    "./repro-run/kv",
    "--kv-disk-space-mb",
    "8192"
  ],
  "turns": [
    {
      "turn": 1,
      "seconds": 10.133,
      "prompt_tokens": 8788,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 2,
      "seconds": 10.578,
      "prompt_tokens": 17551,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 3,
      "seconds": 17.69,
      "prompt_tokens": 26313,
      "cached_tokens": 10240,
      "content": ""
    },
    {
      "turn": 4,
      "seconds": 17.119,
      "prompt_tokens": 35071,
      "cached_tokens": 20480,
      "content": ""
    },
    {
      "turn": 5,
      "seconds": 16.455,
      "prompt_tokens": 43841,
      "cached_tokens": 30720,
      "content": ""
    },
    {
      "turn": 6,
      "seconds": 14.806,
      "prompt_tokens": 52572,
      "cached_tokens": 40960,
      "content": ""
    },
    {
      "turn": 7,
      "seconds": 12.21,
      "prompt_tokens": 61338,
      "cached_tokens": 51200,
      "content": ""
    },
    {
      "turn": 8,
      "seconds": 22.925,
      "prompt_tokens": 70096,
      "cached_tokens": 51200,
      "content": ""
    },
    {
      "turn": 9,
      "seconds": 36.145,
      "prompt_tokens": 78859,
      "cached_tokens": 51200,
      "content": ""
    },
    {
      "turn": 10,
      "seconds": 107.349,
      "prompt_tokens": 87622,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 11,
      "seconds": 118.031,
      "prompt_tokens": 96368,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 12,
      "seconds": 123.502,
      "prompt_tokens": 105140,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 13,
      "seconds": 134.105,
      "prompt_tokens": 113898,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 14,
      "seconds": 157.488,
      "prompt_tokens": 122641,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 15,
      "seconds": 151.548,
      "prompt_tokens": 131398,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 16,
      "seconds": 165.682,
      "prompt_tokens": 140175,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 17,
      "seconds": 180.036,
      "prompt_tokens": 148927,
      "cached_tokens": 8192,
      "content": ""
    },
    {
      "turn": 18,
      "seconds": 194.599,
      "prompt_tokens": 157692,
      "cached_tokens": 8192,
      "content": ""
    }
  ],
  "aux": [
    {
      "turn": 1,
      "aux": 0,
      "seconds": 1.405,
      "prompt_tokens": 682,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 1,
      "aux": 1,
      "seconds": 1.773,
      "prompt_tokens": 1039,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 2,
      "aux": 0,
      "seconds": 1.556,
      "prompt_tokens": 685,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 2,
      "aux": 1,
      "seconds": 1.389,
      "prompt_tokens": 1038,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 3,
      "aux": 0,
      "seconds": 1.753,
      "prompt_tokens": 700,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 3,
      "aux": 1,
      "seconds": 1.537,
      "prompt_tokens": 1041,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 4,
      "aux": 0,
      "seconds": 1.843,
      "prompt_tokens": 685,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 4,
      "aux": 1,
      "seconds": 1.532,
      "prompt_tokens": 1037,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 5,
      "aux": 0,
      "seconds": 2.005,
      "prompt_tokens": 689,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 5,
      "aux": 1,
      "seconds": 1.539,
      "prompt_tokens": 1041,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 6,
      "aux": 0,
      "seconds": 1.999,
      "prompt_tokens": 682,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 6,
      "aux": 1,
      "seconds": 1.408,
      "prompt_tokens": 1037,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 7,
      "aux": 0,
      "seconds": 2.2,
      "prompt_tokens": 684,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 7,
      "aux": 1,
      "seconds": 1.691,
      "prompt_tokens": 1021,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 8,
      "aux": 0,
      "seconds": 2.156,
      "prompt_tokens": 685,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 8,
      "aux": 1,
      "seconds": 1.56,
      "prompt_tokens": 1038,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 9,
      "aux": 0,
      "seconds": 2.392,
      "prompt_tokens": 681,
      "cached_tokens": 0,
      "content": ""
    },
    {
      "turn": 9,
      "aux": 1,
      "seconds": 1.713,
      "prompt_tokens": 1030,
      "cached_tokens": 0,
      "content": ""
    }
  ],
  "fork": {
    "from_turn": 11,
    "seconds": 111.04,
    "prompt_tokens": 96388,
    "cached_tokens": 8192,
    "content": ""
  },
  "log_stats": {
    "continued_step_tokens": 10240,
    "eviction_events": 174,
    "unique_files_evicted": 69,
    "zero_hit_files": 64,
    "evicted_gib": 90.4,
    "disk_hits": 18,
    "staircase_tokens": [
      40960,
      51200,
      61440,
      71680,
      81920,
      92160,
      102400,
      112640,
      122880,
      133120,
      143360,
      153600
    ]
  },
  "kv_dir_final": {
    "files": 2,
    "gib": 5.48
  }
}
Lingua principale
C
Stelle
24.4k
Fork
2.4k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di antirez/ds4

Tutte le issue di antirez/ds4

Issue simili

Altre issue su C

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.