okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1#!/usr/bin/env python3 2"""Streamed output must reach only the client that asked for it (#4451, #2892). 3 4Many interleaved streaming clients, each with its own random canary in its prompt and the model asked to repeat it. 5Some clients disconnect at random points (before the first byte, during the prompt read, after a few chunks). Every 6text a client receives (content and reasoning) is searched for canaries: any canary that is not the client's own is a 7cross-delivery. Run against any OpenAI-compatible Strata server; the server must be one you started (check the 8listener first on a shared box). 9 10python research/tools/live-probes-2026-10/stream_ownership_probe.py --url http://127.0.0.1:8080 --clients 6 --rounds 20 --seed 1 --out result.json 11 12Exit code 0: no cross-delivery. 1: at least one. 2: the run itself failed (no server, no completed client). 13Nothing here sends anything but chat requests; it never reads another client's connection. 14""" 15import argparse 16import http .client 17import json 18import random 19import re 20import sys 21import threading 22import time 23import urllib .parse 24 25CANARY = re .compile (r"\b[A-Z]{3}-\d{4}\b" ) 26FILLER_WORDS = ("lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et " 27"dolore magna aliqua" ).split () 28 29 30def make_canary (rnd :random .Random ,used :set )-> str : 31while True : 32c = "" .join (rnd .choice ("ABCDEFGHJKLMNPQRSTUVWXYZ" )for _ in range (3 ))+ "-" + f" { rnd . randrange ( 10000 ):04d } " 33if c not in used : 34used .add (c ) 35return c 36 37 38def prompt_for (canary :str ,filler_words :int ,rnd :random .Random )-> str : 39filler = " " .join (rnd .choice (FILLER_WORDS )for _ in range (filler_words )) 40head = (filler + "\n\n" )if filler else "" 41return (f" { head } Your code word is { canary } . Write the code word { canary } { rnd . choice (( 20 , 30 , 40 )) } times, " 42"separated by single spaces, and write nothing else." ) 43 44 45USED :set = set ()# every canary this run has issued: a canary-looking string the model made up is not a cross-delivery 46 47 48class Result : 49def __init__ (self ,canary ,plan ): 50self .canary ,self .plan = canary ,plan 51self .content ,self .reasoning ,self .chunks ,self .error ,self .finished ,self .status = "" ,"" ,0 ,None ,False ,None 52 53@property 54def text (self ): 55return self .reasoning + "\n" + self .content 56 57def foreign (self ): 58return sorted ({c for c in CANARY .findall (self .text )if c != self .canary and c in USED }) 59 60 61def one_client (host ,port ,body ,res :Result ,stop_after_chunks ,stop_after_s ,timeout ): 62"""Streams the reply; leaves (closes the socket) after `stop_after_chunks` chunks or `stop_after_s` seconds.""" 63t0 = time .monotonic () 64conn = http .client .HTTPConnection (host ,port ,timeout = timeout ) 65try : 66conn .request ("POST" ,"/v1/chat/completions" ,json .dumps (body ), {"Content-Type" :"application/json" }) 67if stop_after_s is not None and stop_after_chunks is None :# leave before any answer 68time .sleep (stop_after_s ) 69return 70resp = conn .getresponse () 71res .status = resp .status 72if resp .status != 200 : 73res .error = f"HTTP { resp . status } " 74resp .read () 75return 76while True : 77line = resp .readline () 78if not line : 79break 80line = line .decode ("utf-8" ,"replace" ).strip () 81if not line .startswith ("data:" ): 82continue 83data = line [5 :].strip () 84if data == "[DONE]" : 85res .finished = True 86break 87try : 88obj = json .loads (data ) 89except ValueError : 90continue 91for ch in obj .get ("choices" )or []: 92d = ch .get ("delta" )or {} 93res .content += d .get ("content" )or "" 94res .reasoning += d .get ("reasoning_content" )or d .get ("reasoning" )or "" 95res .chunks += 1 96if stop_after_chunks is not None and res .chunks >= stop_after_chunks : 97return 98if stop_after_s is not None and time .monotonic ()- t0 >= stop_after_s : 99return 100except Exception as e :# noqa: BLE001 - a dropped connection is a result, not a crash 101res .error = f" { type ( e ). __name__ } : { e } " 102finally : 103try : 104conn .close () 105except Exception :# noqa: BLE001 106pass 107 108 109def main (): 110ap = argparse .ArgumentParser () 111ap .add_argument ("--url" ,required = True ) 112ap .add_argument ("--clients" ,type = int ,default = 6 ,help = "interleaved clients per round" ) 113ap .add_argument ("--rounds" ,type = int ,default = 10 ) 114ap .add_argument ("--seed" ,type = int ,default = 1 ) 115ap .add_argument ("--disconnect" ,type = float ,default = 0.5 ,help = "probability that a client leaves early" ) 116ap .add_argument ("--max-tokens" ,type = int ,default = 256 ) 117ap .add_argument ("--thinking" ,type = float ,default = 0.5 ,help = "share of clients that ask for reasoning (effort 'low')" ) 118ap .add_argument ("--filler-max" ,type = int ,default = 3000 ,help = "at most this many filler words in a prompt (a longer prompt read)" ) 119ap .add_argument ("--timeout" ,type = float ,default = 300.0 ) 120ap .add_argument ("--out" ,default = "" ) 121a = ap .parse_args () 122u = urllib .parse .urlparse (a .url ) 123host ,port = u .hostname ,u .port or 80 124rnd = random .Random (a .seed ) 125used ,results ,started = USED , [],time .time () 126for rd in range (a .rounds ): 127threads ,batch = [], [] 128for k in range (a .clients ): 129canary = make_canary (rnd ,used ) 130leave = rnd .random ()< a .disconnect 131plan = {"round" :rd ,"leave" :leave } 132filler = rnd .choice ((0 ,0 ,200 ,a .filler_max ))if a .filler_max else 0 133body = {"messages" : [{"role" :"user" ,"content" :prompt_for (canary ,filler ,rnd )}],"stream" :True , 134"max_tokens" :a .max_tokens ,"reasoning_effort" :"low" if rnd .random ()< a .thinking else "none" } 135plan .update (filler_words = filler ,effort = body ["reasoning_effort" ]) 136chunks = after_s = None 137if leave : 138mode = rnd .choice (("before_answer" ,"early" ,"mid" )) 139plan ["mode" ]= mode 140if mode == "before_answer" : 141after_s = rnd .choice ((0.05 ,0.3 ,1.0 ,2.5 )) 142elif mode == "early" : 143chunks = rnd .randrange (1 ,4 ) 144else : 145chunks = rnd .randrange (5 ,40 ) 146res = Result (canary ,plan ) 147batch .append (res ) 148t = threading .Thread (target = one_client ,args = (host ,port ,body ,res ,chunks ,after_s ,a .timeout ),daemon = True ) 149threads .append (t ) 150for t in threads : 151t .start () 152time .sleep (rnd .choice ((0.0 ,0.02 ,0.1 ))) 153for t in threads : 154t .join (a .timeout + 30 ) 155results .extend (batch ) 156bad = [r for r in batch if r .foreign ()] 157f"round { rd + 1 } / { a . rounds } : { len ( batch ) } clients, { sum ( 1 for r in batch if r . finished ) } finished, " 158f" { sum ( 1 for r in batch if r . plan [ 'leave' ]) } left early, { len ( bad ) } with a foreign canary" ,flush = True ) 159crossed = [r for r in results if r .foreign ()] 160finished = [r for r in results if r .finished ] 161# a finished client of a plain request should have its own canary in its text; a missing one is not a cross-delivery 162# but is reported (the model did not follow the instruction, or the reply was empty / replaced) 163own_missing = [r for r in finished if r .canary not in r .text ] 164summary = {"clients" :len (results ),"finished" :len (finished ),"left_early" :sum (1 for r in results if r .plan ["leave" ]), 165"errors" :sum (1 for r in results if r .error and r .plan ["leave" ]is False ), 166"cross_delivery" :len (crossed ),"finished_without_own_canary" :len (own_missing ), 167"seconds" :round (time .time ()- started ,1 ),"seed" :a .seed , 168"crossed" : [{"canary" :r .canary ,"foreign" :r .foreign (),"plan" :r .plan ,"excerpt" :r .text [:300 ]} 169for r in crossed [:20 ]], 170"samples" : [{"canary" :r .canary ,"plan" :r .plan ,"chunks" :r .chunks ,"excerpt" :r .text [:200 ]} 171for r in (own_missing [:3 ]+ finished [:3 ])]} 172json .dumps ({k :v for k ,v in summary .items ()if k not in ("crossed" ,"samples" )}),flush = True ) 173for c in summary ["crossed" ]: 174"CROSS-DELIVERY" ,json .dumps (c ),flush = True ) 175if a .out : 176with open (a .out ,"w" ,encoding = "utf-8" )as f : 177json .dump (summary ,f ,indent = 1 ) 178if not finished : 179return 2 180return 1 if crossed else 0 181 182 183if __name__ == "__main__" : 184sys .exit (main ())