okami.mom/strata

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

Niko1221terminal: strata_cli, strata_control, bin/strata and the terminal tests64a91dcdc

main
16.2 KiB309 linesraw
1#!/usr/bin/env python3
2"""Headless Monitor soak against a bounded synthetic telemetry server.
3
4This is a client stability check, not model, GPU or serving performance evidence.
5Run for 1800 seconds to exercise reconnects, instance changes and bounded state.
6"""
7
8from __future__ import annotations
9
10import argparse
11import asyncio
12import json
13import os
14import threading
15import time
16import tracemalloc
17from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
18from pathlib import Path
19
20from strata_cli.client import Endpoint
21
22
23class SyntheticTelemetry:
24    def __init__(self, *, exercise_ui: bool = False):
25        self.lock = threading.Lock()
26        self.instance = 0
27        self.unavailable = False
28        self.gets = 0
29        self.failures = 0
30        self.other_methods = 0
31        self.bytes_sent = 0
32        self.in_flight = 0
33        self.max_in_flight = 0
34        self.seq = 0
35        self.exercise_ui = exercise_ui
36
37    def snapshot(self) -> dict:
38        with self.lock:
39            self.seq += 1
40            seq, instance = self.seq, self.instance
41        now = time.time()
42        events = [{"seq": number, "at": now, "request_id": f"{number:012x}", "event": "queued"}
43                  for number in range(max(1, seq - 63), seq + 1)]
44        devices = [{"index": i, "name": f"Synthetic card {i}"} for i in range(4)]
45        topology = {}
46        if self.exercise_ui:
47            # Rotate an unrelated host card and intermittently lose or duplicate
48            # a selected sensor. The Overview must retain only the four selected
49            # card histories and mark current gaps unavailable.
50            devices = [{"index": 100 + seq, "name": "Unselected host card", "util": 10}]
51            devices += [{"index": i, "name": f"Selected card {i}",
52                         "util": (40 + i * 11 + seq) % 100,
53                         "mem_used": (12 + i) * 2**30, "mem_total": 24 * 2**30}
54                        for i in range(4) if not (i == 3 and seq % 5 == 0)]
55            if seq % 7 == 0:
56                devices.append({"index": 1, "name": "Ambiguous card 1", "util": 99})
57            topology = {"mode": "layer split", "selected_devices": [0, 1, 2, 3],
58                        "resolved": False, "stages": []}
59        return {"schema_version": 1, "source": "synthetic-soak", "sampled_at": now,
60                "instance": {"id": f"synthetic-{instance}", "state": "ready", "boot_time": now - 60},
61                "model": {"id": "synthetic-model", "loaded": True, "context": 4096},
62                "rates": {"output_tokens_server_counter": seq * 12},
63                "work": {"active": 0, "queued": seq % 5, "waiting": 0, "slots_requested": 8,
64                         "slots_effective": 8, "groups": 4,
65                         "batch_sample_windows": 4, "batch_sample_rows": 4 * (3 + seq % 4),
66                         "batch_sample_active_rows": 4 * min(3, 2 + seq % 3),
67                         "batch_sample_span_s": 1.0, "batch_sample_age_s": 0.1,
68                         "requests": [{"id": f"r{i:02d}", "state": "queued"} for i in range(70)]},
69                "topology": topology, "devices": devices,
70                "activity": {"last_seq": seq, "events": events}}
71
72    def counters(self) -> dict:
73        with self.lock:
74            return {"gets": self.gets, "http_failures": self.failures,
75                    "other_methods": self.other_methods, "bytes_sent": self.bytes_sent,
76                    "max_in_flight": self.max_in_flight, "instance": self.instance}
77
78
79def handler_for(service: SyntheticTelemetry):
80    class Handler(BaseHTTPRequestHandler):
81        def log_message(self, *_args):
82            pass
83
84        def do_GET(self):
85            with service.lock:
86                service.in_flight += 1
87                service.max_in_flight = max(service.max_in_flight, service.in_flight)
88                service.gets += 1
89                unavailable = service.unavailable
90            try:
91                if self.path != "/v1/telemetry":
92                    self.send_error(404)
93                    return
94                if unavailable:
95                    with service.lock:
96                        service.failures += 1
97                    self.send_error(503)
98                    return
99                body = json.dumps(service.snapshot(), separators=(",", ":")).encode()
100                self.send_response(200)
101                self.send_header("Content-Type", "application/json")
102                self.send_header("Content-Length", str(len(body)))
103                self.end_headers()
104                self.wfile.write(body)
105                with service.lock:
106                    service.bytes_sent += len(body)
107            finally:
108                with service.lock:
109                    service.in_flight -= 1
110
111        def do_POST(self):
112            with service.lock:
113                service.other_methods += 1
114            self.send_error(405)
115
116    return Handler
117
118
119async def soak(seconds: float, interval: float, *, exercise_ui: bool = False) -> dict:
120    try:
121        from strata_cli.monitor import MonitorApp
122    except ImportError as exc:
123        raise RuntimeError("the optional Textual monitor dependency is required") from exc
124    service = SyntheticTelemetry(exercise_ui=exercise_ui)
125    server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(service))
126    thread = threading.Thread(target=server.serve_forever, daemon=True)
127    thread.start()
128    endpoint = Endpoint(f"http://127.0.0.1:{server.server_port}", timeout=1)
129    tracemalloc.start()
130    started = time.monotonic()
131    cpu_started = time.process_time()
132    events: list[str] = []
133    baseline = None
134    max_output_rate_samples = 0
135    max_batch_samples = 0
136    max_pre_admit_samples = 0
137    max_device_histories = 0
138    max_device_samples = 0
139    sensor_gap_observed = False
140    max_vram_histories = 0
141    max_vram_samples = 0
142    vram_sensor_gap_observed = False
143    resize_count = 0
144    sizes_seen: set[tuple[int, int]] = set()
145    resize_size_cycle = ((140, 44), (110, 30), (80, 24), (60, 16), (40, 12))
146    resize_step = max(1.0, min(5.0, seconds / 20))
147    next_resize = 1.0
148    next_progress = 60.0
149    outage_length = min(5.0, max(1.0, seconds / 20))
150    try:
151        app = MonitorApp(endpoint, None, interval=interval)
152        observed_states = {app.connection_state}
153        async with app.run_test(size=(80, 24)) as pilot:
154            await pilot.press("2")
155            while True:
156                elapsed = time.monotonic() - started
157                if elapsed >= seconds:
158                    break
159                if baseline is None and elapsed >= min(5.0, seconds / 5):
160                    baseline = tracemalloc.get_traced_memory()[0]
161                if elapsed >= seconds * 0.25 and "disconnect" not in events:
162                    with service.lock:
163                        service.unavailable = True
164                    events.append("disconnect")
165                if elapsed >= seconds * 0.25 + outage_length and "reconnect" not in events:
166                    with service.lock:
167                        service.unavailable = False
168                    events.append("reconnect")
169                if elapsed >= seconds * 0.5 and "restart" not in events:
170                    with service.lock:
171                        service.instance += 1
172                        service.seq = 0
173                    events.append("restart")
174                if elapsed >= seconds * 0.75 and "second_disconnect" not in events:
175                    with service.lock:
176                        service.unavailable = True
177                    events.append("second_disconnect")
178                if elapsed >= seconds * 0.75 + outage_length and "second_reconnect" not in events:
179                    with service.lock:
180                        service.unavailable = False
181                    events.append("second_reconnect")
182                if elapsed >= next_progress:
183                    print(json.dumps({"elapsed_s": round(elapsed, 1), **service.counters()}), flush=True)
184                    next_progress += 60.0
185                if exercise_ui and elapsed >= next_resize:
186                    size = resize_size_cycle[resize_count % len(resize_size_cycle)]
187                    await pilot.resize_terminal(*size)
188                    sizes_seen.add(size)
189                    resize_count += 1
190                    next_resize += resize_step
191                observed_states.add(app.connection_state)
192                max_output_rate_samples = max(max_output_rate_samples, len(app.history.output_rate))
193                max_batch_samples = max(max_batch_samples, len(app.history.batch_rows))
194                max_pre_admit_samples = max(max_pre_admit_samples, len(app.history.pre_admit))
195                max_device_histories = max(max_device_histories, len(app.history.device_util))
196                max_device_samples = max(max_device_samples,
197                                         *(len(rows) for rows in app.history.device_util.values()), 0)
198                sensor_gap_observed |= any(rows and rows[-1] is None
199                                           for rows in app.history.device_util.values())
200                max_vram_histories = max(max_vram_histories, len(app.history.device_vram))
201                max_vram_samples = max(max_vram_samples,
202                                       *(len(rows) for rows in app.history.device_vram.values()), 0)
203                vram_sensor_gap_observed |= any(rows and rows[-1] is None
204                                                for rows in app.history.device_vram.values())
205                await asyncio.sleep(min(0.5, max(0.01, seconds - elapsed)))
206            await pilot.press("6")
207            await pilot.pause(0.1)
208            latest = app.latest
209            final_instance = (latest.get("instance") or {}).get("id")
210            retained_activity = len((latest.get("activity") or {}).get("events") or [])
211            retained_requests = len((latest.get("work") or {}).get("requests") or [])
212            output_rate_samples = list(app.history.output_rate)
213            valid_output_rate_samples = sum(value is not None for value in output_rate_samples)
214            valid_batch_samples = sum(value is not None for value in app.history.batch_rows)
215            valid_pre_admit_samples = sum(value is not None for value in app.history.pre_admit)
216            output_rate_instance = app.history.instance
217            monitor_recovered = app.error is None and app.failures == 0
218            await pilot.press("q")
219        process_memory = tracemalloc.get_traced_memory()[0]
220        counters = service.counters()
221        # A fresh read after detach proves the monitor did not shut down the server.
222        detached_server_readable = endpoint.snapshot()["instance"]["id"] == final_instance
223        return {"schema_version": 1, "scope": "synthetic_headless_monitor_soak",
224                "duration_s": round(time.monotonic() - started, 2), "poll_interval_s": interval,
225                "events": events, "final_instance_id": final_instance,
226                "monitor_states": sorted(observed_states),
227                "retained_activity": retained_activity, "retained_requests": retained_requests,
228                "output_rate_samples_retained": len(output_rate_samples),
229                "output_rate_valid_samples": valid_output_rate_samples,
230                "output_rate_history_max_samples": max_output_rate_samples,
231                "batch_history_max_samples": max_batch_samples,
232                "batch_history_valid_samples": valid_batch_samples,
233                "pre_admit_history_max_samples": max_pre_admit_samples,
234                "pre_admit_history_valid_samples": valid_pre_admit_samples,
235                "output_rate_history_instance": list(output_rate_instance) if output_rate_instance else None,
236                "exercise_ui": exercise_ui,
237                "resize_count": resize_count,
238                "terminal_sizes_seen": [list(size) for size in sorted(sizes_seen)],
239                "device_history_max_cards": max_device_histories,
240                "device_history_max_samples": max_device_samples,
241                "device_sensor_gap_observed": sensor_gap_observed,
242                "vram_history_max_cards": max_vram_histories,
243                "vram_history_max_samples": max_vram_samples,
244                "vram_sensor_gap_observed": vram_sensor_gap_observed,
245                "traced_memory_baseline_bytes": baseline,
246                "traced_memory_final_bytes": process_memory,
247                "traced_memory_growth_bytes": process_memory - baseline if baseline is not None else None,
248                "synthetic_memory_growth_budget_bytes": 20 * 1024 * 1024,
249                "combined_process_cpu_s": round(time.process_time() - cpu_started, 3),
250                "monitor_recovered": monitor_recovered,
251                "detached_server_readable": detached_server_readable,
252                "http": {**counters,
253                         "gets_per_s": round(counters["gets"] / max(0.1, time.monotonic() - started), 3),
254                         "bytes_per_s": round(counters["bytes_sent"] / max(0.1, time.monotonic() - started), 1)},
255                "passed": (set(events) == {"disconnect", "reconnect", "restart",
256                                          "second_disconnect", "second_reconnect"}
257                           and final_instance == "synthetic-1" and retained_activity <= 32
258                           and retained_requests <= 50 and 2 <= valid_output_rate_samples
259                           and max_output_rate_samples <= app.history.limit
260                           and 2 <= valid_batch_samples and max_batch_samples <= app.history.limit
261                           and 2 <= valid_pre_admit_samples and max_pre_admit_samples <= app.history.limit
262                           and output_rate_instance == ("id", final_instance)
263                           and counters["other_methods"] == 0
264                           and counters["max_in_flight"] <= 1 and counters["http_failures"] >= 2
265                           and {"connecting", "connected", "stale"} <= observed_states
266                           and monitor_recovered and detached_server_readable and baseline is not None
267                           and process_memory - baseline <= 20 * 1024 * 1024
268                           and (not exercise_ui or
269                                (sizes_seen == set(resize_size_cycle) and resize_count >= 4
270                                 and max_device_histories <= 4 and max_device_samples <= app.history.limit
271                                 and sensor_gap_observed
272                                 and set(app.history.device_util) == {0, 1, 2, 3}
273                                 and max_vram_histories <= 4 and max_vram_samples <= app.history.limit
274                                 and vram_sensor_gap_observed
275                                 and set(app.history.device_vram) == {0, 1, 2, 3})))}
276    finally:
277        server.shutdown()
278        server.server_close()
279        thread.join(timeout=2)
280        tracemalloc.stop()
281
282
283def main(argv: list[str] | None = None) -> int:
284    parser = argparse.ArgumentParser(description="Headless synthetic Strata Monitor soak")
285    parser.add_argument("--seconds", type=float, default=1800)
286    parser.add_argument("--interval", type=float, default=0.5)
287    parser.add_argument("--exercise-ui", action="store_true",
288                        help="resize across five terminal sizes and churn selected/host card sensors")
289    parser.add_argument("--report", type=Path, required=True, help="new absolute JSON report path")
290    args = parser.parse_args(argv)
291    if not 8 <= args.seconds <= 3600 or not 0.5 <= args.interval <= 30:
292        parser.error("--seconds must be 8..3600 and --interval must be 0.5..30")
293    if args.exercise_ui and args.seconds < 30:
294        parser.error("--exercise-ui requires at least 30 seconds")
295    report_path = args.report.expanduser()
296    if not report_path.is_absolute() or report_path.exists():
297        parser.error("--report must be an absolute new file")
298    result = asyncio.run(soak(args.seconds, args.interval, exercise_ui=args.exercise_ui))
299    report_path.parent.mkdir(parents=True, exist_ok=True)
300    descriptor = os.open(report_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
301    with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
302        json.dump(result, stream, indent=2)
303        stream.write("\n")
304    print(json.dumps({"report": str(report_path), "passed": result["passed"]}), flush=True)
305    return 0 if result["passed"] else 6
306
307
308if __name__ == "__main__":
309    raise SystemExit(main())