okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
07fe758ac
main
1"""CPU-only regression for opt-in reasoning recovery: python -m unittest serve.test_reasoning_loop_recovery.""" 2import threading 3import unittest 4from serve .server import (Service ,ByteTokenizer ,MockEngine ,HIGH_EFFORT , 5reasoning_repeat_coverage ,focused_recovery_prompt ) 6 7 8class Tokenizer (ByteTokenizer ): 9def token_bytes (self ,token ): 10return self .SPECIALS [token - 256 ].encode ()if token >= 256 else bytes ([token ]) 11 12 13class RecordingEngine (MockEngine ): 14def __init__ (self ,tokenizer ,scripts ): 15super ().__init__ (tokenizer ,scripts ,max_context = 100000 ) 16self .calls = [] 17self .sampling_calls = [] 18self .sampling_objects = [] 19 20def generate (self ,ids ,max_new ,sampling ,cancel ,** kwargs ): 21self .calls .append ((list (ids ),max_new )) 22self .sampling_calls .append (dict (sampling or {})) 23self .sampling_objects .append (sampling ) 24yield from super ().generate (ids ,max_new ,sampling ,cancel ,** kwargs ) 25 26 27class ReasoningLoopRecovery (unittest .TestCase ): 28def setUp (self ): 29self .tok = Tokenizer () 30self .ids = self .tok .encode ('<|im_start|>system\n' + HIGH_EFFORT + 31'<|im_end|>\n<|im_start|>user\nSolve this unchanged task<|im_end|>\n' 32'<|im_start|>assistant\n<think>\n' ,parse_special = True ) 33self .loop = 'Need maybe Agent support agent seven b. ' * 700 34 35def test_repetition_and_novel_work (self ): 36self .assertEqual (reasoning_repeat_coverage (' ' .join (str (i )for i in range (4000 ))),0 ) 37self .assertGreater (reasoning_repeat_coverage (self .loop ),.9 ) 38 39def test_a_loop_written_as_one_long_word (self ): 40"""#1753: a 24k-digit string cycling an 11-digit pattern is one word to the split and never one token twice.""" 41self .assertEqual (reasoning_repeat_coverage ('Counting the digits of 9^104. ' + '58747693387' * 3000 ),1 ) 42counted = 'Digits: ' + '' .join (str (i )for i in range (1000 ))# 2,893 chars that never repeat 43self .assertEqual (reasoning_repeat_coverage (counted ),0 ) 44self .assertEqual (reasoning_repeat_coverage ('58747693387' * 100 ),0 )# a tail too short to judge 45 46def test_user_instruction_is_never_rewritten (self ): 47ids = self .tok .encode ('<|im_start|>user\n' + HIGH_EFFORT ,parse_special = True ) 48self .assertIsNone (focused_recovery_prompt (self .tok ,ids , [])) 49 50def test_preserves_task_and_exact_generated_tokens (self ): 51generated = self .tok .encode ('中文 partially checked code' ,parse_special = False ) 52prompt = focused_recovery_prompt (self .tok ,self .ids ,generated ) 53self .assertEqual (prompt [- len (generated ):],generated ) 54self .assertIn ('Solve this unchanged task' ,self .tok .decode (prompt )) 55self .assertNotIn ('</think>' ,self .tok .decode (prompt )) 56 57def run_case (self ,enabled ): 58engine = RecordingEngine (self .tok , [self .loop , 59'I have verified the solution.\n</think>\nComplete solution.' ]) 60service = Service (engine ,self .tok ,None ) 61service .answer_room = False # these cases test the loop guards at the cap itself 62service .reasoning_loop_recovery = enabled 63events = list (service .run (self .ids ,True , [],40000 , {},threading .Event ())) 64return engine ,events 65 66def test_old_explicit_sampler_recovers_without_mutating_request (self ): 67engine = RecordingEngine (self .tok , [self .loop , 68'Verified.\n</think>\nComplete solution.' ]) 69service = Service (engine ,self .tok ,None ) 70service .answer_room = False # these cases test the loop guards at the cap itself 71service .reasoning_loop_recovery = True 72request = {'temperature' :.2 ,'presence_penalty' :0 ,'top_p' :.95 ,'top_k' :64 ,'seed' :2 } 73list (service .run (self .ids ,True , [],40000 ,request ,threading .Event ())) 74self .assertEqual (engine .sampling_calls [0 ],request ) 75self .assertEqual (engine .sampling_calls [1 ]['temperature' ],1.0 ) 76self .assertEqual (engine .sampling_calls [1 ]['presence_penalty' ],1.5 ) 77self .assertEqual (engine .sampling_calls [1 ]['top_k' ],64 )# a client's top_k and top_p are never touched 78self .assertEqual (engine .sampling_calls [1 ]['top_p' ],.95 ) 79self .assertEqual (engine .sampling_calls [1 ]['seed' ],request ['seed' ]) 80self .assertEqual (request ['temperature' ],.2 ) 81self .assertEqual (request ['presence_penalty' ],0 ) 82 83def test_frozen_cohort_sampler_is_unchanged_during_recovery (self ): 84engine = RecordingEngine (self .tok , [self .loop ,'Done.\n</think>\nComplete solution.' ]) 85service = Service (engine ,self .tok ,None ) 86service .answer_room = False # these cases test the loop guards at the cap itself 87service .reasoning_loop_recovery = True 88sampler = {'temperature' :1.0 ,'top_p' :.95 ,'top_k' :20 ,'presence_penalty' :1.5 ,'seed' :2 } 89list (service .run (self .ids ,True , [],40000 ,sampler ,threading .Event ())) 90self .assertEqual (len (engine .sampling_objects ),2 ) 91self .assertIs (engine .sampling_objects [0 ],engine .sampling_objects [1 ]) 92self .assertIs (engine .sampling_objects [1 ],sampler ) 93 94def test_a_lower_top_p_and_top_k_are_never_raised_or_lowered (self ): 95engine = RecordingEngine (self .tok , [self .loop ,'Verified.\n</think>\nComplete solution.' ]) 96service = Service (engine ,self .tok ,None ) 97service .answer_room = False # these cases test the loop guards at the cap itself 98service .reasoning_loop_recovery = "recover" 99list (service .run (self .ids ,True , [],40000 , {'temperature' :0 ,'top_p' :.5 ,'top_k' :5 },threading .Event ())) 100self .assertEqual ((engine .sampling_calls [1 ]['top_p' ],engine .sampling_calls [1 ]['top_k' ]), (.5 ,5 )) 101self .assertEqual ((engine .sampling_calls [1 ]['temperature' ],engine .sampling_calls [1 ]['presence_penalty' ]), (1.0 ,1.5 )) 102 103def test_the_splice_keeps_a_literal_think_tag_as_text (self ): 104"""#537: the prompt is spliced as token ids, never decoded and encoded again.""" 105from serve .frontend import THINK_TAGS 106head = '<|im_start|>system\n' + HIGH_EFFORT 107marked = self .tok .encode (head + '<|im_end|>\n<|im_start|>user\nquote ' + THINK_TAGS ['</think>' ]+ 108' please<|im_end|>\n<|im_start|>assistant\n<think>\n' ,parse_special = True ) 109spliced = focused_recovery_prompt (self .tok ,marked , []) 110tail = marked [len (self .tok .encode (head ,parse_special = True )):] 111self .assertEqual (spliced [- len (tail ):],tail )# everything after the sentence is the same ids 112self .assertNotEqual (spliced ,marked ) 113 114def test_stop_mode_ends_the_reply_at_the_loop (self ): 115engine = RecordingEngine (self .tok , [self .loop ]) 116service = Service (engine ,self .tok ,None ) 117service .answer_room = False # these cases test the loop guards at the cap itself 118service .reasoning_loop_recovery = "stop" 119events = list (service .run (self .ids ,True , [],40000 , {},threading .Event ())) 120self .assertEqual (len (engine .calls ),1 )# no second pass 121self .assertEqual (events [- 1 ][1 ]['finish' ],'length' ) 122self .assertLess (events [- 1 ][1 ]['completion_tokens' ],20000 ) 123self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 124 125def test_stop_mode_ends_a_loop_written_as_one_long_word (self ): 126"""#1753: the word count never sees the digits, so only the tail's period ends the reply.""" 127engine = RecordingEngine (self .tok , ['9^104 = ' + '58747693387' * 3000 ]) 128service = Service (engine ,self .tok ,None ) 129service .answer_room = False # these cases test the loop guards at the cap itself 130service .reasoning_loop_recovery = "stop" 131events = list (service .run (self .ids ,True , [],40000 , {},threading .Event ())) 132self .assertEqual (len (engine .calls ),1 )# no second pass 133self .assertEqual (events [- 1 ][1 ]['finish' ],'length' ) 134self .assertLess (events [- 1 ][1 ]['completion_tokens' ],5000 ) 135self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 136 137def test_disabled_is_one_pass (self ): 138engine ,events = self .run_case (False ) 139self .assertEqual (len (engine .calls ),1 ) 140self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 141 142def test_default_single_token_guard_does_not_detect_passage_loop (self ): 143engine = RecordingEngine (self .tok , [self .loop ]) 144service = Service (engine ,self .tok ,None ) 145service .answer_room = False # these cases test the loop guards at the cap itself 146events = list (service .run (self .ids ,True , [],16384 , {},threading .Event ())) 147self .assertEqual (service .repeat_stop_tokens ,256 ) 148self .assertEqual (events [- 1 ][1 ]['finish' ],'length' ) 149self .assertEqual (events [- 1 ][1 ]['completion_tokens' ],16384 ) 150self .assertFalse (any (e .kind == 'content' for kind ,e in events if kind == 'event' )) 151 152def test_recovery_is_once_and_never_extends_output_limit (self ): 153engine = RecordingEngine (self .tok , [self .loop ,self .loop ]) 154service = Service (engine ,self .tok ,None ) 155service .answer_room = False # these cases test the loop guards at the cap itself 156service .reasoning_loop_recovery = True 157events = list (service .run (self .ids ,True , [],16384 , {},threading .Event ())) 158self .assertEqual (len (engine .calls ),2 ) 159self .assertEqual (events [- 1 ][1 ]['finish' ],'length' ) 160self .assertEqual (events [- 1 ][1 ]['completion_tokens' ],16384 ) 161self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],1 ) 162 163def test_repeated_final_text_does_not_change_sampler_or_prompt (self ): 164engine = RecordingEngine (self .tok , [self .loop ]) 165service = Service (engine ,self .tok ,None ) 166service .answer_room = False # these cases test the loop guards at the cap itself 167service .reasoning_loop_recovery = True 168events = list (service .run (self .ids ,False , [],40000 , {},threading .Event ())) 169self .assertEqual (len (engine .calls ),1 ) 170self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 171 172def test_missing_native_high_hint_skips_recovery (self ): 173engine = RecordingEngine (self .tok , [self .loop ]) 174service = Service (engine ,self .tok ,None ) 175service .answer_room = False # these cases test the loop guards at the cap itself 176service .reasoning_loop_recovery = True 177ids = self .tok .encode ('<|im_start|>user\nTask<|im_end|>\n' ,parse_special = True ) 178events = list (service .run (ids ,True , [],40000 , {},threading .Event ())) 179self .assertEqual (len (engine .calls ),1 ) 180self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 181 182def test_cancel_during_reasoning_does_not_start_recovery (self ): 183engine = RecordingEngine (self .tok , [self .loop ,'Unused' ]) 184service = Service (engine ,self .tok ,None ) 185service .answer_room = False # these cases test the loop guards at the cap itself 186service .reasoning_loop_recovery = True 187cancel = threading .Event () 188events = [] 189for event in service .run (self .ids ,True , [],40000 , {},cancel ): 190events .append (event ) 191if event [0 ]== 'event' : 192cancel .set () 193self .assertEqual (len (engine .calls ),1 ) 194self .assertEqual (events [- 1 ][1 ]['finish' ],'cancel' ) 195self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],0 ) 196 197def test_batch_status_and_history_record_recovery (self ): 198engine = RecordingEngine (self .tok , [self .loop ,'Done.\n</think>\nAnswer.' ]) 199engine .batch = 2 200service = Service (engine ,self .tok ,None ) 201service .answer_room = False # these cases test the loop guards at the cap itself 202service .reasoning_loop_recovery = True 203events = list (service .run (self .ids ,True , [],40000 , {},threading .Event ())) 204self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],1 ) 205self .assertEqual (service .history [- 1 ]['reasoning_recoveries' ],1 ) 206self .assertGreaterEqual (service .history [- 1 ]['reasoning_repeat_coverage' ],.25 ) 207self .assertFalse (service .status ['busy' ]) 208self .assertEqual (service .live_reqs , {}) 209 210def test_natural_answer_with_shared_budget_and_preserved_prefix (self ): 211engine ,events = self .run_case (True ) 212self .assertEqual (len (engine .calls ),2 ) 213self .assertEqual (events [- 1 ][1 ]['reasoning_recoveries' ],1 ) 214self .assertEqual (events [- 1 ][1 ]['finish' ],'stop' ) 215content = '' .join (e .text or '' for kind ,e in events if kind == 'event' and e .kind == 'content' ) 216self .assertEqual (content ,'Complete solution.' ) 217head_size = len (focused_recovery_prompt (self .tok ,self .ids , [])) 218retained = engine .calls [1 ][0 ][head_size :] 219self .assertEqual (retained ,self .tok .encode (self .loop )[:len (retained )]) 220self .assertEqual (engine .calls [1 ][1 ],40000 - len (retained )) 221self .assertNotIn ('</think>' ,self .tok .decode (engine .calls [1 ][0 ])) 222 223 224if __name__ == '__main__' : 225unittest .main ()