okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cded60248
main
1"""Data-parallel replicas (serve/replicas.py): the config, the router, and the real Service over HTTP with two fake 2engines (the fake of test_parallel.py) behind a ReplicaEngine.""" 3import json 4import sys 5import tempfile 6import threading 7import time 8import unittest 9import urllib .request 10from pathlib import Path 11from unittest import mock 12 13from serve .frontend import ChatTemplate 14from serve .replicas import (BLOCK ,ReplicaConfigError ,ReplicaEngine ,Router ,cpu_sets ,gpu_groups ,remove_arena , 15replica_cfg ,shared_arena_plan ,sweep_stale_arenas ) 16from serve .server import ByteTokenizer ,Service ,StrataEngine ,serve 17from serve .test_parallel import FAKE_BATCH 18 19 20class Config (unittest .TestCase ): 21def test_a_number_cuts_the_gpu_list (self ): 22self .assertEqual (gpu_groups ({"gpu" : [0 ,1 ,2 ,3 ],"replicas" :2 }), [[0 ,1 ], [2 ,3 ]]) 23self .assertEqual (gpu_groups ({"gpu" :"0,1,2,3" ,"replicas" :4 }), [[0 ], [1 ], [2 ], [3 ]]) 24self .assertEqual (gpu_groups ({"gpu" : [0 ,1 ],"replicas" :1 }), []) 25self .assertEqual (gpu_groups ({"gpu" : [0 ,1 ]}), []) 26 27def test_named_groups (self ): 28self .assertEqual (gpu_groups ({"replicas" : [{"gpus" : [0 ,1 ]}, {"gpus" : [2 ]}]}), [[0 ,1 ], [2 ]]) 29self .assertEqual (gpu_groups ({"replicas" : [{"gpus" : [0 ,1 ]}]}), []) 30 31def test_mistakes_are_said (self ): 32for cfg in ({"gpu" : [0 ,1 ,2 ],"replicas" :2 }, {"replicas" :2 }, {"replicas" :"2" }, 33 {"replicas" : [{"gpus" : [0 ,1 ]}, {"gpus" : [1 ,2 ]}]}, {"replicas" : [{"gpus" : []}, {"gpus" : [1 ]}]}): 34with self .assertRaises (ReplicaConfigError ,msg = cfg ): 35gpu_groups (cfg ) 36 37def test_replica_cfg (self ): 38cfg = {"gpu" : [0 ,1 ,2 ,3 ],"args" : ["--x" ],"log" :"/l/strata.log" ,"hip_ordinal" :1 ,"env" : {"A" :"1" }, 39"expert_profile_save" :"/p/prof.bin" , 40"replicas" : [{"gpus" : [0 ,1 ],"env" : {"B" :2 }}, {"gpus" : [2 ,3 ],"args" : ["--y" ]}]} 41a ,b = replica_cfg (cfg ,0 , [0 ,1 ]),replica_cfg (cfg ,1 , [2 ,3 ]) 42self .assertEqual ((a ["gpu" ],b ["gpu" ]), ([0 ,1 ], [2 ,3 ])) 43self .assertEqual ((a ["log" ],b ["log" ]), ("/l/strata.r0.log" ,"/l/strata.r1.log" )) 44self .assertEqual (a ["env" ], {"A" :"1" ,"B" :"2" }) 45self .assertEqual (b ["args" ], ["--x" ,"--y" ]) 46self .assertNotIn ("replicas" ,a ) 47self .assertNotIn ("hip_ordinal" ,a ) 48self .assertEqual (a ["expert_profile_save" ],"/p/prof.r0.bin" ) 49self .assertEqual (cfg ["args" ], ["--x" ])# the original is untouched 50self .assertEqual (replica_cfg ({"gpu" : [0 ,1 ],"args" : []},0 , [3 ])["gpu" ],3 ) 51 52def test_cpu_sets_off (self ): 53self .assertIsNone (cpu_sets (2 ,enabled = False )) 54self .assertIsNone (cpu_sets (1 )) 55 56 57class Routing (unittest .TestCase ): 58def test_matched_prefix_per_replica (self ): 59r = Router (3 ) 60a = list (range (BLOCK * 4 )) 61r .note (0 ,a ) 62r .note (1 ,a [:BLOCK * 2 ]) 63self .assertEqual (r .matched (a + [9 ]* 70 ), [BLOCK * 4 ,BLOCK * 2 ,0 ]) 64self .assertEqual (r .matched ([7 ]* 200 ), [0 ,0 ,0 ]) 65r .forget (0 ) 66self .assertEqual (r .matched (a ), [0 ,BLOCK * 2 ,0 ]) 67 68def test_the_index_is_bounded (self ): 69r = Router (2 ,cap = 10 ) 70for i in range (50 ): 71r .note (i % 2 , [i ]* (BLOCK * 2 )) 72self .assertLessEqual (len (r .blocks ),10 ) 73 74 75class FakeEngine : 76def __init__ (self ,n = 4 ): 77self .batch ,self .up = n ,True 78self .max_context = 4096 79self .info = {} 80self .last = {} 81 82def alive (self ): 83return self .up 84 85def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 86yield 7 87 88 89class RouteChoice (unittest .TestCase ): 90def test_least_loaded_then_affinity (self ): 91e = ReplicaEngine ([FakeEngine (),FakeEngine ()],load_tokens = 3000 ) 92picks = [e .route ([i ]* 100 )for i in range (4 )]# nothing cached: spread 93self .assertEqual (sorted (picks ), [0 ,0 ,1 ,1 ]) 94ids = list (range (BLOCK * 8 )) 95e .inflight = [0 ,0 ] 96k = e .route (ids ) 97e .router .note (k ,ids ) 98e .inflight = [0 ,0 ] 99self .assertEqual (e .route (ids + [5 ]* 10 ),k )# the conversation goes back 100e .inflight = [0 ,0 ] 101e .inflight [k ]= 1 # 512 tokens held < 3000 per running request 102self .assertNotEqual (e .route (ids + [5 ]* 10 ),k ) 103 104def test_a_long_prefix_outweighs_load (self ): 105e = ReplicaEngine ([FakeEngine (),FakeEngine ()],load_tokens = 3000 ) 106ids = list (range (BLOCK * 200 ))# 12,800 tokens held on replica 0 107e .router .note (0 ,ids ) 108e .inflight = [2 ,0 ] 109self .assertEqual (e .route (ids + [1 ]),0 ) 110e .inflight = [5 ,0 ] 111self .assertEqual (e .route (ids + [1 ]),1 ) 112 113def test_a_dead_replica_is_skipped (self ): 114a ,b = FakeEngine (),FakeEngine () 115e = ReplicaEngine ([a ,b ]) 116e .heal = lambda :None 117ids = list (range (BLOCK * 3 )) 118e .router .note (0 ,ids ) 119a .up = False 120self .assertEqual (e .route (ids ),1 ) 121b .up = False 122self .assertEqual (e .route (ids ),- 1 ) 123 124def test_nonfinite_forgets_the_replica (self ): 125"""#879: after DONE ... nonfinite the engine holds no conversation: the router forgets that replica.""" 126from serve .server import EngineNonFinite 127 128class NonFinite (FakeEngine ): 129def generate (self ,ids ,max_new ,sampling ,cancel ): 130yield 7 131raise EngineNonFinite ("the engine's logits became non-finite (#879)" ) 132 133e = ReplicaEngine ([NonFinite (),NonFinite ()]) 134other ,ids = [9 ]* (BLOCK * 4 ),list (range (BLOCK * 3 )) 135e .router .note (0 ,other ) 136e .router .note (1 ,other ) 137k = 0 138e .inflight [k ]+= 1 # as route() counts it 139with mock .patch .object (e ,"route" ,return_value = k ): 140with self .assertRaises (EngineNonFinite ): 141list (e .generate (ids ,10 , {},threading .Event ())) 142self .assertEqual (e .router .matched (ids )[k ],0 ) 143self .assertEqual (e .router .matched (other )[k ],0 )# its older conversations too 144self .assertEqual (e .router .matched (other )[1 - k ],len (other )) 145self .assertEqual (e .inflight [k ],0 ) 146 147def test_batch_is_the_sum (self ): 148self .assertEqual (ReplicaEngine ([FakeEngine (4 ),FakeEngine (4 )]).batch ,8 ) 149self .assertEqual (ReplicaEngine ([FakeEngine (0 ),FakeEngine (0 )]).batch ,2 ) 150 151def test_selected_replica_is_reported_for_solo_requests_too (self ): 152engine = ReplicaEngine ([FakeEngine (),FakeEngine ()]) 153engine .inflight [0 ]= 1 154cancel = threading .Event () 155selected = [] 156cancel ._strata_replica_selected = selected .append 157self .assertEqual (list (engine .generate ([1 ,2 ],1 , {},cancel )), [7 ]) 158self .assertEqual (selected , [1 ]) 159 160 161class ReplicaService (unittest .TestCase ): 162def start (self ,slots = 4 ,n = 2 ): 163import serve .server as server 164self .tmp = tempfile .TemporaryDirectory () 165script = Path (self .tmp .name )/ "fake_strata.py" 166script .write_text (FAKE_BATCH ,encoding = "utf-8" ) 167real = server .subprocess .Popen 168self .logs = [Path (self .tmp .name )/ f"r { i } .log" for i in range (n )] 169engines = [] 170for i in range (n ): 171extra = (["--batch" ,str (slots )]if slots else [])+ ["--log" ,str (self .logs [i ])] 172with mock .patch .object (server .subprocess ,"Popen" , 173lambda cmd ,** kw :real ([sys .executable ,str (script ),* cmd [1 :]],** kw )): 174engines .append (StrataEngine ("strata" ,extra )) 175self .engine = ReplicaEngine (engines ) 176self .svc = Service (self .engine ,ByteTokenizer (),ChatTemplate (Path (__file__ ).parent / "chat_template.jinja" )) 177self .httpd = serve (self .svc ,port = 0 ) 178self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 179 180def tearDown (self ): 181if getattr (self ,"httpd" ,None ): 182self .httpd .shutdown () 183self .httpd .server_close () 184if getattr (self ,"engine" ,None ): 185self .engine .unload () 186if getattr (self ,"tmp" ,None ): 187self .tmp .cleanup () 188 189def post (self ,messages ,max_tokens = 64 ): 190body = {"messages" :messages ,"max_tokens" :max_tokens ,"reasoning_effort" :"none" } 191req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 192headers = {"Content-Type" :"application/json" }) 193with urllib .request .urlopen (req ,timeout = 60 )as r : 194return json .loads (r .read ().decode ())["choices" ][0 ]["message" ]["content" ] 195 196def chat (self ,text ,max_tokens = 64 ): 197return self .post ([{"role" :"user" ,"content" :text }],max_tokens ) 198 199def served (self ): 200return [sum (1 for l in p .read_text ().splitlines ()if l .split ()[0 ]in ("GEN" ,"BGEN" ))if p .exists ()else 0 201for p in self .logs ] 202 203def burst (self ,prompts ): 204out = [None ]* len (prompts ) 205 206def one (i ): 207out [i ]= self .chat (prompts [i ]) 208ts = [threading .Thread (target = one ,args = (i ,))for i in range (len (prompts ))] 209for t in ts : 210t .start () 211for t in ts : 212t .join () 213return out 214 215def test_requests_spread_over_both_and_answers_are_the_solo_answer (self ): 216self .start () 217solo = self .chat ("hello there" ) 218before = self .served () 219out = self .burst ([f"request number { i } " + "x" * 300 for i in range (6 )]) 220got = [b - a for a ,b in zip (before ,self .served ())] 221self .assertTrue (all (g >= 2 for g in got ),got ) 222self .assertEqual (set (out ), {solo }) 223 224def test_metrics_and_status_see_all_slots (self ): 225self .start () 226self .assertEqual (self .svc .v1_status ()["concurrency" ]["serving" ],8 ) 227m = self .svc .metrics () 228self .assertEqual (len (m ["live" ]["slots" ]),8 ) 229self .assertEqual ([r ["replica" ]for r in m ["live" ]["replicas" ]], [0 ,1 ]) 230self .assertEqual (m ["engine" ]["replicas" ],2 ) 231 232def test_terminal_telemetry_correlates_second_replica_without_global_sample_claim (self ): 233self .start () 234self .svc .replica_gpu_groups = [[0 ,1 ], [2 ,3 ]] 235second = self .engine .engines [1 ] 236request_id = "abcdef012345" 237second .slot_live [1 ]= {"request_id" :request_id ,"state" :"reading" ,"prompt_tokens" :100 , 238"prompt_read" :12 ,"generated" :0 ,"started" :time .time (),"first_token" :None } 239first = self .engine .engines [0 ] 240first .terminal_batch_sample = {"windows" :2 ,"processed_rows" :8 ,"active_rows" :4 , 241"elapsed_ms" :1000 ,"observed_monotonic" :time .monotonic ()} 242second .terminal_batch_sample = {"windows" :2 ,"processed_rows" :6 ,"active_rows" :4 , 243"elapsed_ms" :1000 ,"observed_monotonic" :time .monotonic ()} 244first .terminal_stage_sample = {"elapsed_us" :1_000_000 ,"in_flight_us" : [800_000 ,600_000 ], 245"observed_monotonic" :time .monotonic ()} 246second .terminal_stage_sample = {"elapsed_us" :1_000_000 ,"in_flight_us" : [700_000 ,500_000 ], 247"observed_monotonic" :time .monotonic ()} 248self .svc .backend = "cuda" 249for child ,cards in ((first , [0 ,1 ]), (second , [2 ,3 ])): 250child .spawn = (* child .spawn [:4 ], {"CUDA_DEVICE_ORDER" :"PCI_BUS_ID" , 251"CUDA_VISIBLE_DEVICES" :"," .join (map (str ,cards ))}, 252* child .spawn [5 :]) 253child .terminal_stages = [ 254 {"stage" :0 ,"layer_start" :0 ,"layer_end" :19 ,"engine_ordinal" :0 }, 255 {"stage" :1 ,"layer_start" :20 ,"layer_end" :39 ,"engine_ordinal" :1 }] 256with self .svc .status_lock : 257self .svc .terminal_requests [request_id ]= {"id" :request_id ,"state" :"waiting" , 258"queued_at" :time .time (),"admitted_at" :time .time (), 259"prompt_tokens" :100 } 260with urllib .request .urlopen (self .base + "/v1/telemetry" ,timeout = 10 )as response : 261snapshot = json .load (response ) 262slot = snapshot ["work" ]["slots" ][5 ] 263self .assertEqual ((slot ["slot" ],slot ["replica" ],slot ["group" ],slot ["request_id" ]), 264 (5 ,1 ,1 ,request_id )) 265request = snapshot ["work" ]["requests" ][0 ] 266self .assertEqual ((request ["slot" ],request ["replica" ],request ["group" ],request ["state" ]), 267 (5 ,1 ,1 ,"reading" )) 268self .assertEqual (snapshot ["work" ]["groups" ],2 ) 269self .assertIsNone (snapshot ["work" ]["effective_rows_window" ]) 270self .assertEqual ([(row ["replica" ],row ["batch_sample_rows" ],row ["batch_sample_active_rows" ]) 271for row in snapshot ["work" ]["replica_batches" ]], [(0 ,8 ,4 ), (1 ,6 ,4 )]) 272self .assertEqual ([(row ["replica" ],row ["stage_in_flight_us" ]) 273for row in snapshot ["work" ]["replica_stage_samples" ]], 274 [(0 , [800_000 ,600_000 ]), (1 , [700_000 ,500_000 ])]) 275self .assertNotIn ("stage_in_flight_us" ,snapshot ["work" ]) 276self .assertEqual (snapshot ["topology" ]["stages" ], []) 277self .assertEqual (snapshot ["topology" ]["replica_stages" ][1 ]["stages" ][1 ]["device_index" ],3 ) 278self .assertEqual (snapshot ["topology" ]["replica_devices" ], 279 [{"replica" :0 ,"devices" : [0 ,1 ]}, {"replica" :1 ,"devices" : [2 ,3 ]}]) 280second .spawn = (* second .spawn [:4 ], {"CUDA_DEVICE_ORDER" :"PCI_BUS_ID" , 281"CUDA_VISIBLE_DEVICES" :"9,3" },* second .spawn [5 :]) 282with urllib .request .urlopen (self .base + "/v1/telemetry" ,timeout = 10 )as response : 283mismatch = json .load (response ) 284self .assertIsNone (mismatch ["topology" ]["replica_stages" ][1 ]["stages" ][0 ]["device_index" ]) 285self .assertEqual (mismatch ["topology" ]["replica_stages" ][1 ]["stages" ][1 ]["device_index" ],3 ) 286 287def test_engines_without_slots_run_one_each_at_once (self ): 288self .start (slots = 0 ) 289out = self .burst (["a" * 40 ,"b" * 40 ]) 290self .assertEqual (self .served (), [1 ,1 ]) 291self .assertEqual (len (set (out )),1 ) 292 293def test_a_conversation_goes_back_to_its_replica (self ): 294self .start () 295first = "begin " + "lorem ipsum " * 40 296reply = self .chat (first ) 297k = self .served ().index (1 ) 298self .post ([{"role" :"user" ,"content" :first }, {"role" :"assistant" ,"content" :reply }, 299 {"role" :"user" ,"content" :"and then?" }],16 ) 300self .assertEqual (self .served ()[k ],2 ) 301 302def test_a_replica_that_died_is_skipped (self ): 303self .start () 304self .engine .heal = lambda :None 305self .engine .engines [0 ].proc .kill () 306self .engine .engines [0 ].proc .wait () 307self .assertTrue (self .engine .alive ()) 308for i in range (3 ): 309self .assertIn ("ok, done." ,self .chat (f"after the loss { i } " )) 310self .assertEqual (self .served ()[1 ],3 ) 311 312 313class SharedArena (unittest .TestCase ): 314"""The opt-in shared expert arena of the replicas (shared_arena_plan): when it is used, when it is not, what a stale 315file means.""" 316CFG = {"replica_shared_arena" :True ,"args" : ["--pack" ,"/p" ],"gpu" : [0 ,1 ]} 317 318def plan (self ,cfg = None ,n = 2 ,tmp = None ,** kw ): 319return shared_arena_plan (cfg or self .CFG ,n ,shm = tmp ,platform = kw .pop ("platform" ,"linux" ), 320environ = kw .pop ("environ" , {}),free_bytes = kw .pop ("free_bytes" ,100 << 30 ), 321use_memfd = kw .pop ("use_memfd" ,False ),** kw ) 322 323def test_off_by_default_and_for_one_engine (self ): 324with tempfile .TemporaryDirectory ()as d : 325self .assertEqual (self .plan ({"args" : []},tmp = d ), (None ,"" )) 326self .assertEqual (self .plan (n = 1 ,tmp = d ), (None ,"" )) 327self .assertEqual (self .plan ({"args" : []},tmp = d ,environ = {"STRATA_REPLICA_SHARED_ARENA" :"0" }), (None ,"" )) 328 329def test_on_by_config_or_environment (self ): 330with tempfile .TemporaryDirectory ()as d : 331path ,note = self .plan (tmp = d ) 332self .assertTrue (path and path .startswith (d )and path .endswith (".bin" ),path ) 333self .assertIn ("once" ,note ) 334path2 ,_ = self .plan ({"args" : []},tmp = d ,environ = {"STRATA_REPLICA_SHARED_ARENA" :"1" }) 335self .assertTrue (path2 ) 336self .assertEqual (path ,path2 )# (one server: one file) 337 338def test_windows_gets_a_named_section (self ): 339with tempfile .TemporaryDirectory ()as d : 340path ,note = self .plan (tmp = d ,platform = "win32" ) 341self .assertTrue (path and path .startswith ("win:Local" )and "strata-replicas-" in path ,path ) 342self .assertIn ("Windows section" ,note ) 343remove_arena (path )# (nothing to remove: harmless) 344 345def test_only_where_there_is_an_arena_to_share (self ): 346with tempfile .TemporaryDirectory ()as d : 347self .assertIsNone (self .plan (tmp = d ,platform = "darwin" )[0 ]) 348for flag in ("--mmap-experts" ,"--resident-experts" ,"--resident-budget-gib" ,"--shared-expert-arena" ): 349self .assertIsNone (self .plan ({** self .CFG ,"args" : ["--pack" ,"/p" ,flag ]},tmp = d )[0 ],flag ) 350self .assertIsNone (self .plan ({** self .CFG ,"replicas" : [{"gpus" : [0 ],"args" : ["--mmap-experts" ]}, {"gpus" : [1 ]}]},tmp = d )[0 ]) 351self .assertIsNone (self .plan ({** self .CFG ,"arch" :"deepseek41" },tmp = d )[0 ]) 352 353def test_no_room_or_no_shm_says_so_and_falls_back (self ): 354with tempfile .TemporaryDirectory ()as d : 355path ,note = self .plan (tmp = d ,free_bytes = 2 << 30 ) 356self .assertIsNone (path ) 357self .assertIn ("2.0 GiB free" ,note ) 358path ,note = self .plan (tmp = d + "/nope" ) 359self .assertIsNone (path ) 360self .assertIn ("not usable" ,note ) 361 362def test_a_stale_file_goes_a_live_one_stays (self ): 363with tempfile .TemporaryDirectory ()as d : 364uid = __import__ ("os" ).getuid ()if hasattr (__import__ ("os" ),"getuid" )else 0 365dead = Path (d )/ f"strata-replicas- { uid } -2999999.bin" 366live = Path (d )/ f"strata-replicas- { uid } - { __import__ ( 'os' ). getpid () } .bin" 367other = Path (d )/ f"strata-replicas- { uid + 1 } -2999999.bin" 368junk = Path (d )/ "strata-replicas-x.bin" 369for f in (dead ,live ,other ,junk ): 370f .write_bytes (b"x" ) 371with mock .patch ("serve.replicas._pid_alive" ,side_effect = lambda pid :pid != 2999999 ): 372gone = sweep_stale_arenas (d ,uid ) 373self .assertEqual (gone , [dead .name ]) 374self .assertFalse (dead .exists ()) 375self .assertTrue (live .exists ()and other .exists ()and junk .exists ()) 376 377@ unittest . skipUnless (hasattr(__import__( "os" ), "memfd_create" ) and sys . platform . startswith ( "linux" ), "Linux memfd" ) 378def test_a_memfd_is_not_limited_by_dev_shm_and_is_closed_at_the_end (self ): 379import os 380path ,note = shared_arena_plan (self .CFG ,2 ,platform = "linux" ,environ = {},free_bytes = 100 << 30 ,use_memfd = True ) 381self .assertTrue (path and path .startswith (f"/proc/ { os . getpid () } /fd/" ),path ) 382fd = int (path .rsplit ("/" ,1 )[1 ]) 383os .ftruncate (fd ,1 << 20 ) 384self .assertEqual (os .fstat (fd ).st_size ,1 << 20 ) 385with open (path ,"r+b" )as other :# (how an engine opens it) 386other .seek (100 ) 387other .write (b"x" ) 388remove_arena (path ) 389with self .assertRaises (OSError ): 390os .fstat (fd ) 391remove_arena (path )# (twice: harmless) 392 393@ unittest . skipUnless (hasattr(__import__( "os" ), "memfd_create" ) and sys . platform . startswith ( "linux" ), "Linux memfd" ) 394def test_a_memfd_arena_warns_when_the_engines_will_not_all_fit (self ): 395cfg = {** self .CFG ,"model_name" :"qwen3.8-flash-next-iq3_s" } 396path ,note = shared_arena_plan (cfg ,2 ,platform = "linux" ,environ = {},free_bytes = 57 << 30 ,use_memfd = True ) 397try : 398self .assertTrue (path ) 399self .assertIn ("WARNING" ,note ) 400self .assertIn ("may not fit" ,note ) 401finally : 402remove_arena (path ) 403path ,note = shared_arena_plan (cfg ,2 ,platform = "linux" ,environ = {},free_bytes = 120 << 30 ,use_memfd = True ) 404try : 405self .assertNotIn ("WARNING" ,note ) 406finally : 407remove_arena (path ) 408 409def test_a_memfd_needs_free_ram (self ): 410path ,note = shared_arena_plan (self .CFG ,2 ,platform = "linux" ,environ = {},free_bytes = 2 << 30 ,use_memfd = True ) 411self .assertIsNone (path ) 412self .assertIn ("2.0 GiB of RAM" ,note ) 413 414def test_removing_twice_or_nothing_is_harmless (self ): 415with tempfile .TemporaryDirectory ()as d : 416f = Path (d )/ "a.bin" 417f .write_bytes (b"x" ) 418remove_arena (str (f )) 419remove_arena (str (f )) 420remove_arena (None ) 421self .assertFalse (f .exists ()) 422 423def test_the_replica_engine_unlinks_the_file_at_close (self ): 424with tempfile .TemporaryDirectory ()as d : 425f = Path (d )/ "a.bin" 426f .write_bytes (b"x" ) 427 428class E : 429def close (self ): 430pass 431r = ReplicaEngine ([E (),E ()]) 432r .__dict__ ["arena_file" ]= str (f ) 433r .close () 434self .assertFalse (f .exists ()) 435 436 437if __name__ == "__main__" : 438unittest .main ()