okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
8.6 KiB184 linesraw
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
10    python 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:
31    while True:
32        c = "".join(rnd.choice("ABCDEFGHJKLMNPQRSTUVWXYZ") for _ in range(3)) + "-" + f"{rnd.randrange(10000):04d}"
33        if c not in used:
34            used.add(c)
35            return c
36
37
38def prompt_for(canary: str, filler_words: int, rnd: random.Random) -> str:
39    filler = " ".join(rnd.choice(FILLER_WORDS) for _ in range(filler_words))
40    head = (filler + "\n\n") if filler else ""
41    return (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:
49    def __init__(self, canary, plan):
50        self.canary, self.plan = canary, plan
51        self.content, self.reasoning, self.chunks, self.error, self.finished, self.status = "", "", 0, None, False, None
52
53    @property
54    def text(self):
55        return self.reasoning + "\n" + self.content
56
57    def foreign(self):
58        return 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."""
63    t0 = time.monotonic()
64    conn = http.client.HTTPConnection(host, port, timeout=timeout)
65    try:
66        conn.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"})
67        if stop_after_s is not None and stop_after_chunks is None:      # leave before any answer
68            time.sleep(stop_after_s)
69            return
70        resp = conn.getresponse()
71        res.status = resp.status
72        if resp.status != 200:
73            res.error = f"HTTP {resp.status}"
74            resp.read()
75            return
76        while True:
77            line = resp.readline()
78            if not line:
79                break
80            line = line.decode("utf-8", "replace").strip()
81            if not line.startswith("data:"):
82                continue
83            data = line[5:].strip()
84            if data == "[DONE]":
85                res.finished = True
86                break
87            try:
88                obj = json.loads(data)
89            except ValueError:
90                continue
91            for ch in obj.get("choices") or []:
92                d = ch.get("delta") or {}
93                res.content += d.get("content") or ""
94                res.reasoning += d.get("reasoning_content") or d.get("reasoning") or ""
95                res.chunks += 1
96            if stop_after_chunks is not None and res.chunks >= stop_after_chunks:
97                return
98            if stop_after_s is not None and time.monotonic() - t0 >= stop_after_s:
99                return
100    except Exception as e:                       # noqa: BLE001 - a dropped connection is a result, not a crash
101        res.error = f"{type(e).__name__}: {e}"
102    finally:
103        try:
104            conn.close()
105        except Exception:                        # noqa: BLE001
106            pass
107
108
109def main():
110    ap = argparse.ArgumentParser()
111    ap.add_argument("--url", required=True)
112    ap.add_argument("--clients", type=int, default=6, help="interleaved clients per round")
113    ap.add_argument("--rounds", type=int, default=10)
114    ap.add_argument("--seed", type=int, default=1)
115    ap.add_argument("--disconnect", type=float, default=0.5, help="probability that a client leaves early")
116    ap.add_argument("--max-tokens", type=int, default=256)
117    ap.add_argument("--thinking", type=float, default=0.5, help="share of clients that ask for reasoning (effort 'low')")
118    ap.add_argument("--filler-max", type=int, default=3000, help="at most this many filler words in a prompt (a longer prompt read)")
119    ap.add_argument("--timeout", type=float, default=300.0)
120    ap.add_argument("--out", default="")
121    a = ap.parse_args()
122    u = urllib.parse.urlparse(a.url)
123    host, port = u.hostname, u.port or 80
124    rnd = random.Random(a.seed)
125    used, results, started = USED, [], time.time()
126    for rd in range(a.rounds):
127        threads, batch = [], []
128        for k in range(a.clients):
129            canary = make_canary(rnd, used)
130            leave = rnd.random() < a.disconnect
131            plan = {"round": rd, "leave": leave}
132            filler = rnd.choice((0, 0, 200, a.filler_max)) if a.filler_max else 0
133            body = {"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"}
135            plan.update(filler_words=filler, effort=body["reasoning_effort"])
136            chunks = after_s = None
137            if leave:
138                mode = rnd.choice(("before_answer", "early", "mid"))
139                plan["mode"] = mode
140                if mode == "before_answer":
141                    after_s = rnd.choice((0.05, 0.3, 1.0, 2.5))
142                elif mode == "early":
143                    chunks = rnd.randrange(1, 4)
144                else:
145                    chunks = rnd.randrange(5, 40)
146            res = Result(canary, plan)
147            batch.append(res)
148            t = threading.Thread(target=one_client, args=(host, port, body, res, chunks, after_s, a.timeout), daemon=True)
149            threads.append(t)
150        for t in threads:
151            t.start()
152            time.sleep(rnd.choice((0.0, 0.02, 0.1)))
153        for t in threads:
154            t.join(a.timeout + 30)
155        results.extend(batch)
156        bad = [r for r in batch if r.foreign()]
157        print(f"round {rd + 1}/{a.rounds}: {len(batch)} clients, {sum(1 for r in batch if r.finished)} finished, "
158              f"{sum(1 for r in batch if r.plan['leave'])} left early, {len(bad)} with a foreign canary", flush=True)
159    crossed = [r for r in results if r.foreign()]
160    finished = [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)
163    own_missing = [r for r in finished if r.canary not in r.text]
164    summary = {"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]}
169                           for r in crossed[:20]],
170               "samples": [{"canary": r.canary, "plan": r.plan, "chunks": r.chunks, "excerpt": r.text[:200]}
171                           for r in (own_missing[:3] + finished[:3])]}
172    print(json.dumps({k: v for k, v in summary.items() if k not in ("crossed", "samples")}), flush=True)
173    for c in summary["crossed"]:
174        print("CROSS-DELIVERY", json.dumps(c), flush=True)
175    if a.out:
176        with open(a.out, "w", encoding="utf-8") as f:
177            json.dump(summary, f, indent=1)
178    if not finished:
179        return 2
180    return 1 if crossed else 0
181
182
183if __name__ == "__main__":
184    sys.exit(main())