|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""The turnover window of an agentsession run in turnover mode. |
| 16 | +
|
| 17 | +In turnover mode (--agentsession-awake) a run first registers its whole |
| 18 | +fleet: each session creates its actor, runs step 1 and parks. The conductor |
| 19 | +then wakes the awake sessions, and only after that fill does it swap at |
| 20 | +--target-rps. stats.jsonl's other rows cover the whole run, so their rates |
| 21 | +divide by the time spent registering. This finds the end of the fill in the |
| 22 | +line boomer logs then, and writes one `turnover_window` row with each |
| 23 | +request's count, failures and rate from there to the end of the run, read |
| 24 | +from stats_history.csv. runner.py also starts the server telemetry's |
| 25 | +steady-state window there. |
| 26 | +
|
| 27 | +Like the server telemetry, this is additive: runner.py logs a failure here |
| 28 | +and keeps the locust measurements. |
| 29 | +""" |
| 30 | + |
| 31 | +import csv |
| 32 | +import json |
| 33 | +import re |
| 34 | +from datetime import datetime, timezone |
| 35 | +from pathlib import Path |
| 36 | +from typing import Any, Iterable, TextIO |
| 37 | + |
| 38 | +# What agentsession logs once its conductor has woken the awake sessions, |
| 39 | +# right before it starts to swap. |
| 40 | +FILL_DONE_MSG = "agentsession: turnover fill done" |
| 41 | + |
| 42 | +# The prefix runner.py puts on each line boomer writes to the run's log. |
| 43 | +BOOMER_PREFIX = "[boomer] " |
| 44 | + |
| 45 | +# An RFC 3339 time as Go writes it. Its fraction can hold nanoseconds, which |
| 46 | +# datetime does not parse, and only the seconds matter here. |
| 47 | +_TIME_RE = re.compile(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.\d+)?(Z|[+-]\d\d:\d\d)$") |
| 48 | + |
| 49 | + |
| 50 | +def _unix(ts: str) -> int: |
| 51 | + m = _TIME_RE.match(ts) |
| 52 | + if not m: |
| 53 | + raise ValueError(f"not an RFC 3339 time: {ts!r}") |
| 54 | + t = datetime.strptime(m[1], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc) |
| 55 | + offset = 0 |
| 56 | + if m[2] != "Z": |
| 57 | + sign = 1 if m[2][0] == "+" else -1 |
| 58 | + offset = sign * (int(m[2][1:3]) * 3600 + int(m[2][4:6]) * 60) |
| 59 | + return int(t.timestamp()) - offset |
| 60 | + |
| 61 | + |
| 62 | +def fill_done_ts(lines: Iterable[str]) -> int | None: |
| 63 | + """Unix seconds of the first fill-done line in the run's log, or None |
| 64 | + when there is none: the run was not in turnover mode, or its fill never |
| 65 | + finished.""" |
| 66 | + for line in lines: |
| 67 | + if not line.startswith(BOOMER_PREFIX) or FILL_DONE_MSG not in line: |
| 68 | + continue |
| 69 | + try: |
| 70 | + entry = json.loads(line[len(BOOMER_PREFIX):]) |
| 71 | + if entry.get("msg") == FILL_DONE_MSG: |
| 72 | + return _unix(entry["time"]) |
| 73 | + except (AttributeError, KeyError, TypeError, ValueError): |
| 74 | + continue |
| 75 | + return None |
| 76 | + |
| 77 | + |
| 78 | +def window_counts( |
| 79 | + stats_history_csv: Path, start: int |
| 80 | +) -> tuple[int, dict[str, tuple[int, int]]] | None: |
| 81 | + """The time of the last sample in stats_history.csv, and each request's |
| 82 | + requests and failures from start to it, or None when no sample comes |
| 83 | + after start. The counts come from the cumulative columns of the |
| 84 | + per-request rows that --csv-full-history writes: the last sample's minus |
| 85 | + the last one at or before start.""" |
| 86 | + before: dict[str, tuple[int, int]] = {} |
| 87 | + after: dict[str, tuple[int, int]] = {} |
| 88 | + end = None |
| 89 | + with open(stats_history_csv, encoding="utf-8") as f: |
| 90 | + for row in csv.DictReader(f): |
| 91 | + name = row.get("Name") or "" |
| 92 | + if name in ("", "Aggregated", "Total"): |
| 93 | + continue |
| 94 | + try: |
| 95 | + ts = int(row["Timestamp"]) |
| 96 | + counts = (int(row["Total Request Count"]), int(row["Total Failure Count"])) |
| 97 | + except (KeyError, TypeError, ValueError): |
| 98 | + continue |
| 99 | + if ts <= start: |
| 100 | + before[name] = counts |
| 101 | + else: |
| 102 | + after[name] = counts |
| 103 | + end = ts if end is None else max(end, ts) |
| 104 | + if end is None: |
| 105 | + return None |
| 106 | + return end, { |
| 107 | + name: (requests - before.get(name, (0, 0))[0], failures - before.get(name, (0, 0))[1]) |
| 108 | + for name, (requests, failures) in after.items() |
| 109 | + } |
| 110 | + |
| 111 | + |
| 112 | +def window_record( |
| 113 | + start: int, |
| 114 | + end: int, |
| 115 | + counts: dict[str, tuple[int, int]], |
| 116 | + timestamp: str, |
| 117 | + tag: str, |
| 118 | + test_name: str, |
| 119 | +) -> dict[str, Any]: |
| 120 | + """The window as a stats.jsonl row: each request's count, failures and |
| 121 | + rate. The rate counts every request, failed or not, like locust's |
| 122 | + Requests/s.""" |
| 123 | + secs = end - start |
| 124 | + m: dict[str, Any] = {"window_start": start, "window_end": end, "window_s": secs} |
| 125 | + for name, (requests, failures) in sorted(counts.items()): |
| 126 | + m[f"requests_{name}"] = requests |
| 127 | + m[f"failures_{name}"] = failures |
| 128 | + m[f"rps_{name}"] = round(requests / secs, 4) if secs > 0 else None |
| 129 | + return { |
| 130 | + "timestamp": timestamp, |
| 131 | + "tag": tag, |
| 132 | + "test_name": test_name, |
| 133 | + "metric": "turnover_window", |
| 134 | + "measurements": m, |
| 135 | + } |
| 136 | + |
| 137 | + |
| 138 | +def append_turnover_window( |
| 139 | + jsonl_path: Path, |
| 140 | + start: int, |
| 141 | + stats_history_csv: Path, |
| 142 | + timestamp: str, |
| 143 | + tag: str, |
| 144 | + test_name: str, |
| 145 | + logs: TextIO, |
| 146 | +) -> bool: |
| 147 | + """Append the turnover_window row of a run whose fill ended at start to |
| 148 | + jsonl_path, and return whether there was one to append.""" |
| 149 | + if not stats_history_csv.exists(): |
| 150 | + _log(logs, f"No {stats_history_csv}; no turnover_window row") |
| 151 | + return False |
| 152 | + counts = window_counts(stats_history_csv, start) |
| 153 | + if counts is None: |
| 154 | + _log(logs, f"No stats_history sample after the turnover start {start}; no turnover_window row") |
| 155 | + return False |
| 156 | + end, per_request = counts |
| 157 | + row = window_record(start, end, per_request, timestamp, tag, test_name) |
| 158 | + with open(jsonl_path, "a", encoding="utf-8") as f: |
| 159 | + f.write(json.dumps(row) + "\n") |
| 160 | + return True |
| 161 | + |
| 162 | + |
| 163 | +def _log(logs: TextIO, msg: str) -> None: |
| 164 | + print(msg, flush=True) |
| 165 | + logs.write(msg + "\n") |
| 166 | + logs.flush() |
0 commit comments