okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
24.0 KiB475 linesraw
1#!/usr/bin/env python3
2"""tools/dsv41/slot_keep_test.py - the kept conversations of strata-dsv41 (STRATA_DS4_SLOT_KEEP=1): a prompt that does
3not continue the conversation in the model takes the kept one it does continue back, so an agent and its sub-agents
4that take turns on one model read only their new tokens.
5
6    python tools/dsv41/slot_keep_test.py --exe build/strata-dsv41 --pack /data/pack2.00 --ids-dir /tmp/slot-ids
7           [--engine-args "--vram-experts 0 --max-context 20000"] [--turns 3] [--steps ref,old,pin,on,restart,cap]
8
9The prompts are real text (this repo's docs), tokenized through the pack's tokenizer (tools/strata_tokenizer.py, needs
10`regex`) the first time and kept as .ids files in --ids-dir, so a box without `regex` can run the test from a folder
11made elsewhere (--make-only writes just the folder).  Random ids draw near-tie logits, where two greedy runs differ and
12nothing can be compared; real text does not.
13
14Runs of the engine's `--serve` protocol, greedy, spec=0 (the state's position is then exactly the answer's).  Two agents,
15A (parent) and B (a sub-agent), each with its own conversation behind the SAME system prompt and tools, take turns
16A1 B1 A2 B2 ... (the server marks the shared start with pin=N on every request):
17  ref      STRATA_DS4_REUSE=0: every request is a fresh read of its whole prompt.  Its answers are the reference every
18           other run must print, token for token.
19  old      the engine as it was (no pin, no slots): each turn reads its whole prompt again, the other agent having
20           taken the model.  Timings only.
21  pin      the shared start marked, no slots: B goes back to the start A's state holds instead of reading it again.
22  on       the shared start marked and the slots on: a turn that continues a kept conversation reads only its new tokens.
23  restart  a new process on the folder `on` left (QUIT wrote the conversations there): each agent's next turn reads only
24           its new tokens.
25  cap      a folder capped below three conversations' size: it stays under the cap and the newest is kept.
26
27Exit 0: every check passed.  1: a check failed (the reason is printed).  2: the engine did not start or answer, or the
28prompts could not be made.
29"""
30from __future__ import annotations
31
32import argparse
33import json
34import os
35import queue
36import shlex
37import shutil
38import struct
39import subprocess
40import sys
41import tempfile
42import threading
43import time
44from pathlib import Path
45
46HERE = Path(__file__).resolve().parent
47ROOT = HERE.parent.parent
48META_MAGIC = 0x324154454D345344   # "DS4META2" (little endian): a slot's .meta, as src/dsv41/ds4_slotmeta.hpp writes it
49
50
51# ------------------------------------------------------------------------------------------------- prompts
52def corpus_text() -> str:
53    """Real text for the prompts: the repo's README and docs, in a fixed order."""
54    parts = []
55    for p in [ROOT / "README.md", *sorted((ROOT / "docs").glob("*.md"))]:
56        try:
57            parts.append(p.read_text(encoding="utf-8"))
58        except OSError:
59            continue
60    return "\n\n".join(parts)
61
62
63def text_tokens(tok, text: str, salt: str, n: int) -> list[int]:
64    """`n` tokens of `text`, opened by `salt` (so two prompts differ from their first words), repeated if too short."""
65    out: list[int] = []
66    i = 0
67    text = text[:max(4000, n * 7)]   # (a few chars a token; the loop below repeats it if that was too short)
68    while len(out) < n:
69        out += tok.encode(f"{salt} {i}.\n{text}\n", parse_special=False)
70        i += 1
71    return out[:n]
72
73
74def make_tokenizer(pack: str):
75    sys.path.insert(0, str(ROOT / "tools"))
76    import strata_tokenizer as ST   # noqa: E402
77    t = Path(pack) / "tokenizer"
78    vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
79    tokens = [None] * len(vocab)
80    for s, i in vocab.items():
81        tokens[i] = s
82    return ST.Tokenizer(tokens, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),
83                        json.loads((t / "token_type.json").read_text(encoding="utf-8")))
84
85
86def prompts(ids_dir: Path, pack: str, n_sys: int, n_task: int, n_turn: int, turns: int) -> dict[str, list[int]]:
87    """sys (the shared system prompt + tools), taskA, taskB, and turnA1.. turnB<turns> (each new user/tool text)."""
88    want = {"sys": n_sys, "taskA": n_task, "taskB": n_task, **{f"turn{x}{i}": n_turn for x in "AB" for i in range(1, turns + 1)}}
89    ids_dir.mkdir(parents=True, exist_ok=True)
90    have: dict[str, list[int]] = {}
91    tok = None
92    text = None
93    for name, n in want.items():
94        f = ids_dir / f"{name}.ids"
95        ids: list[int] | None = None
96        if f.exists():
97            ids = [int(x) for x in f.read_text().split()]
98            if len(ids) != n:
99                ids = None
100        if ids is None:
101            if tok is None:
102                tok = make_tokenizer(pack)
103                text = corpus_text()
104            salt = {"sys": "System prompt and tools.", "taskA": "Task for agent A."}.get(name, f"Message {name}.")
105            if name == "taskB":
106                salt = "Task for agent B."
107            # (the system prompt is cut from the corpus' start, the others from later in it, so they differ)
108            body = text if name == "sys" else text[len(text) // 3:]
109            ids = text_tokens(tok, body, salt, n)
110            f.write_text(" ".join(str(x) for x in ids))
111        have[name] = ids
112    return have
113
114
115# ------------------------------------------------------------------------------------------------- the .meta file
116def meta_tokens(path: str) -> tuple[list[int], list[int]] | None:
117    """A slot's .meta, as the engine writes it: the magic, its identity (length, bytes), the state's size, its tokens,
118    its checkpoints (count, positions), the magic again.  None: not one of the engine's .meta files, or damaged."""
119    try:
120        with open(path, "rb") as f:
121            data = f.read()
122        m0, il = struct.unpack_from("<QQ", data, 0)
123        if m0 != META_MAGIC:
124            return None
125        _size, nt = struct.unpack_from("<QQ", data, 16 + il)
126        toks = list(struct.unpack_from("<%di" % nt, data, 32 + il))
127        (nc,) = struct.unpack_from("<Q", data, 32 + il + 4 * nt)
128        cks = list(struct.unpack_from("<%dq" % nc, data, 40 + il + 4 * nt))
129        (m1,) = struct.unpack_from("<Q", data, 40 + il + 4 * nt + 8 * nc)
130    except (OSError, struct.error):
131        return None
132    return (toks, cks) if m1 == META_MAGIC else None
133
134
135# ------------------------------------------------------------------------------------------------- the engine
136class Engine:
137    """One `strata-dsv41 --serve` process: its READY line, then `GEN` in, `T` / `DONE` out (a reader thread, so it
138    runs the same on Windows)."""
139
140    def __init__(self, exe: str, args: list[str], env: dict):
141        self.exe, self.args, self.env = exe, args, env
142        self.notes: list[str] = []
143        self.lines: queue.Queue = queue.Queue()
144        self.proc = None
145        self.err_path = ""
146        self.ready = ""
147
148    def _pump(self) -> None:
149        for raw in iter(self.proc.stdout.readline, b""):
150            self.lines.put(raw.decode("utf-8", "replace").strip())
151        self.lines.put(None)
152
153    def _line(self, end: float) -> str:
154        while True:
155            left = end - time.monotonic()
156            if left <= 0:
157                raise RuntimeError("the engine did not answer in time")
158            try:
159                line = self.lines.get(timeout=min(left, 5.0))
160            except queue.Empty:
161                if self.proc.poll() is not None and self.lines.empty():
162                    raise RuntimeError(f"the engine ended (exit {self.proc.returncode})")
163                continue
164            if line is None:
165                raise RuntimeError("the engine's output ended")
166            if line.startswith("NOTE "):
167                self.notes.append(line[5:].strip())
168            return line
169
170    def start(self, timeout: float) -> None:
171        env = dict(os.environ)
172        env.update(self.env)
173        fd, self.err_path = tempfile.mkstemp(prefix="ds4-slots-err-")
174        err = os.fdopen(fd, "wb")
175        self.proc = subprocess.Popen([self.exe, *self.args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err,
176                                     env=env, bufsize=0)
177        err.close()
178        threading.Thread(target=self._pump, daemon=True).start()
179        end = time.monotonic() + timeout
180        while True:
181            line = self._line(end)
182            if line.startswith("READY "):
183                self.ready = line
184                return
185            if line.startswith("ERR "):
186                raise RuntimeError("the engine refused to start: " + line)
187
188    def request(self, prompt: list[int], max_new: int, pin: int = 0, timeout: float = 3600.0) -> dict:
189        keys = f" pin={pin}" if pin else ""
190        self.proc.stdin.write(f"GEN {max_new} spec=0{keys} {','.join(str(t) for t in prompt)}\n".encode())
191        self.proc.stdin.flush()
192        out = {"tokens": [], "reused": None, "prompt_len": len(prompt), "finish": None, "s": 0.0, "ttft_ms": 0.0}
193        t0 = time.monotonic()
194        end = t0 + timeout
195        while True:
196            line = self._line(end)
197            if line.startswith("T "):
198                out["tokens"].append(int(line[2:]))
199            elif line.startswith("ERR "):
200                out["error"] = line[4:]
201                return out
202            elif line.startswith("DONE "):
203                f = line.split()
204                out["generated"], out["prompt"], out["finish"] = int(f[1]), int(f[2]), f[5]
205                out["ttft_ms"] = float(f[3])    # (request start to the first token's logits: the restore + the read)
206                out["decode_ms"] = float(f[4])
207                out["reused"] = int(f[8])
208                out["s"] = time.monotonic() - t0
209                return out
210
211    def quit(self, timeout: float = 300.0) -> None:
212        try:
213            self.proc.stdin.write(b"QUIT\n")
214            self.proc.stdin.flush()
215        except OSError:
216            pass
217        end = time.monotonic() + timeout
218        while time.monotonic() < end:
219            try:
220                line = self.lines.get(timeout=1.0)
221            except queue.Empty:
222                if self.proc.poll() is not None:
223                    break
224                continue
225            if line is None:
226                break
227            if line.startswith("NOTE "):
228                self.notes.append(line[5:].strip())
229        try:
230            self.proc.wait(timeout=max(1.0, end - time.monotonic()))
231        except subprocess.TimeoutExpired:
232            self.proc.kill()
233            raise RuntimeError("the engine did not end after QUIT")
234
235    def stderr_lines(self) -> list[str]:
236        if not self.err_path:
237            return []
238        try:
239            with open(self.err_path, encoding="utf-8", errors="replace") as f:
240                lines = f.read().splitlines()
241            os.unlink(self.err_path)
242        except OSError:
243            return []
244        return lines
245
246
247def run(exe: str, pack: str, engine_args: list[str], slots: str, keep: bool, steps: list[tuple[str, object]],
248        max_new: int, pin: int = 0, reuse: bool = True, slot_gb: float | None = None, load_timeout: float = 3600.0):
249    """One engine process; each step is (name, a function of the answers so far that gives its prompt).  `pin`: the
250    shared start's length sent with every request (what the server sends); `reuse` False: every request is a fresh
251    read of its whole prompt (STRATA_DS4_REUSE=0)."""
252    env = {"STRATA_DS4_SLOT_KEEP": "1" if keep else "0", "STRATA_DS4_SLOT_DIR": slots, "STRATA_DS4_SLOT_MIN": "256",
253           "STRATA_DS4_REUSE": "1" if reuse else "0"}
254    if slot_gb is not None:
255        env["STRATA_DS4_SLOT_GB"] = str(slot_gb)
256    args = ["--pack", pack, "--dspark", "off", "--threads", "on", "--vision", "off", "--expert-profile", "none",
257            *engine_args, "--serve"]
258    eng = Engine(exe, args, env)
259    t0 = time.monotonic()
260    answers: dict[str, dict] = {}
261    try:
262        eng.start(load_timeout)
263        load_s = time.monotonic() - t0
264        for name, make in steps:
265            prompt = make(answers)
266            answers[name] = eng.request(prompt, max_new, pin=pin)
267            if "error" in answers[name]:
268                raise RuntimeError(f"{name}: {answers[name]['error']}")
269    finally:
270        if eng.proc is not None:
271            try:
272                eng.quit()
273            except RuntimeError as e:
274                print("   ", e, flush=True)
275        err = eng.stderr_lines()
276    for line in err:
277        if line.startswith("ds4 slots:") and "failed" in line:
278            raise RuntimeError("the engine: " + line)
279    return answers, eng.notes, load_s
280
281
282def main() -> int:
283    ap = argparse.ArgumentParser(description="the kept conversations: two agents taking turns on one model")
284    ap.add_argument("--pack", required=True)
285    ap.add_argument("--exe", default=str(ROOT / "build" / "strata-dsv41"))
286    ap.add_argument("--ids-dir", default="", help="the prompts' .ids files (made from the docs when missing)")
287    ap.add_argument("--make-only", action="store_true", help="write the .ids files and stop")
288    ap.add_argument("--engine-args", default="", help="more engine flags, e.g. '--vram-experts 0 --max-context 20000'")
289    ap.add_argument("--len-sys", type=int, default=6000, help="the shared system prompt + tools (tokens)")
290    ap.add_argument("--len-task", type=int, default=300, help="each agent's own first message (tokens)")
291    ap.add_argument("--len-turn", type=int, default=150, help="each later message (tokens)")
292    ap.add_argument("--turns", type=int, default=3, help="turns per agent")
293    ap.add_argument("--max-new", type=int, default=24)
294    ap.add_argument("--steps", default="ref,old,pin,on,restart,cap",
295                    help="ref: fresh reads (the reference), old: the engine as it was, pin: the shared start only, "
296                         "on: slots + shared start, restart: a new process on the folder, cap: the folder's cap")
297    ap.add_argument("--keep-dir", default="", help="keep the slot folders here (default: a temp dir, removed)")
298    a_ = ap.parse_args()
299    steps = set(a_.steps.split(","))
300    ids_dir = Path(a_.ids_dir or tempfile.mkdtemp(prefix="slot-ids-"))
301    try:
302        P = prompts(ids_dir, a_.pack, a_.len_sys, a_.len_task, a_.len_turn, a_.turns + 1)
303    except (OSError, ImportError, ValueError) as e:
304        print(f"the prompts cannot be made: {e}", flush=True)
305        return 2
306    if a_.make_only:
307        print(f"prompts written to {ids_dir}", flush=True)
308        return 0
309    if not os.path.exists(a_.exe):
310        print(f"{a_.exe}: no engine - build it first", flush=True)
311        return 2
312    engine_args = shlex.split(a_.engine_args)
313    N, max_new = a_.turns, a_.max_new
314    PIN = len(P["sys"])
315    ok = True
316
317    def check(what: str, cond: bool) -> None:
318        nonlocal ok
319        print(("  ok    " if cond else "  FAIL  ") + what, flush=True)
320        ok = ok and cond
321
322    # the turns A1 B1 A2 B2 ...; an agent's prompt is its previous prompt + the answer it got + the new message
323    # (the answers of `ref` when given, so every arm sends the same prompts byte for byte)
324    def build_steps(ref: dict | None, upto: int = N, start: int = 1, agents: str = "AB"):
325        out = []
326        for i in range(start, upto + 1):
327            for x in agents:
328                def make(ans, x=x, i=i):
329                    src = ref if ref is not None else ans
330                    prompt = P["sys"] + P["task" + x]
331                    for j in range(1, i):
332                        prompt = prompt + src[f"{x}{j}"]["tokens"] + P[f"turn{x}{j}"]
333                    return prompt
334                out.append((f"{x}{i}", make))
335        return out
336
337    def table(ans: dict, upto: int = N) -> tuple[float, float]:
338        for i in range(1, upto + 1):
339            for x in "AB":
340                r = ans[f"{x}{i}"]
341                print(f"        {x}{i}: prompt {r['prompt_len']:>6}  first token {r['ttft_ms'] / 1000:6.2f} s  "
342                      f"reused {r['reused']:>6}", flush=True)
343        wall = sum(ans[f"{x}{i}"]["s"] for i in range(1, upto + 1) for x in "AB")
344        tt = sum(ans[f"{x}{i}"]["ttft_ms"] for i in range(1, upto + 1) for x in "AB") / 1000
345        print(f"        {2 * upto} turns: wall {wall:.1f} s, time to first token (sum) {tt:.1f} s", flush=True)
346        return wall, tt
347
348    def same_tokens(name: str, ans: dict, ref: dict, upto: int = N) -> bool:
349        bad = [f"{x}{i}" for i in range(1, upto + 1) for x in "AB" if ans[f"{x}{i}"]["tokens"] != ref[f"{x}{i}"]["tokens"]]
350        for k in bad:
351            print(f"        {k}: {ans[k]['tokens'][:8]} vs the reference's {ref[k]['tokens'][:8]}", flush=True)
352        return not bad
353
354    tmp = tempfile.mkdtemp(prefix="ds4-slots-") if not a_.keep_dir else a_.keep_dir
355    os.makedirs(tmp, exist_ok=True)
356    dir_on = os.path.join(tmp, "on")
357    ref = None
358    sums: dict[str, tuple[float, float]] = {}
359    try:
360        print(f"prompts: system+tools {len(P['sys'])} tok, task {len(P['taskA'])}, turn {len(P['turnA1'])}; "
361              f"{N} turns per agent, {max_new} new tokens each, pin={PIN}", flush=True)
362        need_ref = bool(steps & {"ref", "pin", "on", "restart", "cap"})
363        if need_ref:
364            print("ref: A1 B1 A2 B2 ... every request a fresh read of its whole prompt (STRATA_DS4_REUSE=0), shared "
365                  "start marked", flush=True)
366            ref, _, load0 = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "ref"), False,
367                                build_steps(None, N + 1), max_new, pin=PIN, reuse=False)
368            print(f"        load {load0:.0f} s", flush=True)
369            sums["ref"] = table(ref)
370            check("ref: nothing is reused", all(ref[f"{x}{i}"]["reused"] == 0 for i in range(1, N + 1) for x in "AB"))
371
372        if "old" in steps:
373            print("old: the engine as it was (no shared start, no slots): the other agent takes the model every turn",
374                  flush=True)
375            old, _, _ = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "old"), False,
376                            build_steps(ref, N) if ref else build_steps(None, N), max_new)
377            sums["old"] = table(old)
378            if ref is not None:
379                print(f"        tokens {'the same as' if same_tokens('old', old, ref) else 'DIFFER from'} the reference's "
380                      "(informational: no shared-start split here)", flush=True)
381
382        if "pin" in steps:
383            print("pin: the shared start marked, no slots: a sub-agent goes back to the start the other left", flush=True)
384            pn, _, _ = run(a_.exe, a_.pack, engine_args, os.path.join(tmp, "pin"), False, build_steps(ref, N), max_new,
385                           pin=PIN)
386            sums["pin"] = table(pn)
387            check(f"pin: the sub-agent's first turn reads only its own task (reused {pn['B1']['reused']} of {PIN})",
388                  pn["B1"]["reused"] == PIN)
389            check(f"pin: every turn prints the reference's tokens ({2 * N} x {max_new})", same_tokens("pin", pn, ref))
390
391        if "on" in steps:
392            print("on: slots on (RAM) and the shared start marked", flush=True)
393            on, notes, _ = run(a_.exe, a_.pack, engine_args, dir_on, True, build_steps(ref, N), max_new, pin=PIN)
394            sums["on"] = table(on)
395            check(f"on: the sub-agent's first turn reads only its own task (reused {on['B1']['reused']} of {PIN})",
396                  on["B1"]["reused"] == PIN)
397            check(f"on: every turn prints the reference's tokens ({2 * N} x {max_new})", same_tokens("on", on, ref))
398            # a turn after the first continues a kept conversation: the whole earlier prompt + answer minus its last
399            # token is reused (the state ends one token short of the answer's last one)
400            full = True
401            for i in range(2, N + 1):
402                for x in "AB":
403                    want = on[f"{x}{i}"]["prompt_len"] - len(P[f"turn{x}{i - 1}"]) - 1
404                    got = on[f"{x}{i}"]["reused"]
405                    if got != want:
406                        full = False
407                        print(f"        {x}{i}: reused {got}, expected {want}", flush=True)
408            check("on: every later turn reuses its whole earlier conversation", full)
409            if "old" in sums:
410                check(f"on: faster to the first token than the old engine ({sums['on'][1]:.1f} s vs {sums['old'][1]:.1f} s)",
411                      sums["on"][1] < sums["old"][1])
412                print(f"        wall x{sums['old'][0] / max(sums['on'][0], 1e-9):.2f}, first token x"
413                      f"{sums['old'][1] / max(sums['on'][1], 1e-9):.2f} against the old engine", flush=True)
414
415        if "restart" in steps:
416            bins = [f for f in os.listdir(dir_on) if f.startswith("slot-") and f.endswith(".bin")] if os.path.isdir(dir_on) else []
417            check(f"restart: the folder holds both agents' conversations ({len(bins)} .bin)", len(bins) == 2)
418            print("restart: each agent's next turn, a new process on the folder", flush=True)
419            rs, notes2, _ = run(a_.exe, a_.pack, engine_args, dir_on, True,
420                                [(f"{x}{N + 1}", build_steps(ref, N + 1, N + 1, x)[0][1]) for x in "AB"], max_new,
421                                pin=PIN)
422            for x in "AB":
423                r = rs[f"{x}{N + 1}"]
424                print(f"        {x}{N + 1}: prompt {r['prompt_len']:>6}  first token {r['ttft_ms'] / 1000:6.2f} s  reused {r['reused']:>6}",
425                      flush=True)
426                want = r["prompt_len"] - len(P[f"turn{x}{N}"]) - 1
427                check(f"restart: {x}{N + 1} reuses its whole conversation ({r['reused']} of {want})", r["reused"] == want)
428                check(f"restart: {x}{N + 1} prints the reference's tokens", r["tokens"] == ref[f"{x}{N + 1}"]["tokens"])
429
430        if "cap" in steps:
431            # three conversations (A, B and an unrelated C) cannot fit under A+B's bytes: the least recently used goes
432            ca = os.path.join(tmp, "cap")
433            seen = {}
434            if os.path.isdir(dir_on):
435                for fn in os.listdir(dir_on):
436                    if fn.endswith(".bin"):
437                        seen[fn] = os.path.getsize(os.path.join(dir_on, fn))
438            if len(seen) == 2:
439                cap_gb = sum(seen.values()) / 2**30 * 1.02
440                c_prompt = P["taskB"] + P["taskA"] + P["sys"][:2000]
441                print(f"cap: A, B, C into a folder capped at {cap_gb:.3f} GB (the bytes of A and B)", flush=True)
442                run(a_.exe, a_.pack, engine_args, ca, True,
443                    [("A1", build_steps(ref, 1)[0][1]), ("B1", build_steps(ref, 1)[1][1]),
444                     ("C1", lambda _: c_prompt)], max_new, pin=PIN, slot_gb=cap_gb)
445                total = sum(os.path.getsize(os.path.join(ca, f)) for f in os.listdir(ca) if f.endswith(".bin"))
446                held = []
447                a_start, b_start = P["sys"] + P["taskA"], P["sys"] + P["taskB"]
448                for fn in sorted(os.listdir(ca)):
449                    if fn.endswith(".meta"):
450                        mt = meta_tokens(os.path.join(ca, fn))
451                        if mt:
452                            t = mt[0]
453                            held.append("C" if t[:len(c_prompt)] == c_prompt else "A" if t[:len(a_start)] == a_start
454                                        else "B" if t[:len(b_start)] == b_start else "?")
455                print(f"        the folder holds {sorted(held)} ({total / 2**20:.1f} MiB of {cap_gb * 1024:.1f} MiB)", flush=True)
456                check("cap: the folder stays under its cap", total <= cap_gb * 2**30)
457                check("cap: the newest conversation (C) is kept", "C" in held)
458                check("cap: the least recently used (A) is gone", "A" not in held)
459            else:
460                print("        (no two conversations in the loop's folder: the cap check needs the on step)", flush=True)
461    except (RuntimeError, OSError) as e:
462        print(f"FAIL: {e}", flush=True)
463        ok = False
464    finally:
465        if not a_.keep_dir:
466            shutil.rmtree(tmp, ignore_errors=True)
467    if sums:
468        print("summary (wall s, sum of first-token s): " + "  ".join(f"{k} {v[0]:.1f}/{v[1]:.1f}" for k, v in sums.items()),
469              flush=True)
470    print("PASS: the kept conversations read on from their state" if ok else "FAIL", flush=True)
471    return 0 if ok else 1
472
473
474if __name__ == "__main__":
475    sys.exit(main())