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