ezharjan commited on
Commit
d5fee4e
·
verified ·
1 Parent(s): 8e77610

LocalNet-Dynamics 1.0.0

Browse files
.gitattributes CHANGED
@@ -58,3 +58,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ dataset/localnet_dynamics.csv filter=lfs diff=lfs merge=lfs -text
62
+ dataset/raw/localnet_desktop-eth_20260920_123407.csv filter=lfs diff=lfs merge=lfs -text
63
+ figures/pdf/overview_timeline.pdf filter=lfs diff=lfs merge=lfs -text
64
+ figures/pdf/regimes.pdf filter=lfs diff=lfs merge=lfs -text
65
+ figures/pdf/tcp_vs_icmp.pdf filter=lfs diff=lfs merge=lfs -text
CITATION.cff ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this dataset, please cite it as below. The toolkit that produced it has its own citation in the source repository."
3
+ type: dataset
4
+ title: "LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset"
5
+ authors:
6
+ - family-names: "Ezharjan"
7
+ given-names: "Alexander"
8
+ version: 1.0.0
9
+ date-released: "2026-10-09"
10
+ license: MIT
11
+ url: "https://huggingface.co/datasets/ezharjan/LocalNetDynamics"
12
+ repository-code: "https://github.com/Ezharjan/LocalNetDynamicsDataset"
13
+ abstract: >-
14
+ A longitudinal telemetry dataset of a residential local area network,
15
+ sampled every 30 seconds around the clock from a wired desktop for 19 days.
16
+ Each sample records ICMP latency, jitter and loss to a reference host and to
17
+ the gateway, TCP connect time, cached and recursive DNS response time, HTTP
18
+ time-to-first-response and hourly WAN throughput tests, with time-of-day
19
+ features and rule-based reference labels for forecasting, anomaly detection
20
+ and quality-of-service research.
21
+ keywords:
22
+ - network telemetry
23
+ - latency
24
+ - jitter
25
+ - packet loss
26
+ - DNS
27
+ - throughput
28
+ - quality of service
29
+ - anomaly detection
30
+ - time series
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexander Ezharjan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: LocalNet-Dynamics
3
+ license: mit
4
+ language:
5
+ - en
6
+ tags:
7
+ - tabular
8
+ - timeseries
9
+ - networking
10
+ - telemetry
11
+ - latency
12
+ - jitter
13
+ - packet-loss
14
+ - dns
15
+ - wifi
16
+ - throughput
17
+ - qos
18
+ - anomaly-detection
19
+ task_categories:
20
+ - time-series-forecasting
21
+ - tabular-classification
22
+ - tabular-regression
23
+ annotations_creators:
24
+ - machine-generated
25
+ source_datasets:
26
+ - original
27
+ size_categories:
28
+ - 10K<n<100K
29
+ configs:
30
+ - config_name: default
31
+ data_files:
32
+ - split: train
33
+ path: dataset/localnet_dynamics.parquet
34
+ ---
35
+
36
+ # LocalNet-Dynamics
37
+
38
+ A longitudinal, high-resolution telemetry dataset of a residential local area
39
+ network, sampled every 30 seconds around the clock from a wired desktop for
40
+ 19 days (2026-09-20 to 2026-10-09). Each of the 54,617 rows is one sampling
41
+ epoch and combines ICMP latency, loss and jitter to a reference host and to
42
+ the gateway, TCP connect time, cached and recursive DNS response time, HTTP
43
+ time-to-first-response and hourly WAN throughput tests with time-of-day
44
+ features and rule-based reference labels.
45
+
46
+ - Author and point of contact: Alexander Ezharjan
47
+ - Dataset: https://huggingface.co/datasets/ezharjan/LocalNetDynamics
48
+ - Source code (collector, build pipeline, analysis): https://github.com/Ezharjan/LocalNetDynamicsDataset
49
+ - License: MIT (code and data)
50
+ - Version: 1.0.0
51
+
52
+ ## Intended uses
53
+
54
+ - Time-series forecasting of latency, jitter and loss. The capture shows
55
+ strong persistence (lag-1 autocorrelation of the log round-trip time 0.81,
56
+ still 0.42 after three hours) and almost no 24-hour periodicity (0.09 at a
57
+ one-day lag), so it rewards models that track regime changes rather than
58
+ seasonal ones.
59
+ - Unsupervised and semi-supervised anomaly detection, evaluated against the
60
+ reference labels and the episode tables in `dataset/analysis.json`.
61
+ - QoS classification (for example, whether a sample meets the requirements of
62
+ real-time voice, cloud gaming or video conferencing).
63
+ - Root-cause studies: the gateway probe, the TCP probe and the
64
+ cached-versus-recursive DNS timings make it possible to separate first-hop
65
+ degradation from path changes and from resolver degradation. The capture
66
+ contains worked examples of each.
67
+ - Studies of the relationship between ICMP loss and application-visible
68
+ latency (HTTP retransmission modes, DNS tails).
69
+
70
+ ## Collection site
71
+
72
+ | Item | Value |
73
+ |---|---|
74
+ | Vantage point | one desktop PC, host label `desktop-eth` |
75
+ | Link between client and router | wired Ethernet (the collector could not read the media type, see the limitations) |
76
+ | Client operating system | Windows 11 (build 26200), Python 3.12.12 |
77
+ | Gateway and resolver | the home router, a private address on the `192.168.1.0/24` LAN |
78
+ | Time zone | US Eastern, UTC-4 for the whole run |
79
+ | Reference host | `8.8.8.8` (ICMP and TCP port 443) |
80
+ | Access technology, advertised plan, router model | not recorded |
81
+ | Household usage during the run | normal use, not annotated |
82
+
83
+ ## Files
84
+
85
+ | File | Content |
86
+ |---|---|
87
+ | `dataset/localnet_dynamics.parquet` | consolidated dataset, one row per sample, typed columns (the file served by the dataset viewer) |
88
+ | `dataset/localnet_dynamics.csv` | the same table as CSV |
89
+ | `dataset/summary.json` | row counts, coverage, per-metric statistics, per-run label thresholds |
90
+ | `dataset/analysis.json` | every number quoted in this card: profiles, regimes, episodes, conditional statistics, autocorrelation, speed-test quality |
91
+ | `dataset/raw/localnet_desktop-eth_20260920_123407.csv` | raw measurements of the collection run, exactly as written by the collector |
92
+ | `dataset/raw/localnet_desktop-eth_20260920_123407.json` | configuration, environment, detected network and running summary of that run |
93
+ | `figures/png/`, `figures/pdf/` | the ten figures below, as 200 dpi PNG and as vector PDF |
94
+ | `scripts/` | collector, builder, annotation tool, analysis, plotting and packaging scripts |
95
+ | `tests/` | pytest suite |
96
+
97
+ The consolidated files are produced from the raw files by
98
+ `scripts/build_dataset.py`; the raw files are never edited. No manual event
99
+ annotations were recorded during this run, so there is no `events.csv`.
100
+
101
+ ## Findings
102
+
103
+ The numbers in this section are computed by `scripts/analyze.py` and stored in
104
+ `dataset/analysis.json`.
105
+
106
+ ### Overview
107
+
108
+ ![Overview timeline](figures/png/overview_timeline.png)
109
+
110
+ 54,617 samples from 2026-09-20 12:34 to 2026-10-09 15:49 local time, 99.1 % of
111
+ the samples expected at the 30-second interval. 345 gaps are exactly 60 s,
112
+ the tick skipped after an hourly speed test; 78 gaps are longer, up to 122 s,
113
+ 53 of them after a speed test that overran two ticks and the rest after
114
+ samples whose probes waited for their timeouts. The median round-trip time
115
+ to 8.8.8.8 is 11.1 ms (95th percentile 22.3 ms), the median first-hop
116
+ round-trip time 0.2 ms, the median TCP handshake 14.5 ms.
117
+
118
+ ### Two regimes
119
+
120
+ A single least-squares change point in the daily share of samples with ICMP
121
+ loss falls on 2026-09-30 and divides the capture into two ten-day halves:
122
+
123
+ | | Sep 20 to Sep 29 | Sep 30 to Oct 9 |
124
+ |---|---|---|
125
+ | samples | 27,020 | 27,597 |
126
+ | samples with at least one lost echo | 23.2 % | 5.3 % |
127
+ | mean packet loss | 2.98 % | 0.57 % |
128
+ | round-trip time, median / p95 / p99 | 11.9 / 24.3 / 28.4 ms | 10.8 / 14.2 / 25.5 ms |
129
+ | jitter, median / p95 | 2.22 / 9.22 ms | 0.78 / 4.56 ms |
130
+ | HTTP response, median / p95 | 87.7 / 1,094 ms | 77.6 / 157 ms |
131
+ | HTTP responses slower than 1 s | 5.87 % | 1.09 % |
132
+ | recursive DNS, median | 62.5 ms | 56.2 ms |
133
+ | samples with any label | 38.9 % | 9.2 % |
134
+
135
+ ![Regimes](figures/png/regimes.png)
136
+
137
+ ![Labels](figures/png/labels.png)
138
+
139
+ ### Loss: daytime, weekdays, upstream of the gateway
140
+
141
+ ![Diurnal profile](figures/png/diurnal_profile.png)
142
+
143
+ ![Calendar heat maps](figures/png/calendar_heatmaps.png)
144
+
145
+ 14.1 % of all samples lost at least one of their ten echoes; 6,309 lost
146
+ exactly one, 1,092 two, 230 three, 41 four. On weekdays the hourly share of
147
+ samples with loss rises from 6 to 8 % between midnight and 05:00 to 25.2 % at
148
+ 08:00 and stays above 20 % until 16:00; on weekends it stays between 6 % and
149
+ 14 % all day. Weekdays as a whole have 15.2 % of samples with loss, weekends
150
+ 10.5 %. Outside the four outages, the gateway lost a packet in exactly one
151
+ sample, so the loss sits beyond the first hop.
152
+
153
+ ![Loss anatomy](figures/png/loss_anatomy.png)
154
+
155
+ Loss is only weakly bursty: a sample that follows a lossy sample is lossy with
156
+ probability 0.30 against a base rate of 0.14, and the autocorrelation of the
157
+ loss indicator is 0.18 at lag 1. The other probes show what a lost echo means:
158
+
159
+ | | no loss | 1 of 10 lost | 2 or more lost |
160
+ |---|---|---|---|
161
+ | samples | 46,907 | 6,309 | 1,383 |
162
+ | round-trip time, median | 11.0 ms | 11.8 ms | 12.6 ms |
163
+ | jitter, median | 1.00 ms | 2.12 ms | 3.29 ms |
164
+ | TCP handshake, median | 14.5 ms | 14.3 ms | 14.4 ms |
165
+ | HTTP responses slower than 1 s | 2.54 % | 7.47 % | 16.34 % |
166
+ | recursive DNS slower than 200 ms | 1.75 % | 5.22 % | 9.60 % |
167
+
168
+ The HTTP response time has a smooth body with a median of 81.9 ms and a 95th
169
+ percentile of 271 ms, then discrete modes: 2.48 % of responses fall between
170
+ 1.0 and 1.4 s and 0.55 % between 3.9 and 4.4 s. Their timing matches the
171
+ retransmission timers of the operating system's DNS client and TCP stack (one
172
+ second, then multiples of it), and they occur three to six times more often in
173
+ samples that also lost an echo, so they are lost packets waiting out a timer
174
+ rather than slow servers: the mechanism by which an echo lost in a ten-second
175
+ burst becomes a one-second stall for an application.
176
+
177
+ ### Latency episodes: path changes and a first-hop event
178
+
179
+ ![Degradation anatomy](figures/png/degradation_anatomy.png)
180
+
181
+ Runs of the high-latency label, merged across gaps of up to ten samples, give
182
+ nine episodes of 30 minutes or more; they contain 88.4 % of all high-latency
183
+ labels. Each is classified from the probe that moved: *first hop* if the
184
+ median gateway round-trip time exceeds the run's gateway threshold (5.2 ms),
185
+ *path change* if the median minimum ICMP time or the median fastest TCP
186
+ handshake rises at least 5 ms above its run median (10.0 and 12.3 ms), and
187
+ *queueing* otherwise.
188
+
189
+ | start (local) | end (local) | hours | ICMP min | ICMP mean | TCP fastest | gateway | kind |
190
+ |---|---|---|---|---|---|---|---|
191
+ | Mon Sep 21 22:34 | Tue Sep 22 01:05 | 2.52 | 20.0 | 26.4 | 25.7 | 0.0 | path change |
192
+ | Tue Sep 22 01:27 | 02:41 | 1.23 | 10.0 | 20.4 | 20.1 | 0.0 | path change |
193
+ | Tue Sep 22 02:47 | 03:44 | 0.95 | 11.0 | 21.1 | 19.5 | 0.0 | path change |
194
+ | Thu Sep 24 23:51 | Fri Sep 25 01:16 | 1.42 | 11.0 | 22.3 | 20.1 | 0.0 | path change |
195
+ | Sat Sep 26 14:07 | 14:54 | 0.78 | 14.0 | 23.5 | 18.1 | 11.4 | first hop |
196
+ | Sat Sep 26 15:01 | 15:32 | 0.52 | 14.0 | 22.0 | 18.1 | 11.2 | first hop |
197
+ | Sat Sep 26 16:36 | 18:17 | 1.68 | 14.0 | 23.7 | 20.7 | 10.6 | first hop |
198
+ | Sun Sep 27 00:00 | 06:16 | 6.28 | 17.0 | 25.6 | 23.8 | 0.0 | path change |
199
+ | Tue Sep 29 21:21 | Wed Sep 30 07:34 | 10.22 | 20.0 | 24.8 | 24.5 | 0.0 | path change |
200
+
201
+ Values are medians over the episode, in milliseconds; an end time without a
202
+ date is on the start date. The six path changes fall on four nights and all
203
+ lie between 21:21 and 07:34. In every one of them the fastest TCP handshake
204
+ sits 7 to 13 ms above its 12.3 ms baseline, the gateway is untouched, and the
205
+ DNS probe, whose queries the gateway forwards to the upstream resolver, stays
206
+ within 4 ms of its 36 ms median, so the extra delay lies on the route towards
207
+ 8.8.8.8, beyond the first hop and beyond the point where the path to the
208
+ resolver branches off. The three first-hop episodes are one event on the
209
+ afternoon of Saturday September 26: the gateway answered in 10 to 11 ms
210
+ instead of 0.2 ms, every other probe inherited the delay, and that day holds
211
+ 507 of the 560 gateway-degraded labels.
212
+
213
+ ### Outages
214
+
215
+ | start (local) | duration | samples | gateway reachable |
216
+ |---|---|---|---|
217
+ | Mon Sep 21 13:03 | 2.0 min | 4 | no |
218
+ | Thu Sep 24 07:10 | 2.5 min | 5 | no |
219
+ | Sat Sep 26 13:11 | 2.5 min | 5 | no |
220
+ | Tue Oct 6 02:51 | 2.0 min | 4 | no |
221
+
222
+ Every outage took the gateway down together with the target, with name
223
+ resolution failing as well (`getaddrinfo failed` in the `notes` column), so
224
+ all four were first-hop events. The ISP path never failed on its own during
225
+ the capture. Outages account for 18 samples, 0.03 % of the dataset.
226
+
227
+ ### The TCP/ICMP split
228
+
229
+ ![TCP versus ICMP](figures/png/tcp_vs_icmp.png)
230
+
231
+ Over the whole capture the fastest TCP handshake exceeds the minimum ICMP time
232
+ by 2.27 ms (median). From 22:00 on October 6 the share of samples in which it
233
+ exceeds it by more than 5 ms jumps from 7.2 % to 63.7 %, and the fastest
234
+ handshake becomes bimodal (first quartile 12.9 ms, median 18.6 ms, third
235
+ quartile 22.2 ms) while the ICMP minimum stays at 10 ms. The ICMP and TCP
236
+ probes address the same host, so the difference is in how the two kinds of
237
+ flow are routed; a monitor that relies on ping alone would not see the change.
238
+
239
+ ### DNS
240
+
241
+ The "cached" probe asks the gateway resolver for `example.com`, which it has
242
+ answered before, yet its median is 36.0 ms (5th percentile 17 ms; only 3.4 %
243
+ of answers arrive within 15 ms). The gateway therefore forwards every query
244
+ upstream rather than serving it from a local cache, and the column measures
245
+ the upstream resolver's responsiveness. The recursive probe (a random name
246
+ under `example.com`) has a median of 59.2 ms, 20.2 ms above the cached probe
247
+ in the same sample; 2.35 % of recursive lookups take longer than 200 ms and
248
+ the 99th percentile is 1,266 ms. 24 samples recorded a DNS timeout, 14 of
249
+ them during the four outages (the other four outage samples failed with a
250
+ socket error instead).
251
+
252
+ ### Memory
253
+
254
+ ![Autocorrelation](figures/png/autocorrelation.png)
255
+
256
+ | lag | 30 s | 5 min | 30 min | 3 h | 12 h | 24 h |
257
+ |---|---|---|---|---|---|---|
258
+ | log round-trip time | 0.81 | 0.76 | 0.68 | 0.42 | 0.18 | 0.09 |
259
+ | jitter | 0.44 | 0.42 | 0.36 | 0.25 | 0.23 | 0.17 |
260
+ | lost-echo indicator | 0.18 | 0.17 | 0.16 | 0.14 | 0.04 | 0.10 |
261
+ | fastest TCP handshake | 0.28 | 0.15 | 0.14 | 0.09 | 0.04 | 0.02 |
262
+ | recursive DNS | 0.04 | 0.02 | 0.02 | 0.02 | 0.00 | 0.01 |
263
+ | HTTP | 0.06 | 0.05 | 0.03 | 0.04 | 0.02 | 0.01 |
264
+
265
+ Latency is persistent for hours and has no daily cycle at this site; DNS and
266
+ HTTP timings are memoryless at every lag.
267
+
268
+ ### WAN throughput
269
+
270
+ ![Speed tests](figures/png/speedtest.png)
271
+
272
+ 460 hourly speed tests ran through the `speedtest-cli` Python fallback with no
273
+ pinned server and used 162 different servers. 79 tests could not measure the
274
+ server's latency (the fallback encodes that failure as a value of 600,000 ms
275
+ or more; the builder sets it to missing), 7 reported a download of 0 Mbit/s
276
+ and 4 an upload of 0 Mbit/s. Download: median 34.7 Mbit/s, 90th percentile
277
+ 183 Mbit/s, maximum 480.7 Mbit/s; among the ten most used servers the
278
+ per-server median ranges from 20.9 to 371.8 Mbit/s. Upload: median
279
+ 28.6 Mbit/s, 90th percentile 40.3 Mbit/s, maximum 54.2 Mbit/s. The median
280
+ download is 61.5 Mbit/s for the 95 tests started between 00:00 and 04:59 and
281
+ 22.0 Mbit/s for the 156 started between 09:00 and 16:59. The download column is a lower bound on
282
+ the access link and depends heavily on the server; the upload column is more
283
+ consistent. Loaded latency was not measured because the official Ookla CLI was
284
+ not installed.
285
+
286
+ ## Measurement protocol
287
+
288
+ One sample is taken at every tick of a fixed schedule (`start + k * interval`).
289
+ Within a sample the following probes run concurrently:
290
+
291
+ - ICMP: `ping_count` (10) echo requests to the target and `gateway_ping_count`
292
+ (5) to the default gateway, one second apart, each waiting at most
293
+ `ping_timeout` (2 s) for its reply. Per-reply round-trip times are parsed
294
+ from the output of the operating system's `ping`.
295
+ - TCP: `tcp_count` (5) TCP handshakes to `target:443`, 0.2 s apart, timed with
296
+ a high-resolution clock from `connect()` start to completion.
297
+ - DNS: two UDP queries (type A, recursion desired) sent directly to the
298
+ configured resolver, bypassing the operating-system cache. The first asks for
299
+ `dns_host` (`example.com`), which the resolver serves from its cache after
300
+ the first sample and therefore measures the resolver's responsiveness. The
301
+ second asks for a random 12-hexadecimal-character subdomain of `dns_host`,
302
+ which can never be cached and therefore measures a full recursive
303
+ resolution. A response with rcode NOERROR or NXDOMAIN is a valid measurement.
304
+ - HTTP: one GET request for `http_url`
305
+ (`http://www.msftconnecttest.com/connecttest.txt`) with the system proxy
306
+ bypassed, timed until the response headers have been received.
307
+ - Wi-Fi: link metrics read from the operating system
308
+ (`netsh wlan show interfaces`, `iw dev <if> link`, `system_profiler
309
+ SPAirPortDataType`).
310
+
311
+ After the concurrent probes, and only on their own cadence (every hour in the
312
+ published run), the heavy tests run: an Ookla speed test and/or an `iperf3`
313
+ test. Because they run after the latency probes of the same sample, they do
314
+ not influence that sample's latency columns; a sample that includes a speed
315
+ test usually overruns the interval, and the collector then skips to the next
316
+ tick.
317
+
318
+ The default gateway, the interface type and the resolver are detected at start
319
+ and re-detected every 15 minutes (or within a minute after the gateway probe
320
+ loses every packet). System sleep is inhibited for the duration of the run.
321
+
322
+ Run configuration of the published capture: interval 30 s, 10 echoes to
323
+ `8.8.8.8` and 5 to the gateway with a 2 s timeout, 5 TCP handshakes to port
324
+ 443, DNS probes against the gateway resolver with a 3 s timeout, HTTP probe
325
+ with a 5 s timeout, Wi-Fi metrics enabled, SSID not recorded, speed test every
326
+ hour with no pinned server, no iperf3 server, collector version 2.0.0.
327
+
328
+ ## Schema
329
+
330
+ Empty cells mean "not measured or failed"; the `notes` column records the
331
+ reason (for example `ping: no replies`, `dns recursive: timeout`,
332
+ `speedtest (ookla) failed: ...`). Times are in milliseconds unless the column
333
+ name says otherwise.
334
+
335
+ ### Identity and time
336
+
337
+ | Column | Type | Description |
338
+ |---|---|---|
339
+ | `run_id` | string | collection run identifier, `<host_label_>YYYYMMDD_HHMMSS` in local time of the run start |
340
+ | `host_label` | string | free-text label of the vantage point (`--host-label`), empty if not given |
341
+ | `sample_index` | int | 0-based row number within the run |
342
+ | `timestamp_utc` | string | sample start, ISO 8601 UTC, e.g. `2026-09-05T14:00:00Z` |
343
+ | `timestamp_local` | string | sample start in the collector's local time with UTC offset, e.g. `2026-09-05T10:00:00-04:00` |
344
+ | `epoch_s` | int | sample start as Unix time (seconds) |
345
+ | `elapsed_s` | float | seconds since the start of the run |
346
+ | `link_type` | string | `wifi`, `ethernet`, `other` or `unknown`: the interface that carries the default route |
347
+ | `gateway_ip` | string | default gateway (private address) |
348
+ | `dns_server` | string | resolver used for the DNS probes |
349
+ | `target` | string | host used for the ICMP and TCP probes |
350
+
351
+ ### Run context (added by the builder)
352
+
353
+ | Column | Type | Description |
354
+ |---|---|---|
355
+ | `collector_version` | string | version of `collect_data.py` that wrote the run |
356
+ | `collector_os` | string | `Windows`, `Linux` or `macOS` |
357
+ | `interval_s` | float | configured sampling interval of the run |
358
+ | `rtt_resolution_ms` | float | resolution of the ICMP columns: 1.0 on Windows, 0.001 elsewhere |
359
+
360
+ ### Time features (added by the builder, from `timestamp_local`)
361
+
362
+ | Column | Type | Description |
363
+ |---|---|---|
364
+ | `date_local` | string | local calendar date `YYYY-MM-DD` |
365
+ | `hour_local` | int | local hour 0-23 |
366
+ | `weekday_local` | int | 0 = Monday ... 6 = Sunday |
367
+ | `is_weekend` | int | 1 on Saturday and Sunday |
368
+ | `gap_before_s` | float | seconds since the previous sample of the same run; larger than `interval_s` after a skipped tick or a sleep/outage gap |
369
+
370
+ ### Target latency (ICMP)
371
+
372
+ | Column | Type | Description |
373
+ |---|---|---|
374
+ | `rtt_min_ms` | float | minimum round-trip time of the received replies |
375
+ | `rtt_avg_ms` | float | arithmetic mean |
376
+ | `rtt_median_ms` | float | median |
377
+ | `rtt_max_ms` | float | maximum |
378
+ | `rtt_stddev_ms` | float | population standard deviation of the received replies (the `mdev` of Linux `ping`) |
379
+ | `jitter_ms` | float | mean absolute difference between consecutive received replies (packet delay variation in the sense of RFC 3393, applied to round-trip times); empty when fewer than two replies were received |
380
+ | `packets_sent` | int | echo requests sent (`ping_count`) |
381
+ | `packets_received` | int | replies received |
382
+ | `packet_loss_pct` | float | `100 * (sent - received) / sent` |
383
+
384
+ ### Gateway latency (ICMP to the default gateway)
385
+
386
+ | Column | Type | Description |
387
+ |---|---|---|
388
+ | `gateway_rtt_min_ms` | float | minimum round-trip time |
389
+ | `gateway_rtt_avg_ms` | float | mean |
390
+ | `gateway_rtt_max_ms` | float | maximum |
391
+ | `gateway_jitter_ms` | float | mean absolute consecutive difference |
392
+ | `gateway_packet_loss_pct` | float | loss in percent |
393
+
394
+ ### TCP, DNS and HTTP
395
+
396
+ | Column | Type | Description |
397
+ |---|---|---|
398
+ | `tcp_connect_min_ms` | float | fastest of the TCP handshakes to `target:443` |
399
+ | `tcp_connect_median_ms` | float | median handshake time |
400
+ | `dns_resolve_ms` | float | response time of the resolver for `dns_host` (cache-served after the first sample) |
401
+ | `dns_recursive_ms` | float | response time for a random subdomain of `dns_host` (full recursive lookup) |
402
+ | `http_ms` | float | time to the response headers of `http_url`, including the operating-system name lookup, the TCP handshake and the request |
403
+ | `http_status` | int | HTTP status code of that response |
404
+
405
+ ### Wi-Fi link (empty on wired links)
406
+
407
+ | Column | Type | Description |
408
+ |---|---|---|
409
+ | `wifi_ssid` | string | network name; only recorded with `--record-ssid` |
410
+ | `wifi_signal_pct` | int | link quality 0-100: the value reported by Windows; on Linux and macOS derived from RSSI with the Windows mapping `quality = 2 * (rssi + 100)` clipped to 0-100 |
411
+ | `wifi_rssi_dbm` | float | received signal strength: as reported on Linux and macOS; on Windows derived from the quality with `rssi = quality / 2 - 100` |
412
+ | `wifi_rx_mbps` | float | negotiated receive PHY rate (Mbit/s) |
413
+ | `wifi_tx_mbps` | float | negotiated transmit PHY rate (Mbit/s); equals the receive rate on macOS, which reports one rate |
414
+ | `wifi_channel` | int | channel number |
415
+ | `wifi_band_ghz` | float | 2.4, 5 or 6 |
416
+ | `wifi_phy` | string | standard in use, e.g. `802.11ax` |
417
+
418
+ ### WAN throughput (rows in which a speed test ran)
419
+
420
+ | Column | Type | Description |
421
+ |---|---|---|
422
+ | `download_mbps` | float | download throughput (Mbit/s) |
423
+ | `upload_mbps` | float | upload throughput (Mbit/s) |
424
+ | `speedtest_ping_ms` | float | idle latency to the speed-test server as reported by the tool; missing when the `speedtest-cli` fallback could not measure it |
425
+ | `download_loaded_latency_ms` | float | interquartile-mean latency measured during the download (Ookla CLI only) |
426
+ | `upload_loaded_latency_ms` | float | interquartile-mean latency measured during the upload (Ookla CLI only) |
427
+ | `speedtest_server_id` | int | Ookla server id |
428
+ | `speedtest_server` | string | server name and location |
429
+
430
+ ### LAN throughput (rows in which an iperf3 test ran)
431
+
432
+ | Column | Type | Description |
433
+ |---|---|---|
434
+ | `lan_throughput_mbps` | float | TCP throughput to the LAN iperf3 server (Mbit/s) |
435
+ | `lan_retransmits` | int | TCP retransmissions during the test, when reported |
436
+
437
+ ### Reference labels (added by the builder)
438
+
439
+ | Column | Type | Rule |
440
+ |---|---|---|
441
+ | `label_outage` | int | `packets_received == 0` while `packets_sent > 0` |
442
+ | `label_packet_loss` | int | `0 < packet_loss_pct < 100` |
443
+ | `label_high_latency` | int | `rtt_avg_ms > T_rtt` |
444
+ | `label_high_jitter` | int | `jitter_ms > T_jitter` |
445
+ | `label_gateway_degraded` | int | `gateway_rtt_avg_ms > T_gateway` or `gateway_packet_loss_pct > 0` |
446
+ | `label_anomaly` | int | any of the above |
447
+
448
+ The thresholds are computed per run from that run's own distribution with a
449
+ robust rule, so they adapt to the baseline of the site without being pulled by
450
+ the outliers they are meant to find:
451
+
452
+ ```text
453
+ T = median + max(k * 1.4826 * MAD, absolute floor, relative floor * median)
454
+ ```
455
+
456
+ with `k = 5`, the median absolute deviation `MAD`, and the floors
457
+ 10 ms / 50 % for `rtt_avg_ms`, 5 ms / 100 % for `jitter_ms` and
458
+ 5 ms / 100 % for `gateway_rtt_avg_ms`. A threshold is not computed (and the
459
+ label stays 0) for runs with fewer than 20 valid values. For the published run
460
+ the thresholds are 21.1 ms (`rtt_avg_ms`), 6.0 ms (`jitter_ms`) and 5.2 ms
461
+ (`gateway_rtt_avg_ms`); the values used for each run are stored in
462
+ `dataset/summary.json`. These labels are derived from the measurements
463
+ themselves; they are reference points for evaluating detectors, not
464
+ independent ground truth.
465
+
466
+ ### Manual annotations and notes
467
+
468
+ | Column | Type | Description |
469
+ |---|---|---|
470
+ | `event_category` | string | categories of the manual events covering the sample time, joined with ` \| `; one of `load`, `outage`, `maintenance`, `environment`, `isp`, `device`, `other` |
471
+ | `event_description` | string | the corresponding free-text descriptions |
472
+ | `sample_duration_s` | float | wall-clock time the sample's probes took |
473
+ | `notes` | string | probe errors and status messages, `; `-separated |
474
+
475
+ ## Validation performed by the builder
476
+
477
+ - Rows with a malformed `timestamp_utc` are dropped and duplicate
478
+ `(run_id, timestamp_utc)` pairs are reduced to the first occurrence (none in
479
+ the published run).
480
+ - Loss percentages outside 0-100 are set to missing (none in the published
481
+ run).
482
+ - `speedtest_ping_ms` values of 600,000 ms or more are set to missing. The
483
+ `speedtest-cli` fallback scores each failed latency attempt as 3,600 s and
484
+ averages three attempts over six, so one failed attempt already yields
485
+ 600,000 ms and three yield 1,800,000 ms. The raw file keeps the original
486
+ values; 79 of the 460 speed-test rows are affected. Collector version 2.0.1
487
+ no longer records such values.
488
+
489
+ ## Statistics
490
+
491
+ <!-- BEGIN GENERATED STATISTICS -->
492
+ Generated by `scripts/build_dataset.py` on 2026-10-10T05:42:01Z from 1 collection run(s).
493
+
494
+ | Item | Value |
495
+ |---|---|
496
+ | Rows | 54,617 |
497
+ | Columns | 67 |
498
+ | First sample (UTC) | 2026-09-20T16:34:22Z |
499
+ | Last sample (UTC) | 2026-10-09T19:49:43Z |
500
+ | Span | 19.14 days |
501
+ | Sampling coverage | 99.1 % of the samples expected at the configured interval |
502
+ | Manual event annotations | 0 |
503
+
504
+ | Run | Vantage | Link | OS | Interval | Rows | Span | Coverage |
505
+ |---|---|---|---|---|---|---|---|
506
+ | desktop-eth_20260920_123407 | desktop-eth | unknown (54617) | Windows | 30 s | 54,617 | 459.26 h | 99.1 % |
507
+
508
+ | Metric | n | Median | Mean | p95 | Max |
509
+ |---|---|---|---|---|---|
510
+ | rtt_avg_ms | 54,599 | 11.1 | 12.581 | 22.3 | 288.6 |
511
+ | rtt_min_ms | 54,599 | 10.0 | 10.432 | 14.0 | 263.0 |
512
+ | rtt_max_ms | 54,599 | 13.0 | 17.869 | 32.0 | 373.0 |
513
+ | jitter_ms | 54,599 | 1.0 | 2.306 | 7.667 | 59.778 |
514
+ | packet_loss_pct | 54,617 | 0.0 | 1.763 | 10.0 | 100.0 |
515
+ | gateway_rtt_avg_ms | 54,599 | 0.2 | 0.321 | 0.8 | 89.4 |
516
+ | gateway_packet_loss_pct | 54,617 | 0.0 | 0.033 | 0.0 | 100.0 |
517
+ | tcp_connect_median_ms | 54,598 | 14.484 | 19.311 | 32.127 | 1524.463 |
518
+ | dns_resolve_ms | 54,595 | 36.026 | 43.594 | 74.878 | 3252.214 |
519
+ | dns_recursive_ms | 54,590 | 59.242 | 87.275 | 106.31 | 25645.041 |
520
+ | http_ms | 54,565 | 81.911 | 154.745 | 271.36 | 13111.02 |
521
+ | wifi_signal_pct | 4 | 85.0 | 85.75 | 88.4 | 89.0 |
522
+ | wifi_rssi_dbm | 4 | -57.5 | -57.125 | -55.8 | -55.5 |
523
+ | wifi_rx_mbps | 4 | 866.7 | 866.7 | 866.7 | 866.7 |
524
+ | download_mbps | 460 | 34.725 | 68.463 | 318.275 | 480.72 |
525
+ | upload_mbps | 460 | 28.625 | 26.121 | 41.142 | 54.17 |
526
+ | speedtest_ping_ms | 381 | 52.058 | 93.665 | 196.381 | 1167.189 |
527
+
528
+ | Reference label | Rows | Share |
529
+ |---|---|---|
530
+ | label_outage | 18 | 0.033 % |
531
+ | label_packet_loss | 7,692 | 14.084 % |
532
+ | label_high_latency | 3,067 | 5.615 % |
533
+ | label_high_jitter | 5,074 | 9.29 % |
534
+ | label_gateway_degraded | 560 | 1.025 % |
535
+ | label_anomaly | 13,036 | 23.868 % |
536
+
537
+ <!-- END GENERATED STATISTICS -->
538
+
539
+ ## Known limitations and biases
540
+
541
+ - Single vantage point, single run. Absolute values reflect one site's access
542
+ technology, router, cabling and ISP routing. Relative variation, the
543
+ structure of episodes and the probe-to-probe relationships transfer better
544
+ than absolute baselines.
545
+ - `link_type` is `unknown` for every row. The PowerShell route query returned
546
+ nothing on this machine, the collector fell back to `route print`, and that
547
+ fallback does not report the media type. The vantage point is a wired
548
+ desktop (host label `desktop-eth`, median first-hop round-trip time 0.2 ms).
549
+ Four rows carry Wi-Fi link metrics (channel 44 or 157, 5 GHz, 802.11ac,
550
+ 866.7 Mbit/s): a wireless adapter on the same machine was connected at those
551
+ moments. Their first-hop round-trip times (0.0 to 1.2 ms) and target
552
+ latencies match the wired baseline, so the default route stayed on the
553
+ wired link.
554
+ - ICMP resolution on Windows is 1 ms and sub-millisecond replies are stored as
555
+ 0; jitter and standard deviation computed from such values contain
556
+ quantisation noise, and the gateway columns are mostly 0 for this wired
557
+ site. Use `tcp_connect_*` for sub-millisecond latency, or collect on
558
+ Linux/macOS. `rtt_resolution_ms` states the resolution of each run.
559
+ - ICMP is handled differently from user traffic by some routers and hosts
560
+ (rate limiting, de-prioritisation). The TCP connect and HTTP columns measure
561
+ the transport and application paths that applications actually use, and the
562
+ October 6 TCP/ICMP split shows that the two can be routed differently.
563
+ - The 10-echo burst characterises latency over roughly ten seconds of each
564
+ interval; events shorter than that between samples are not observed.
565
+ - The DNS "cached" probe is cached at the upstream resolver, not at the
566
+ gateway: at this site the gateway forwards every query, so the column
567
+ measures the upstream resolver plus the forwarding hop.
568
+ - The DNS "recursive" probe generates NXDOMAIN answers for random names; a
569
+ resolver that applies aggressive negative caching or that intercepts
570
+ NXDOMAIN (ISP search redirection) still answers, but its timing reflects that
571
+ behaviour.
572
+ - The HTTP probe includes the operating system's name lookup for the URL's
573
+ host, which is normally cached; its discrete modes near 1.1, 1.3 and 4.1 s
574
+ are retransmission timers waiting out lost packets, not propagation or
575
+ queueing delay.
576
+ - Speed tests were run with the `speedtest-cli` fallback, which uses the
577
+ Python interpreter's own HTTP transfers, and without a pinned server. The
578
+ download column is a lower bound that depends strongly on the chosen
579
+ server; 79 tests have no latency, 7 report 0 Mbit/s download and 4 report
580
+ 0 Mbit/s upload. Loaded latency is absent. Speed tests also load the
581
+ household link for about half a minute, which is visible to other devices,
582
+ and they leave a 60-second gap in the 30-second grid.
583
+ - The two halves of the capture differ markedly (see the findings). Models
584
+ trained on one half should be evaluated on the other.
585
+ - No manual event annotations were recorded, so the `event_*` columns are
586
+ empty and the causes of the episodes are inferred from the probes only.
587
+ - Gaps: system sleep, reboots and collector restarts appear as gaps
588
+ (`gap_before_s`) or as separate runs; ticks skipped after an overrun also
589
+ appear as gaps. The published run has none longer than 122 s.
590
+ - Clock: timestamps come from the system clock; `elapsed_s` uses a monotonic
591
+ clock and is unaffected by clock adjustments.
592
+
593
+ ## Privacy
594
+
595
+ The dataset does not contain public IP addresses, hostnames of household
596
+ devices, MAC addresses, Wi-Fi network names or per-device traffic. Gateway and
597
+ resolver addresses are private LAN addresses. The run metadata records the
598
+ operating system build, the Python version, the time zone and the private LAN
599
+ address of the collector. Speed-test rows name the test server, which was not
600
+ pinned and therefore only indicates the broad region of the site.
601
+
602
+ ## Citation
603
+
604
+ If you use the data:
605
+
606
+ ```bibtex
607
+ @dataset{ezharjan_localnetdynamics_data_2026,
608
+ author = {Ezharjan, Alexander},
609
+ title = {LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset},
610
+ year = {2026},
611
+ version = {1.0.0},
612
+ publisher = {Hugging Face},
613
+ url = {https://huggingface.co/datasets/ezharjan/LocalNetDynamics}
614
+ }
615
+ ```
616
+
617
+ If you use the collector, the build pipeline or the analysis code:
618
+
619
+ ```bibtex
620
+ @software{ezharjan_localnetdynamics_code_2026,
621
+ author = {Ezharjan, Alexander},
622
+ title = {LocalNet-Dynamics: collector, build pipeline and analysis toolkit for longitudinal home-network telemetry},
623
+ year = {2026},
624
+ version = {1.0.0},
625
+ url = {https://github.com/Ezharjan/LocalNetDynamicsDataset}
626
+ }
627
+ ```
dataset/analysis.json ADDED
@@ -0,0 +1,1504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_utc": "2026-10-10T05:42:03Z",
3
+ "overview": {
4
+ "rows": 54617,
5
+ "runs": 1,
6
+ "first_utc": "2026-09-20T16:34:22Z",
7
+ "last_utc": "2026-10-09T19:49:43Z",
8
+ "first_local": "2026-09-20T12:34:22-04:00",
9
+ "last_local": "2026-10-09T15:49:43-04:00",
10
+ "span_days": 19.14,
11
+ "full_days": 18,
12
+ "coverage_pct": 99.1,
13
+ "max_gap_s": 122.0,
14
+ "gaps_of_2_intervals": 345,
15
+ "gaps_over_2_intervals": 78,
16
+ "gaps_over_2_intervals_after_speedtest": 53,
17
+ "rows_with_notes": 59,
18
+ "wifi_rows": 4,
19
+ "link_types": {
20
+ "unknown": 54617
21
+ },
22
+ "metrics": {
23
+ "rtt_avg_ms": {
24
+ "n": 54599,
25
+ "median": 11.1,
26
+ "mean": 12.581,
27
+ "p95": 22.3,
28
+ "p99": 27.0,
29
+ "max": 288.6
30
+ },
31
+ "rtt_min_ms": {
32
+ "n": 54599,
33
+ "median": 10.0,
34
+ "mean": 10.432,
35
+ "p95": 14.0,
36
+ "p99": 22.0,
37
+ "max": 263.0
38
+ },
39
+ "rtt_max_ms": {
40
+ "n": 54599,
41
+ "median": 13.0,
42
+ "mean": 17.869,
43
+ "p95": 32.0,
44
+ "p99": 43.0,
45
+ "max": 373.0
46
+ },
47
+ "jitter_ms": {
48
+ "n": 54599,
49
+ "median": 1.0,
50
+ "mean": 2.306,
51
+ "p95": 7.667,
52
+ "p99": 11.333,
53
+ "max": 59.778
54
+ },
55
+ "packet_loss_pct": {
56
+ "n": 54617,
57
+ "median": 0.0,
58
+ "mean": 1.763,
59
+ "p95": 10.0,
60
+ "p99": 20.0,
61
+ "max": 100.0
62
+ },
63
+ "gateway_rtt_avg_ms": {
64
+ "n": 54599,
65
+ "median": 0.2,
66
+ "mean": 0.321,
67
+ "p95": 0.8,
68
+ "p99": 5.0,
69
+ "max": 89.4
70
+ },
71
+ "tcp_connect_min_ms": {
72
+ "n": 54598,
73
+ "median": 12.296,
74
+ "mean": 14.133,
75
+ "p95": 23.886,
76
+ "p99": 28.762,
77
+ "max": 1032.09
78
+ },
79
+ "tcp_connect_median_ms": {
80
+ "n": 54598,
81
+ "median": 14.484,
82
+ "mean": 19.311,
83
+ "p95": 32.127,
84
+ "p99": 38.784,
85
+ "max": 1524.463
86
+ },
87
+ "dns_resolve_ms": {
88
+ "n": 54595,
89
+ "median": 36.026,
90
+ "mean": 43.594,
91
+ "p95": 74.878,
92
+ "p99": 121.832,
93
+ "max": 3252.214
94
+ },
95
+ "dns_recursive_ms": {
96
+ "n": 54590,
97
+ "median": 59.242,
98
+ "mean": 87.275,
99
+ "p95": 106.31,
100
+ "p99": 1266.18,
101
+ "max": 25645.041
102
+ },
103
+ "http_ms": {
104
+ "n": 54565,
105
+ "median": 81.911,
106
+ "mean": 154.745,
107
+ "p95": 271.36,
108
+ "p99": 1375.212,
109
+ "max": 13111.02
110
+ },
111
+ "download_mbps": {
112
+ "n": 460,
113
+ "median": 34.725,
114
+ "mean": 68.463,
115
+ "p95": 318.275,
116
+ "p99": 417.581,
117
+ "max": 480.72
118
+ },
119
+ "upload_mbps": {
120
+ "n": 460,
121
+ "median": 28.625,
122
+ "mean": 26.121,
123
+ "p95": 41.142,
124
+ "p99": 44.101,
125
+ "max": 54.17
126
+ }
127
+ }
128
+ },
129
+ "hour_profile": [
130
+ {
131
+ "hour": 0,
132
+ "n": 2263,
133
+ "rtt_median": 11.4,
134
+ "rtt_p25": 10.7,
135
+ "rtt_p75": 15.5,
136
+ "rtt_p95": 27.44,
137
+ "jitter_median": 1.222,
138
+ "loss_share_pct": 6.41,
139
+ "loss_share_weekday_pct": 6.55,
140
+ "loss_share_weekend_pct": 5.88,
141
+ "http_p95": 160.456,
142
+ "http_over_1s_pct": 1.72,
143
+ "high_latency_pct": 19.93,
144
+ "gateway_p95": 0.6
145
+ },
146
+ {
147
+ "hour": 1,
148
+ "n": 2266,
149
+ "rtt_median": 11.4,
150
+ "rtt_p25": 10.8,
151
+ "rtt_p75": 15.9,
152
+ "rtt_p95": 25.383,
153
+ "jitter_median": 1.292,
154
+ "loss_share_pct": 7.28,
155
+ "loss_share_weekday_pct": 6.65,
156
+ "loss_share_weekend_pct": 9.64,
157
+ "http_p95": 146.393,
158
+ "http_over_1s_pct": 1.19,
159
+ "high_latency_pct": 13.72,
160
+ "gateway_p95": 0.8
161
+ },
162
+ {
163
+ "hour": 2,
164
+ "n": 2266,
165
+ "rtt_median": 11.4,
166
+ "rtt_p25": 10.778,
167
+ "rtt_p75": 15.9,
168
+ "rtt_p95": 25.59,
169
+ "jitter_median": 1.222,
170
+ "loss_share_pct": 8.25,
171
+ "loss_share_weekday_pct": 7.83,
172
+ "loss_share_weekend_pct": 9.83,
173
+ "http_p95": 149.275,
174
+ "http_over_1s_pct": 1.42,
175
+ "high_latency_pct": 13.55,
176
+ "gateway_p95": 0.8
177
+ },
178
+ {
179
+ "hour": 3,
180
+ "n": 2263,
181
+ "rtt_median": 11.2,
182
+ "rtt_p25": 10.683,
183
+ "rtt_p75": 13.845,
184
+ "rtt_p95": 25.44,
185
+ "jitter_median": 1.0,
186
+ "loss_share_pct": 7.69,
187
+ "loss_share_weekday_pct": 7.5,
188
+ "loss_share_weekend_pct": 8.39,
189
+ "http_p95": 135.124,
190
+ "http_over_1s_pct": 1.63,
191
+ "high_latency_pct": 12.77,
192
+ "gateway_p95": 0.8
193
+ },
194
+ {
195
+ "hour": 4,
196
+ "n": 2264,
197
+ "rtt_median": 11.0,
198
+ "rtt_p25": 10.6,
199
+ "rtt_p75": 12.133,
200
+ "rtt_p95": 24.548,
201
+ "jitter_median": 0.827,
202
+ "loss_share_pct": 6.71,
203
+ "loss_share_weekday_pct": 5.76,
204
+ "loss_share_weekend_pct": 10.32,
205
+ "http_p95": 130.753,
206
+ "http_over_1s_pct": 1.19,
207
+ "high_latency_pct": 10.51,
208
+ "gateway_p95": 0.8
209
+ },
210
+ {
211
+ "hour": 5,
212
+ "n": 2263,
213
+ "rtt_median": 11.0,
214
+ "rtt_p25": 10.6,
215
+ "rtt_p75": 11.9,
216
+ "rtt_p95": 24.6,
217
+ "jitter_median": 0.875,
218
+ "loss_share_pct": 9.81,
219
+ "loss_share_weekday_pct": 9.35,
220
+ "loss_share_weekend_pct": 11.55,
221
+ "http_p95": 135.304,
222
+ "http_over_1s_pct": 1.81,
223
+ "high_latency_pct": 10.38,
224
+ "gateway_p95": 0.8
225
+ },
226
+ {
227
+ "hour": 6,
228
+ "n": 2265,
229
+ "rtt_median": 11.0,
230
+ "rtt_p25": 10.6,
231
+ "rtt_p75": 12.7,
232
+ "rtt_p95": 24.0,
233
+ "jitter_median": 0.889,
234
+ "loss_share_pct": 13.6,
235
+ "loss_share_weekday_pct": 15.1,
236
+ "loss_share_weekend_pct": 7.97,
237
+ "http_p95": 263.324,
238
+ "http_over_1s_pct": 3.53,
239
+ "high_latency_pct": 7.42,
240
+ "gateway_p95": 0.8
241
+ },
242
+ {
243
+ "hour": 7,
244
+ "n": 2265,
245
+ "rtt_median": 11.1,
246
+ "rtt_p25": 10.6,
247
+ "rtt_p75": 12.4,
248
+ "rtt_p95": 20.305,
249
+ "jitter_median": 0.889,
250
+ "loss_share_pct": 17.26,
251
+ "loss_share_weekday_pct": 20.02,
252
+ "loss_share_weekend_pct": 6.92,
253
+ "http_p95": 151.028,
254
+ "http_over_1s_pct": 3.23,
255
+ "high_latency_pct": 4.06,
256
+ "gateway_p95": 0.8
257
+ },
258
+ {
259
+ "hour": 8,
260
+ "n": 2262,
261
+ "rtt_median": 11.1,
262
+ "rtt_p25": 10.5,
263
+ "rtt_p75": 12.333,
264
+ "rtt_p95": 16.5,
265
+ "jitter_median": 0.889,
266
+ "loss_share_pct": 21.75,
267
+ "loss_share_weekday_pct": 25.21,
268
+ "loss_share_weekend_pct": 8.81,
269
+ "http_p95": 1088.286,
270
+ "http_over_1s_pct": 5.57,
271
+ "high_latency_pct": 0.84,
272
+ "gateway_p95": 0.8
273
+ },
274
+ {
275
+ "hour": 9,
276
+ "n": 2262,
277
+ "rtt_median": 11.0,
278
+ "rtt_p25": 10.5,
279
+ "rtt_p75": 12.333,
280
+ "rtt_p95": 17.0,
281
+ "jitter_median": 1.0,
282
+ "loss_share_pct": 19.98,
283
+ "loss_share_weekday_pct": 23.12,
284
+ "loss_share_weekend_pct": 8.19,
285
+ "http_p95": 1070.512,
286
+ "http_over_1s_pct": 5.57,
287
+ "high_latency_pct": 0.53,
288
+ "gateway_p95": 0.8
289
+ },
290
+ {
291
+ "hour": 10,
292
+ "n": 2256,
293
+ "rtt_median": 11.0,
294
+ "rtt_p25": 10.6,
295
+ "rtt_p75": 12.333,
296
+ "rtt_p95": 16.0,
297
+ "jitter_median": 1.111,
298
+ "loss_share_pct": 18.26,
299
+ "loss_share_weekday_pct": 20.73,
300
+ "loss_share_weekend_pct": 9.03,
301
+ "http_p95": 324.732,
302
+ "http_over_1s_pct": 4.3,
303
+ "high_latency_pct": 0.84,
304
+ "gateway_p95": 0.8
305
+ },
306
+ {
307
+ "hour": 11,
308
+ "n": 2259,
309
+ "rtt_median": 11.1,
310
+ "rtt_p25": 10.6,
311
+ "rtt_p75": 12.4,
312
+ "rtt_p95": 15.222,
313
+ "jitter_median": 1.222,
314
+ "loss_share_pct": 19.17,
315
+ "loss_share_weekday_pct": 21.39,
316
+ "loss_share_weekend_pct": 10.78,
317
+ "http_p95": 326.073,
318
+ "http_over_1s_pct": 4.48,
319
+ "high_latency_pct": 0.35,
320
+ "gateway_p95": 0.6
321
+ },
322
+ {
323
+ "hour": 12,
324
+ "n": 2307,
325
+ "rtt_median": 11.0,
326
+ "rtt_p25": 10.5,
327
+ "rtt_p75": 12.4,
328
+ "rtt_p95": 16.0,
329
+ "jitter_median": 1.0,
330
+ "loss_share_pct": 20.42,
331
+ "loss_share_weekday_pct": 22.6,
332
+ "loss_share_weekend_pct": 12.98,
333
+ "http_p95": 1071.792,
334
+ "http_over_1s_pct": 5.33,
335
+ "high_latency_pct": 0.26,
336
+ "gateway_p95": 0.6
337
+ },
338
+ {
339
+ "hour": 13,
340
+ "n": 2375,
341
+ "rtt_median": 10.9,
342
+ "rtt_p25": 10.5,
343
+ "rtt_p75": 12.333,
344
+ "rtt_p95": 16.0,
345
+ "jitter_median": 1.0,
346
+ "loss_share_pct": 20.21,
347
+ "loss_share_weekday_pct": 22.91,
348
+ "loss_share_weekend_pct": 12.03,
349
+ "http_p95": 1055.948,
350
+ "http_over_1s_pct": 5.08,
351
+ "high_latency_pct": 0.97,
352
+ "gateway_p95": 0.8
353
+ },
354
+ {
355
+ "hour": 14,
356
+ "n": 2377,
357
+ "rtt_median": 11.0,
358
+ "rtt_p25": 10.5,
359
+ "rtt_p75": 12.6,
360
+ "rtt_p95": 19.4,
361
+ "jitter_median": 1.111,
362
+ "loss_share_pct": 20.87,
363
+ "loss_share_weekday_pct": 23.64,
364
+ "loss_share_weekend_pct": 12.5,
365
+ "http_p95": 1079.365,
366
+ "http_over_1s_pct": 5.56,
367
+ "high_latency_pct": 3.83,
368
+ "gateway_p95": 1.0
369
+ },
370
+ {
371
+ "hour": 15,
372
+ "n": 2356,
373
+ "rtt_median": 11.1,
374
+ "rtt_p25": 10.6,
375
+ "rtt_p75": 12.8,
376
+ "rtt_p95": 18.822,
377
+ "jitter_median": 1.111,
378
+ "loss_share_pct": 21.31,
379
+ "loss_share_weekday_pct": 23.91,
380
+ "loss_share_weekend_pct": 13.54,
381
+ "http_p95": 1076.688,
382
+ "http_over_1s_pct": 5.69,
383
+ "high_latency_pct": 2.97,
384
+ "gateway_p95": 1.0
385
+ },
386
+ {
387
+ "hour": 16,
388
+ "n": 2258,
389
+ "rtt_median": 11.1,
390
+ "rtt_p25": 10.6,
391
+ "rtt_p75": 12.5,
392
+ "rtt_p95": 17.7,
393
+ "jitter_median": 1.118,
394
+ "loss_share_pct": 19.53,
395
+ "loss_share_weekday_pct": 22.76,
396
+ "loss_share_weekend_pct": 10.46,
397
+ "http_p95": 1081.493,
398
+ "http_over_1s_pct": 5.68,
399
+ "high_latency_pct": 2.61,
400
+ "gateway_p95": 0.8
401
+ },
402
+ {
403
+ "hour": 17,
404
+ "n": 2252,
405
+ "rtt_median": 11.1,
406
+ "rtt_p25": 10.6,
407
+ "rtt_p75": 12.556,
408
+ "rtt_p95": 19.745,
409
+ "jitter_median": 1.111,
410
+ "loss_share_pct": 16.87,
411
+ "loss_share_weekday_pct": 18.82,
412
+ "loss_share_weekend_pct": 11.38,
413
+ "http_p95": 263.657,
414
+ "http_over_1s_pct": 3.78,
415
+ "high_latency_pct": 3.95,
416
+ "gateway_p95": 6.0
417
+ },
418
+ {
419
+ "hour": 18,
420
+ "n": 2258,
421
+ "rtt_median": 11.0,
422
+ "rtt_p25": 10.5,
423
+ "rtt_p75": 12.2,
424
+ "rtt_p95": 15.8,
425
+ "jitter_median": 1.111,
426
+ "loss_share_pct": 13.82,
427
+ "loss_share_weekday_pct": 14.11,
428
+ "loss_share_weekend_pct": 13.01,
429
+ "http_p95": 312.767,
430
+ "http_over_1s_pct": 3.63,
431
+ "high_latency_pct": 1.2,
432
+ "gateway_p95": 0.6
433
+ },
434
+ {
435
+ "hour": 19,
436
+ "n": 2255,
437
+ "rtt_median": 11.0,
438
+ "rtt_p25": 10.556,
439
+ "rtt_p75": 12.0,
440
+ "rtt_p95": 14.5,
441
+ "jitter_median": 1.0,
442
+ "loss_share_pct": 11.18,
443
+ "loss_share_weekday_pct": 11.73,
444
+ "loss_share_weekend_pct": 9.63,
445
+ "http_p95": 269.201,
446
+ "http_over_1s_pct": 3.24,
447
+ "high_latency_pct": 0.49,
448
+ "gateway_p95": 0.6
449
+ },
450
+ {
451
+ "hour": 20,
452
+ "n": 2257,
453
+ "rtt_median": 10.9,
454
+ "rtt_p25": 10.6,
455
+ "rtt_p75": 11.7,
456
+ "rtt_p95": 14.1,
457
+ "jitter_median": 1.0,
458
+ "loss_share_pct": 10.15,
459
+ "loss_share_weekday_pct": 9.49,
460
+ "loss_share_weekend_pct": 11.99,
461
+ "http_p95": 388.689,
462
+ "http_over_1s_pct": 2.75,
463
+ "high_latency_pct": 0.31,
464
+ "gateway_p95": 0.6
465
+ },
466
+ {
467
+ "hour": 21,
468
+ "n": 2257,
469
+ "rtt_median": 11.1,
470
+ "rtt_p25": 10.7,
471
+ "rtt_p75": 12.5,
472
+ "rtt_p95": 17.455,
473
+ "jitter_median": 1.222,
474
+ "loss_share_pct": 9.53,
475
+ "loss_share_weekday_pct": 8.29,
476
+ "loss_share_weekend_pct": 12.98,
477
+ "http_p95": 323.17,
478
+ "http_over_1s_pct": 2.53,
479
+ "high_latency_pct": 3.9,
480
+ "gateway_p95": 0.6
481
+ },
482
+ {
483
+ "hour": 22,
484
+ "n": 2251,
485
+ "rtt_median": 11.3,
486
+ "rtt_p25": 10.7,
487
+ "rtt_p75": 12.9,
488
+ "rtt_p95": 24.9,
489
+ "jitter_median": 1.222,
490
+ "loss_share_pct": 8.31,
491
+ "loss_share_weekday_pct": 7.67,
492
+ "loss_share_weekend_pct": 10.08,
493
+ "http_p95": 268.161,
494
+ "http_over_1s_pct": 2.13,
495
+ "high_latency_pct": 8.35,
496
+ "gateway_p95": 0.6
497
+ },
498
+ {
499
+ "hour": 23,
500
+ "n": 2260,
501
+ "rtt_median": 11.2,
502
+ "rtt_p25": 10.6,
503
+ "rtt_p75": 12.889,
504
+ "rtt_p95": 25.89,
505
+ "jitter_median": 1.111,
506
+ "loss_share_pct": 9.38,
507
+ "loss_share_weekday_pct": 8.58,
508
+ "loss_share_weekend_pct": 11.62,
509
+ "http_p95": 146.393,
510
+ "http_over_1s_pct": 1.55,
511
+ "high_latency_pct": 11.46,
512
+ "gateway_p95": 0.6
513
+ }
514
+ ],
515
+ "weekday_weekend": {
516
+ "weekday": {
517
+ "n": 41865,
518
+ "rtt_median": 11.1,
519
+ "rtt_p95": 20.3,
520
+ "loss_share_pct": 15.21,
521
+ "jitter_median": 1.0,
522
+ "http_median": 81.525
523
+ },
524
+ "weekend": {
525
+ "n": 12752,
526
+ "rtt_median": 11.2,
527
+ "rtt_p95": 24.8,
528
+ "loss_share_pct": 10.54,
529
+ "jitter_median": 1.111,
530
+ "http_median": 83.276
531
+ }
532
+ },
533
+ "daily": [
534
+ {
535
+ "date": "2026-09-20",
536
+ "weekday": 6,
537
+ "n": 1331,
538
+ "rtt_median": 10.7,
539
+ "rtt_p95": 13.2,
540
+ "rtt_min_median": 10.0,
541
+ "tcp_min_median": 11.933,
542
+ "loss_share_pct": 10.22,
543
+ "mean_loss_pct": 1.097,
544
+ "jitter_median": 0.889,
545
+ "http_p95": 370.934,
546
+ "anomaly_pct": 13.15,
547
+ "gateway_degraded": 9
548
+ },
549
+ {
550
+ "date": "2026-09-21",
551
+ "weekday": 0,
552
+ "n": 2852,
553
+ "rtt_median": 11.2,
554
+ "rtt_p95": 25.0,
555
+ "rtt_min_median": 10.0,
556
+ "tcp_min_median": 12.113,
557
+ "loss_share_pct": 21.18,
558
+ "mean_loss_pct": 3.166,
559
+ "jitter_median": 1.222,
560
+ "http_p95": 1093.809,
561
+ "anomaly_pct": 29.49,
562
+ "gateway_degraded": 5
563
+ },
564
+ {
565
+ "date": "2026-09-22",
566
+ "weekday": 1,
567
+ "n": 2860,
568
+ "rtt_median": 11.646,
569
+ "rtt_p95": 24.1,
570
+ "rtt_min_median": 10.0,
571
+ "tcp_min_median": 12.237,
572
+ "loss_share_pct": 19.9,
573
+ "mean_loss_pct": 2.367,
574
+ "jitter_median": 1.778,
575
+ "http_p95": 1065.949,
576
+ "anomaly_pct": 35.24,
577
+ "gateway_degraded": 7
578
+ },
579
+ {
580
+ "date": "2026-09-23",
581
+ "weekday": 2,
582
+ "n": 2853,
583
+ "rtt_median": 12.0,
584
+ "rtt_p95": 16.9,
585
+ "rtt_min_median": 10.0,
586
+ "tcp_min_median": 12.142,
587
+ "loss_share_pct": 33.93,
588
+ "mean_loss_pct": 4.707,
589
+ "jitter_median": 1.125,
590
+ "http_p95": 1295.07,
591
+ "anomaly_pct": 38.77,
592
+ "gateway_degraded": 3
593
+ },
594
+ {
595
+ "date": "2026-09-24",
596
+ "weekday": 3,
597
+ "n": 2859,
598
+ "rtt_median": 11.2,
599
+ "rtt_p95": 16.556,
600
+ "rtt_min_median": 10.0,
601
+ "tcp_min_median": 12.118,
602
+ "loss_share_pct": 30.57,
603
+ "mean_loss_pct": 4.113,
604
+ "jitter_median": 1.222,
605
+ "http_p95": 1285.424,
606
+ "anomaly_pct": 37.01,
607
+ "gateway_degraded": 5
608
+ },
609
+ {
610
+ "date": "2026-09-25",
611
+ "weekday": 4,
612
+ "n": 2848,
613
+ "rtt_median": 11.2,
614
+ "rtt_p95": 21.273,
615
+ "rtt_min_median": 10.0,
616
+ "tcp_min_median": 12.338,
617
+ "loss_share_pct": 16.33,
618
+ "mean_loss_pct": 1.857,
619
+ "jitter_median": 1.111,
620
+ "http_p95": 192.037,
621
+ "anomaly_pct": 25.28,
622
+ "gateway_degraded": 3
623
+ },
624
+ {
625
+ "date": "2026-09-26",
626
+ "weekday": 5,
627
+ "n": 2849,
628
+ "rtt_median": 11.3,
629
+ "rtt_p95": 24.889,
630
+ "rtt_min_median": 10.0,
631
+ "tcp_min_median": 12.303,
632
+ "loss_share_pct": 13.83,
633
+ "mean_loss_pct": 1.692,
634
+ "jitter_median": 1.222,
635
+ "http_p95": 195.367,
636
+ "anomaly_pct": 30.92,
637
+ "gateway_degraded": 507
638
+ },
639
+ {
640
+ "date": "2026-09-27",
641
+ "weekday": 6,
642
+ "n": 2858,
643
+ "rtt_median": 15.261,
644
+ "rtt_p95": 27.815,
645
+ "rtt_min_median": 10.0,
646
+ "tcp_min_median": 12.745,
647
+ "loss_share_pct": 16.34,
648
+ "mean_loss_pct": 1.802,
649
+ "jitter_median": 5.333,
650
+ "http_p95": 272.551,
651
+ "anomaly_pct": 60.81,
652
+ "gateway_degraded": 0
653
+ },
654
+ {
655
+ "date": "2026-09-28",
656
+ "weekday": 0,
657
+ "n": 2854,
658
+ "rtt_median": 13.0,
659
+ "rtt_p95": 18.9,
660
+ "rtt_min_median": 10.0,
661
+ "tcp_min_median": 12.326,
662
+ "loss_share_pct": 32.69,
663
+ "mean_loss_pct": 4.201,
664
+ "jitter_median": 4.333,
665
+ "http_p95": 1284.014,
666
+ "anomaly_pct": 52.21,
667
+ "gateway_degraded": 0
668
+ },
669
+ {
670
+ "date": "2026-09-29",
671
+ "weekday": 1,
672
+ "n": 2856,
673
+ "rtt_median": 12.889,
674
+ "rtt_p95": 25.4,
675
+ "rtt_min_median": 10.0,
676
+ "tcp_min_median": 12.369,
677
+ "loss_share_pct": 29.69,
678
+ "mean_loss_pct": 3.771,
679
+ "jitter_median": 3.667,
680
+ "http_p95": 1294.432,
681
+ "anomaly_pct": 52.28,
682
+ "gateway_degraded": 0
683
+ },
684
+ {
685
+ "date": "2026-09-30",
686
+ "weekday": 2,
687
+ "n": 2858,
688
+ "rtt_median": 11.4,
689
+ "rtt_p95": 26.3,
690
+ "rtt_min_median": 10.0,
691
+ "tcp_min_median": 12.446,
692
+ "loss_share_pct": 9.34,
693
+ "mean_loss_pct": 1.018,
694
+ "jitter_median": 1.667,
695
+ "http_p95": 201.76,
696
+ "anomaly_pct": 38.17,
697
+ "gateway_degraded": 0
698
+ },
699
+ {
700
+ "date": "2026-10-01",
701
+ "weekday": 3,
702
+ "n": 2856,
703
+ "rtt_median": 10.9,
704
+ "rtt_p95": 13.3,
705
+ "rtt_min_median": 10.0,
706
+ "tcp_min_median": 12.157,
707
+ "loss_share_pct": 5.78,
708
+ "mean_loss_pct": 0.637,
709
+ "jitter_median": 0.889,
710
+ "http_p95": 124.368,
711
+ "anomaly_pct": 7.84,
712
+ "gateway_degraded": 0
713
+ },
714
+ {
715
+ "date": "2026-10-02",
716
+ "weekday": 4,
717
+ "n": 2854,
718
+ "rtt_median": 10.9,
719
+ "rtt_p95": 13.0,
720
+ "rtt_min_median": 10.0,
721
+ "tcp_min_median": 12.221,
722
+ "loss_share_pct": 6.76,
723
+ "mean_loss_pct": 0.708,
724
+ "jitter_median": 0.889,
725
+ "http_p95": 108.096,
726
+ "anomaly_pct": 8.13,
727
+ "gateway_degraded": 0
728
+ },
729
+ {
730
+ "date": "2026-10-03",
731
+ "weekday": 5,
732
+ "n": 2859,
733
+ "rtt_median": 10.6,
734
+ "rtt_p95": 12.6,
735
+ "rtt_min_median": 10.0,
736
+ "tcp_min_median": 12.054,
737
+ "loss_share_pct": 6.61,
738
+ "mean_loss_pct": 0.693,
739
+ "jitter_median": 0.667,
740
+ "http_p95": 111.648,
741
+ "anomaly_pct": 7.52,
742
+ "gateway_degraded": 7
743
+ },
744
+ {
745
+ "date": "2026-10-04",
746
+ "weekday": 6,
747
+ "n": 2855,
748
+ "rtt_median": 11.0,
749
+ "rtt_p95": 13.0,
750
+ "rtt_min_median": 10.0,
751
+ "tcp_min_median": 12.237,
752
+ "loss_share_pct": 5.53,
753
+ "mean_loss_pct": 0.581,
754
+ "jitter_median": 0.778,
755
+ "http_p95": 114.124,
756
+ "anomaly_pct": 6.06,
757
+ "gateway_degraded": 1
758
+ },
759
+ {
760
+ "date": "2026-10-05",
761
+ "weekday": 0,
762
+ "n": 2859,
763
+ "rtt_median": 10.9,
764
+ "rtt_p95": 12.8,
765
+ "rtt_min_median": 10.0,
766
+ "tcp_min_median": 12.197,
767
+ "loss_share_pct": 5.46,
768
+ "mean_loss_pct": 0.581,
769
+ "jitter_median": 0.778,
770
+ "http_p95": 217.098,
771
+ "anomaly_pct": 6.47,
772
+ "gateway_degraded": 3
773
+ },
774
+ {
775
+ "date": "2026-10-06",
776
+ "weekday": 1,
777
+ "n": 2853,
778
+ "rtt_median": 10.9,
779
+ "rtt_p95": 12.6,
780
+ "rtt_min_median": 10.0,
781
+ "tcp_min_median": 12.226,
782
+ "loss_share_pct": 2.98,
783
+ "mean_loss_pct": 0.452,
784
+ "jitter_median": 0.778,
785
+ "http_p95": 206.245,
786
+ "anomaly_pct": 4.14,
787
+ "gateway_degraded": 7
788
+ },
789
+ {
790
+ "date": "2026-10-07",
791
+ "weekday": 2,
792
+ "n": 2854,
793
+ "rtt_median": 10.4,
794
+ "rtt_p95": 11.6,
795
+ "rtt_min_median": 10.0,
796
+ "tcp_min_median": 19.295,
797
+ "loss_share_pct": 1.61,
798
+ "mean_loss_pct": 0.172,
799
+ "jitter_median": 0.667,
800
+ "http_p95": 185.259,
801
+ "anomaly_pct": 1.89,
802
+ "gateway_degraded": 0
803
+ },
804
+ {
805
+ "date": "2026-10-08",
806
+ "weekday": 3,
807
+ "n": 2862,
808
+ "rtt_median": 10.5,
809
+ "rtt_p95": 12.8,
810
+ "rtt_min_median": 10.0,
811
+ "tcp_min_median": 17.971,
812
+ "loss_share_pct": 3.95,
813
+ "mean_loss_pct": 0.412,
814
+ "jitter_median": 0.778,
815
+ "http_p95": 196.441,
816
+ "anomaly_pct": 4.65,
817
+ "gateway_degraded": 0
818
+ },
819
+ {
820
+ "date": "2026-10-09",
821
+ "weekday": 4,
822
+ "n": 1887,
823
+ "rtt_median": 10.5,
824
+ "rtt_p95": 12.444,
825
+ "rtt_min_median": 10.0,
826
+ "tcp_min_median": 18.398,
827
+ "loss_share_pct": 4.24,
828
+ "mean_loss_pct": 0.44,
829
+ "jitter_median": 0.667,
830
+ "http_p95": 113.939,
831
+ "anomaly_pct": 5.35,
832
+ "gateway_degraded": 3
833
+ }
834
+ ],
835
+ "regimes": {
836
+ "method": "single least-squares change point in the daily share of samples with ICMP loss",
837
+ "split_date": "2026-09-30",
838
+ "daily_loss_share_before_pct": 22.47,
839
+ "daily_loss_share_after_pct": 5.23,
840
+ "before": {
841
+ "first_date": "2026-09-20",
842
+ "last_date": "2026-09-29",
843
+ "n": 27020,
844
+ "days": 10,
845
+ "rtt_median": 11.9,
846
+ "rtt_p95": 24.3,
847
+ "rtt_p99": 28.4,
848
+ "jitter_median": 2.222,
849
+ "jitter_p95": 9.222,
850
+ "loss_share_pct": 23.16,
851
+ "mean_loss_pct": 2.978,
852
+ "tcp_median": 14.101,
853
+ "dns_cached_median": 37.234,
854
+ "dns_recursive_median": 62.511,
855
+ "http_median": 87.667,
856
+ "http_p95": 1093.754,
857
+ "http_over_1s_pct": 5.87,
858
+ "labels_pct": {
859
+ "label_outage": 0.05,
860
+ "label_packet_loss": 23.11,
861
+ "label_high_latency": 7.96,
862
+ "label_high_jitter": 17.25,
863
+ "label_gateway_degraded": 1.99,
864
+ "label_anomaly": 38.9
865
+ }
866
+ },
867
+ "after": {
868
+ "first_date": "2026-09-30",
869
+ "last_date": "2026-10-09",
870
+ "n": 27597,
871
+ "days": 10,
872
+ "rtt_median": 10.8,
873
+ "rtt_p95": 14.2,
874
+ "rtt_p99": 25.5,
875
+ "jitter_median": 0.778,
876
+ "jitter_p95": 4.556,
877
+ "loss_share_pct": 5.26,
878
+ "mean_loss_pct": 0.574,
879
+ "tcp_median": 15.307,
880
+ "dns_cached_median": 35.018,
881
+ "dns_recursive_median": 56.243,
882
+ "http_median": 77.572,
883
+ "http_p95": 157.017,
884
+ "http_over_1s_pct": 1.09,
885
+ "labels_pct": {
886
+ "label_outage": 0.01,
887
+ "label_packet_loss": 5.25,
888
+ "label_high_latency": 3.32,
889
+ "label_high_jitter": 1.5,
890
+ "label_gateway_degraded": 0.08,
891
+ "label_anomaly": 9.15
892
+ }
893
+ }
894
+ },
895
+ "outages": [
896
+ {
897
+ "start_local": "2026-09-21T13:03:22-04:00",
898
+ "end_local": "2026-09-21T13:04:54-04:00",
899
+ "weekday": 0,
900
+ "samples": 4,
901
+ "minutes": 2.0,
902
+ "gateway_unreachable": true,
903
+ "gateway_loss_sample_before": 20.0
904
+ },
905
+ {
906
+ "start_local": "2026-09-24T07:10:56-04:00",
907
+ "end_local": "2026-09-24T07:12:56-04:00",
908
+ "weekday": 3,
909
+ "samples": 5,
910
+ "minutes": 2.5,
911
+ "gateway_unreachable": true,
912
+ "gateway_loss_sample_before": 0.0
913
+ },
914
+ {
915
+ "start_local": "2026-09-26T13:11:29-04:00",
916
+ "end_local": "2026-09-26T13:13:29-04:00",
917
+ "weekday": 5,
918
+ "samples": 5,
919
+ "minutes": 2.5,
920
+ "gateway_unreachable": true,
921
+ "gateway_loss_sample_before": 0.0
922
+ },
923
+ {
924
+ "start_local": "2026-10-06T02:51:09-04:00",
925
+ "end_local": "2026-10-06T02:52:40-04:00",
926
+ "weekday": 1,
927
+ "samples": 4,
928
+ "minutes": 2.0,
929
+ "gateway_unreachable": true,
930
+ "gateway_loss_sample_before": 0.0
931
+ }
932
+ ],
933
+ "latency_episodes": [
934
+ {
935
+ "run_id": "desktop-eth_20260920_123407",
936
+ "start_local": "2026-09-21T22:34:24-04:00",
937
+ "end_local": "2026-09-22T01:05:24-04:00",
938
+ "weekday": 0,
939
+ "hours": 2.52,
940
+ "samples": 300,
941
+ "labelled_samples": 296,
942
+ "rtt_min_median": 20.0,
943
+ "rtt_avg_median": 26.422,
944
+ "tcp_min_median": 25.68,
945
+ "gateway_median": 0.0,
946
+ "jitter_median": 5.723,
947
+ "dns_cached_median": 36.483,
948
+ "http_median": 124.519,
949
+ "loss_share_pct": 14.0,
950
+ "run_rtt_min_median": 10.0,
951
+ "run_tcp_min_median": 12.3,
952
+ "kind": "path change"
953
+ },
954
+ {
955
+ "run_id": "desktop-eth_20260920_123407",
956
+ "start_local": "2026-09-22T01:27:24-04:00",
957
+ "end_local": "2026-09-22T02:41:24-04:00",
958
+ "weekday": 1,
959
+ "hours": 1.23,
960
+ "samples": 147,
961
+ "labelled_samples": 62,
962
+ "rtt_min_median": 10.0,
963
+ "rtt_avg_median": 20.4,
964
+ "tcp_min_median": 20.07,
965
+ "gateway_median": 0.0,
966
+ "jitter_median": 5.111,
967
+ "dns_cached_median": 36.795,
968
+ "http_median": 100.914,
969
+ "loss_share_pct": 6.12,
970
+ "run_rtt_min_median": 10.0,
971
+ "run_tcp_min_median": 12.3,
972
+ "kind": "path change"
973
+ },
974
+ {
975
+ "run_id": "desktop-eth_20260920_123407",
976
+ "start_local": "2026-09-22T02:47:24-04:00",
977
+ "end_local": "2026-09-22T03:44:24-04:00",
978
+ "weekday": 1,
979
+ "hours": 0.95,
980
+ "samples": 114,
981
+ "labelled_samples": 57,
982
+ "rtt_min_median": 11.0,
983
+ "rtt_avg_median": 21.15,
984
+ "tcp_min_median": 19.5,
985
+ "gateway_median": 0.0,
986
+ "jitter_median": 5.333,
987
+ "dns_cached_median": 36.397,
988
+ "http_median": 104.078,
989
+ "loss_share_pct": 3.51,
990
+ "run_rtt_min_median": 10.0,
991
+ "run_tcp_min_median": 12.3,
992
+ "kind": "path change"
993
+ },
994
+ {
995
+ "run_id": "desktop-eth_20260920_123407",
996
+ "start_local": "2026-09-24T23:51:27-04:00",
997
+ "end_local": "2026-09-25T01:16:27-04:00",
998
+ "weekday": 3,
999
+ "hours": 1.42,
1000
+ "samples": 170,
1001
+ "labelled_samples": 111,
1002
+ "rtt_min_median": 11.0,
1003
+ "rtt_avg_median": 22.3,
1004
+ "tcp_min_median": 20.05,
1005
+ "gateway_median": 0.0,
1006
+ "jitter_median": 6.444,
1007
+ "dns_cached_median": 37.297,
1008
+ "http_median": 106.861,
1009
+ "loss_share_pct": 7.06,
1010
+ "run_rtt_min_median": 10.0,
1011
+ "run_tcp_min_median": 12.3,
1012
+ "kind": "path change"
1013
+ },
1014
+ {
1015
+ "run_id": "desktop-eth_20260920_123407",
1016
+ "start_local": "2026-09-26T14:07:29-04:00",
1017
+ "end_local": "2026-09-26T14:54:29-04:00",
1018
+ "weekday": 5,
1019
+ "hours": 0.78,
1020
+ "samples": 94,
1021
+ "labelled_samples": 75,
1022
+ "rtt_min_median": 14.0,
1023
+ "rtt_avg_median": 23.5,
1024
+ "tcp_min_median": 18.09,
1025
+ "gateway_median": 11.4,
1026
+ "jitter_median": 8.291,
1027
+ "dns_cached_median": 48.922,
1028
+ "http_median": 113.554,
1029
+ "loss_share_pct": 14.89,
1030
+ "run_rtt_min_median": 10.0,
1031
+ "run_tcp_min_median": 12.3,
1032
+ "kind": "first hop"
1033
+ },
1034
+ {
1035
+ "run_id": "desktop-eth_20260920_123407",
1036
+ "start_local": "2026-09-26T15:01:59-04:00",
1037
+ "end_local": "2026-09-26T15:32:59-04:00",
1038
+ "weekday": 5,
1039
+ "hours": 0.52,
1040
+ "samples": 63,
1041
+ "labelled_samples": 44,
1042
+ "rtt_min_median": 14.0,
1043
+ "rtt_avg_median": 22.0,
1044
+ "tcp_min_median": 18.13,
1045
+ "gateway_median": 11.2,
1046
+ "jitter_median": 7.444,
1047
+ "dns_cached_median": 38.085,
1048
+ "http_median": 108.327,
1049
+ "loss_share_pct": 14.29,
1050
+ "run_rtt_min_median": 10.0,
1051
+ "run_tcp_min_median": 12.3,
1052
+ "kind": "first hop"
1053
+ },
1054
+ {
1055
+ "run_id": "desktop-eth_20260920_123407",
1056
+ "start_local": "2026-09-26T16:36:59-04:00",
1057
+ "end_local": "2026-09-26T18:17:29-04:00",
1058
+ "weekday": 5,
1059
+ "hours": 1.68,
1060
+ "samples": 199,
1061
+ "labelled_samples": 140,
1062
+ "rtt_min_median": 14.0,
1063
+ "rtt_avg_median": 23.7,
1064
+ "tcp_min_median": 20.66,
1065
+ "gateway_median": 10.6,
1066
+ "jitter_median": 8.0,
1067
+ "dns_cached_median": 46.31,
1068
+ "http_median": 125.929,
1069
+ "loss_share_pct": 21.61,
1070
+ "run_rtt_min_median": 10.0,
1071
+ "run_tcp_min_median": 12.3,
1072
+ "kind": "first hop"
1073
+ },
1074
+ {
1075
+ "run_id": "desktop-eth_20260920_123407",
1076
+ "start_local": "2026-09-27T00:00:29-04:00",
1077
+ "end_local": "2026-09-27T06:16:59-04:00",
1078
+ "weekday": 6,
1079
+ "hours": 6.28,
1080
+ "samples": 751,
1081
+ "labelled_samples": 728,
1082
+ "rtt_min_median": 17.0,
1083
+ "rtt_avg_median": 25.6,
1084
+ "tcp_min_median": 23.81,
1085
+ "gateway_median": 0.0,
1086
+ "jitter_median": 6.0,
1087
+ "dns_cached_median": 40.061,
1088
+ "http_median": 116.654,
1089
+ "loss_share_pct": 18.64,
1090
+ "run_rtt_min_median": 10.0,
1091
+ "run_tcp_min_median": 12.3,
1092
+ "kind": "path change"
1093
+ },
1094
+ {
1095
+ "run_id": "desktop-eth_20260920_123407",
1096
+ "start_local": "2026-09-29T21:21:32-04:00",
1097
+ "end_local": "2026-09-30T07:34:34-04:00",
1098
+ "weekday": 1,
1099
+ "hours": 10.22,
1100
+ "samples": 1220,
1101
+ "labelled_samples": 1197,
1102
+ "rtt_min_median": 20.0,
1103
+ "rtt_avg_median": 24.8,
1104
+ "tcp_min_median": 24.52,
1105
+ "gateway_median": 0.0,
1106
+ "jitter_median": 3.5,
1107
+ "dns_cached_median": 39.95,
1108
+ "http_median": 117.706,
1109
+ "loss_share_pct": 12.79,
1110
+ "run_rtt_min_median": 10.0,
1111
+ "run_tcp_min_median": 12.3,
1112
+ "kind": "path change"
1113
+ }
1114
+ ],
1115
+ "loss": {
1116
+ "samples_with_loss_pct": 14.12,
1117
+ "mean_loss_pct": 1.763,
1118
+ "packets_received_counts": {
1119
+ "4": 4,
1120
+ "5": 16,
1121
+ "6": 41,
1122
+ "7": 230,
1123
+ "8": 1092,
1124
+ "9": 6309,
1125
+ "10": 46907
1126
+ },
1127
+ "gateway_loss_samples_pct": 0.03,
1128
+ "gateway_loss_outside_outages_samples": 1,
1129
+ "persistence": {
1130
+ "p_loss": 0.1412,
1131
+ "p_loss_given_previous_loss": 0.2977,
1132
+ "ratio": 2.11
1133
+ },
1134
+ "conditional": {
1135
+ "no_loss": {
1136
+ "n": 46907,
1137
+ "rtt_median": 11.0,
1138
+ "jitter_median": 1.0,
1139
+ "tcp_median": 14.521,
1140
+ "tcp_p95": 31.995,
1141
+ "tcp_missing_pct": 0.0,
1142
+ "http_median": 81.362,
1143
+ "http_p95": 234.902,
1144
+ "http_over_1s_pct": 2.54,
1145
+ "dns_recursive_over_200ms_pct": 1.75,
1146
+ "gateway_loss_pct": 0.0
1147
+ },
1148
+ "one_lost": {
1149
+ "n": 6309,
1150
+ "rtt_median": 11.778,
1151
+ "jitter_median": 2.125,
1152
+ "tcp_median": 14.265,
1153
+ "tcp_p95": 32.66,
1154
+ "tcp_missing_pct": 0.0,
1155
+ "http_median": 85.113,
1156
+ "http_p95": 1278.521,
1157
+ "http_over_1s_pct": 7.47,
1158
+ "dns_recursive_over_200ms_pct": 5.22,
1159
+ "gateway_loss_pct": 0.0
1160
+ },
1161
+ "two_plus_lost": {
1162
+ "n": 1383,
1163
+ "rtt_median": 12.625,
1164
+ "jitter_median": 3.286,
1165
+ "tcp_median": 14.392,
1166
+ "tcp_p95": 34.071,
1167
+ "tcp_missing_pct": 0.07,
1168
+ "http_median": 89.658,
1169
+ "http_p95": 1485.044,
1170
+ "http_over_1s_pct": 16.34,
1171
+ "dns_recursive_over_200ms_pct": 9.6,
1172
+ "gateway_loss_pct": 0.07
1173
+ }
1174
+ }
1175
+ },
1176
+ "tcp_icmp": {
1177
+ "tcp_min_minus_icmp_min_median_ms": 2.27,
1178
+ "tcp_median_minus_icmp_avg_median_ms": 2.925,
1179
+ "split_local": "2026-10-06T22:00",
1180
+ "long_path_share_before_pct": 7.22,
1181
+ "long_path_share_after_pct": 63.73,
1182
+ "after_split": {
1183
+ "tcp_min_p25": 12.925,
1184
+ "tcp_min_median": 18.556,
1185
+ "tcp_min_p75": 22.233,
1186
+ "icmp_min_median": 10.0,
1187
+ "icmp_avg_median": 10.5,
1188
+ "share_tcp_min_over_17ms_pct": 55.64
1189
+ },
1190
+ "before_split": {
1191
+ "tcp_min_median": 12.218,
1192
+ "icmp_min_median": 10.0
1193
+ }
1194
+ },
1195
+ "dns_http": {
1196
+ "dns_cached": {
1197
+ "median": 36.026,
1198
+ "p05": 17.031,
1199
+ "p95": 74.878,
1200
+ "share_under_15ms_pct": 3.38,
1201
+ "share_under_5ms_pct": 0.01
1202
+ },
1203
+ "dns_recursive": {
1204
+ "median": 59.242,
1205
+ "p95": 106.31,
1206
+ "p99": 1266.18,
1207
+ "share_over_200ms_pct": 2.35
1208
+ },
1209
+ "dns_recursive_minus_cached_median_ms": 20.16,
1210
+ "dns_timeouts": 24,
1211
+ "dns_timeouts_during_outages": 14,
1212
+ "http": {
1213
+ "median": 81.911,
1214
+ "p90": 155.012,
1215
+ "p95": 271.36,
1216
+ "p99": 1375.212,
1217
+ "share_1000_1400ms_pct": 2.48,
1218
+ "share_3900_4400ms_pct": 0.55,
1219
+ "share_over_1s_pct": 3.45,
1220
+ "share_over_5s_pct": 0.08,
1221
+ "timeouts": 32,
1222
+ "status_counts": {
1223
+ "200": 54565
1224
+ }
1225
+ }
1226
+ },
1227
+ "autocorrelation": {
1228
+ "lag_minutes": [
1229
+ 0.5,
1230
+ 1,
1231
+ 2.5,
1232
+ 5,
1233
+ 10,
1234
+ 30,
1235
+ 60,
1236
+ 180,
1237
+ 360,
1238
+ 720,
1239
+ 1440
1240
+ ],
1241
+ "lag_samples": [
1242
+ 1,
1243
+ 2,
1244
+ 5,
1245
+ 10,
1246
+ 20,
1247
+ 60,
1248
+ 120,
1249
+ 360,
1250
+ 720,
1251
+ 1440,
1252
+ 2880
1253
+ ],
1254
+ "values": {
1255
+ "rtt_avg_ms": [
1256
+ 0.737,
1257
+ 0.658,
1258
+ 0.582,
1259
+ 0.52,
1260
+ 0.49,
1261
+ 0.473,
1262
+ 0.386,
1263
+ 0.259,
1264
+ 0.118,
1265
+ 0.097,
1266
+ 0.025
1267
+ ],
1268
+ "log_rtt_avg_ms": [
1269
+ 0.808,
1270
+ 0.806,
1271
+ 0.768,
1272
+ 0.762,
1273
+ 0.731,
1274
+ 0.68,
1275
+ 0.597,
1276
+ 0.422,
1277
+ 0.223,
1278
+ 0.182,
1279
+ 0.092
1280
+ ],
1281
+ "jitter_ms": [
1282
+ 0.438,
1283
+ 0.457,
1284
+ 0.397,
1285
+ 0.415,
1286
+ 0.391,
1287
+ 0.356,
1288
+ 0.291,
1289
+ 0.252,
1290
+ 0.205,
1291
+ 0.232,
1292
+ 0.174
1293
+ ],
1294
+ "loss_indicator": [
1295
+ 0.182,
1296
+ 0.175,
1297
+ 0.181,
1298
+ 0.169,
1299
+ 0.167,
1300
+ 0.156,
1301
+ 0.145,
1302
+ 0.135,
1303
+ 0.089,
1304
+ 0.04,
1305
+ 0.097
1306
+ ],
1307
+ "tcp_connect_min_ms": [
1308
+ 0.281,
1309
+ 0.217,
1310
+ 0.203,
1311
+ 0.151,
1312
+ 0.149,
1313
+ 0.143,
1314
+ 0.123,
1315
+ 0.092,
1316
+ 0.055,
1317
+ 0.038,
1318
+ 0.016
1319
+ ],
1320
+ "dns_recursive_ms": [
1321
+ 0.035,
1322
+ 0.035,
1323
+ 0.026,
1324
+ 0.02,
1325
+ 0.025,
1326
+ 0.023,
1327
+ 0.023,
1328
+ 0.016,
1329
+ 0.004,
1330
+ 0.0,
1331
+ 0.008
1332
+ ],
1333
+ "http_ms": [
1334
+ 0.061,
1335
+ 0.059,
1336
+ 0.047,
1337
+ 0.045,
1338
+ 0.046,
1339
+ 0.034,
1340
+ 0.039,
1341
+ 0.042,
1342
+ 0.028,
1343
+ 0.017,
1344
+ 0.013
1345
+ ]
1346
+ }
1347
+ },
1348
+ "speedtest": {
1349
+ "tests": 460,
1350
+ "servers": 162,
1351
+ "failed_latency_probe": 79,
1352
+ "zero_download": 7,
1353
+ "zero_upload": 4,
1354
+ "download": {
1355
+ "n": 460,
1356
+ "median": 34.725,
1357
+ "mean": 68.463,
1358
+ "p95": 318.275,
1359
+ "p99": 417.581,
1360
+ "max": 480.72
1361
+ },
1362
+ "upload": {
1363
+ "n": 460,
1364
+ "median": 28.625,
1365
+ "mean": 26.121,
1366
+ "p95": 41.142,
1367
+ "p99": 44.101,
1368
+ "max": 54.17
1369
+ },
1370
+ "download_quantiles": {
1371
+ "0.1": 9.082,
1372
+ "0.25": 15.84,
1373
+ "0.5": 34.725,
1374
+ "0.75": 65.045,
1375
+ "0.9": 183.019
1376
+ },
1377
+ "upload_quantiles": {
1378
+ "0.1": 9.366,
1379
+ "0.25": 15.015,
1380
+ "0.5": 28.625,
1381
+ "0.75": 37.992,
1382
+ "0.9": 40.281
1383
+ },
1384
+ "ping_valid": {
1385
+ "n": 381,
1386
+ "median": 52.058,
1387
+ "mean": 93.665,
1388
+ "p95": 196.381,
1389
+ "p99": 396.917,
1390
+ "max": 1167.189
1391
+ },
1392
+ "download_median_night_0_4": 61.52,
1393
+ "download_median_day_9_16": 22.005,
1394
+ "sample_duration_median_s": 34.91,
1395
+ "top_servers": [
1396
+ {
1397
+ "server": "Spectrum, New York, NY",
1398
+ "n": 16,
1399
+ "download_median": 133.0,
1400
+ "download_max": 319.5,
1401
+ "upload_median": 38.4,
1402
+ "ping_median": 20.9
1403
+ },
1404
+ {
1405
+ "server": "Surfshark Ltd, New York, NY",
1406
+ "n": 15,
1407
+ "download_median": 56.7,
1408
+ "download_max": 480.7,
1409
+ "upload_median": 39.1,
1410
+ "ping_median": 28.0
1411
+ },
1412
+ {
1413
+ "server": "WebNX Inc, New York, NY",
1414
+ "n": 15,
1415
+ "download_median": 44.5,
1416
+ "download_max": 252.4,
1417
+ "upload_median": 39.7,
1418
+ "ping_median": 29.2
1419
+ },
1420
+ {
1421
+ "server": "Summit Broadband, Orlando, FL",
1422
+ "n": 13,
1423
+ "download_median": 34.3,
1424
+ "download_max": 61.9,
1425
+ "upload_median": 37.7,
1426
+ "ping_median": 43.6
1427
+ },
1428
+ {
1429
+ "server": "GOZFLY LLC, Herndon, VA",
1430
+ "n": 9,
1431
+ "download_median": 22.6,
1432
+ "download_max": 80.6,
1433
+ "upload_median": 33.8,
1434
+ "ping_median": 20.6
1435
+ },
1436
+ {
1437
+ "server": "EZEE Fiber, Chicago, IL",
1438
+ "n": 9,
1439
+ "download_median": 41.6,
1440
+ "download_max": 62.6,
1441
+ "upload_median": 35.8,
1442
+ "ping_median": 44.0
1443
+ },
1444
+ {
1445
+ "server": "Spectrum, Oxford, MA",
1446
+ "n": 9,
1447
+ "download_median": 371.8,
1448
+ "download_max": 456.5,
1449
+ "upload_median": 40.7,
1450
+ "ping_median": 28.6
1451
+ },
1452
+ {
1453
+ "server": "University of Florida, Gainesville, FL",
1454
+ "n": 8,
1455
+ "download_median": 20.9,
1456
+ "download_max": 53.9,
1457
+ "upload_median": 35.3,
1458
+ "ping_median": 39.6
1459
+ },
1460
+ {
1461
+ "server": "Summit Broadband, Bonita Springs, FL",
1462
+ "n": 7,
1463
+ "download_median": 85.8,
1464
+ "download_max": 105.3,
1465
+ "upload_median": 37.0,
1466
+ "ping_median": 49.6
1467
+ },
1468
+ {
1469
+ "server": "Redel Internet, Balne\u00e1rio Cambori\u00fa",
1470
+ "n": 6,
1471
+ "download_median": 36.2,
1472
+ "download_max": 37.4,
1473
+ "upload_median": 19.8,
1474
+ "ping_median": 142.8
1475
+ }
1476
+ ]
1477
+ },
1478
+ "labels": {
1479
+ "counts": {
1480
+ "label_outage": 18,
1481
+ "label_packet_loss": 7692,
1482
+ "label_high_latency": 3067,
1483
+ "label_high_jitter": 5074,
1484
+ "label_gateway_degraded": 560,
1485
+ "label_anomaly": 13036
1486
+ },
1487
+ "share_pct": {
1488
+ "label_outage": 0.03,
1489
+ "label_packet_loss": 14.08,
1490
+ "label_high_latency": 5.62,
1491
+ "label_high_jitter": 9.29,
1492
+ "label_gateway_degraded": 1.03,
1493
+ "label_anomaly": 23.87
1494
+ },
1495
+ "exactly_one_label": 10205,
1496
+ "two_or_more_labels": 2831,
1497
+ "high_latency_in_episodes_pct": 88.4,
1498
+ "episode_kinds": {
1499
+ "path change": 6,
1500
+ "first hop": 3,
1501
+ "queueing": 0
1502
+ }
1503
+ }
1504
+ }
dataset/localnet_dynamics.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fe30f9a91afeb018196711470e29b61ee367a8cb638b3fdf05bc4eec0afd400
3
+ size 18452443
dataset/localnet_dynamics.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9dee301cd18939c36b91765ad8d0198e1c98caea620c3fae15b8377df8b4ee1
3
+ size 3500919
dataset/raw/localnet_desktop-eth_20260920_123407.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d37484c1c71b75ab52df3574d028e16234fc4978900d0ebd54a70c76808d0cc0
3
+ size 15198518
dataset/raw/localnet_desktop-eth_20260920_123407.json ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "run_id": "desktop-eth_20260920_123407",
3
+ "host_label": "desktop-eth",
4
+ "collector_version": "2.0.0",
5
+ "status": "running",
6
+ "started_utc": "2026-09-20T16:34:18Z",
7
+ "updated_utc": "2026-10-09T19:45:22Z",
8
+ "planned_duration_s": 2592000.0,
9
+ "elapsed_s": 1653039.2,
10
+ "interval_s": 30.0,
11
+ "sample_count": 54608,
12
+ "first_sample_utc": "2026-09-20T16:34:22Z",
13
+ "last_sample_utc": "2026-10-09T19:45:13Z",
14
+ "csv_file": "localnet_desktop-eth_20260920_123407.csv",
15
+ "config": {
16
+ "target": "8.8.8.8",
17
+ "ping_count": 10,
18
+ "gateway_ping_count": 5,
19
+ "ping_timeout_s": 2.0,
20
+ "tcp_port": 443,
21
+ "tcp_count": 5,
22
+ "dns_host": "example.com",
23
+ "dns_server": "192.168.1.1",
24
+ "dns_timeout_s": 3.0,
25
+ "http_url": "http://www.msftconnecttest.com/connecttest.txt",
26
+ "http_timeout_s": 5.0,
27
+ "wifi": true,
28
+ "record_ssid": false,
29
+ "speedtest": true,
30
+ "speedtest_every_s": 3600.0,
31
+ "speedtest_server_id": null,
32
+ "iperf_server": null,
33
+ "iperf_port": 5201,
34
+ "iperf_every_s": null,
35
+ "iperf_duration_s": 10,
36
+ "iperf_reverse": false
37
+ },
38
+ "environment": {
39
+ "os": "Windows-11-10.0.26200-SP0",
40
+ "python": "3.12.12",
41
+ "machine": "AMD64",
42
+ "timezone": "Eastern Daylight Time",
43
+ "utc_offset_s": -14400,
44
+ "ping_resolution_ms": 1.0
45
+ },
46
+ "network": {
47
+ "gateway_ip": "192.168.1.1",
48
+ "interface": null,
49
+ "local_ip": "192.168.1.217",
50
+ "link_type": "unknown",
51
+ "link_types_seen": {
52
+ "unknown": 54608
53
+ },
54
+ "detection_source": "route print"
55
+ },
56
+ "summary": {
57
+ "rtt_avg_ms": {
58
+ "count": 54590,
59
+ "mean": 12.581,
60
+ "median": 11.1,
61
+ "min": 9.3,
62
+ "max": 288.6,
63
+ "p95": 22.3,
64
+ "stddev": 5.217
65
+ },
66
+ "rtt_min_ms": {
67
+ "count": 54590,
68
+ "mean": 10.432,
69
+ "median": 10.0,
70
+ "min": 5.0,
71
+ "max": 263.0,
72
+ "p95": 14.0,
73
+ "stddev": 3.125
74
+ },
75
+ "rtt_max_ms": {
76
+ "count": 54590,
77
+ "mean": 17.87,
78
+ "median": 13.0,
79
+ "min": 10.0,
80
+ "max": 373.0,
81
+ "p95": 32.0,
82
+ "stddev": 10.344
83
+ },
84
+ "jitter_ms": {
85
+ "count": 54590,
86
+ "mean": 2.306,
87
+ "median": 1.0,
88
+ "min": 0.0,
89
+ "max": 59.778,
90
+ "p95": 7.667,
91
+ "stddev": 2.692
92
+ },
93
+ "packet_loss_pct": {
94
+ "count": 54608,
95
+ "mean": 1.764,
96
+ "median": 0.0,
97
+ "min": 0.0,
98
+ "max": 100.0,
99
+ "p95": 10.0,
100
+ "stddev": 5.072
101
+ },
102
+ "gateway_rtt_avg_ms": {
103
+ "count": 54590,
104
+ "mean": 0.321,
105
+ "median": 0.2,
106
+ "min": 0.0,
107
+ "max": 89.4,
108
+ "p95": 0.8,
109
+ "stddev": 1.319
110
+ },
111
+ "gateway_packet_loss_pct": {
112
+ "count": 54608,
113
+ "mean": 0.033,
114
+ "median": 0.0,
115
+ "min": 0.0,
116
+ "max": 100.0,
117
+ "p95": 0.0,
118
+ "stddev": 1.817
119
+ },
120
+ "tcp_connect_median_ms": {
121
+ "count": 54589,
122
+ "mean": 19.311,
123
+ "median": 14.483,
124
+ "min": 11.262,
125
+ "max": 1524.463,
126
+ "p95": 32.127,
127
+ "stddev": 18.435
128
+ },
129
+ "dns_resolve_ms": {
130
+ "count": 54586,
131
+ "mean": 43.595,
132
+ "median": 36.025,
133
+ "min": 3.743,
134
+ "max": 3252.214,
135
+ "p95": 74.864,
136
+ "stddev": 70.374
137
+ },
138
+ "dns_recursive_ms": {
139
+ "count": 54581,
140
+ "mean": 87.278,
141
+ "median": 59.238,
142
+ "min": 16.657,
143
+ "max": 25645.041,
144
+ "p95": 106.313,
145
+ "stddev": 230.545
146
+ },
147
+ "http_ms": {
148
+ "count": 54556,
149
+ "mean": 154.754,
150
+ "median": 81.91,
151
+ "min": 23.451,
152
+ "max": 13111.02,
153
+ "p95": 271.398,
154
+ "stddev": 403.142
155
+ },
156
+ "wifi_signal_pct": {
157
+ "count": 4,
158
+ "mean": 85.75,
159
+ "median": 85.0,
160
+ "min": 84.0,
161
+ "max": 89.0,
162
+ "p95": 89.0,
163
+ "stddev": 1.92
164
+ },
165
+ "wifi_rssi_dbm": {
166
+ "count": 4,
167
+ "mean": -57.125,
168
+ "median": -57.5,
169
+ "min": -58.0,
170
+ "max": -55.5,
171
+ "p95": -55.5,
172
+ "stddev": 0.96
173
+ },
174
+ "wifi_rx_mbps": {
175
+ "count": 4,
176
+ "mean": 866.7,
177
+ "median": 866.7,
178
+ "min": 866.7,
179
+ "max": 866.7,
180
+ "p95": 866.7,
181
+ "stddev": 0.0
182
+ },
183
+ "download_mbps": {
184
+ "count": 460,
185
+ "mean": 68.463,
186
+ "median": 34.725,
187
+ "min": 0.0,
188
+ "max": 480.72,
189
+ "p95": 319.51,
190
+ "stddev": 93.847
191
+ },
192
+ "upload_mbps": {
193
+ "count": 460,
194
+ "mean": 26.121,
195
+ "median": 28.625,
196
+ "min": 0.0,
197
+ "max": 54.17,
198
+ "p95": 41.17,
199
+ "stddev": 12.608
200
+ },
201
+ "speedtest_ping_ms": {
202
+ "count": 460,
203
+ "mean": 306603.157,
204
+ "median": 78.725,
205
+ "min": 16.672,
206
+ "max": 1800000.0,
207
+ "p95": 1800000.0,
208
+ "stddev": 674249.533
209
+ },
210
+ "sample_duration_s": {
211
+ "count": 54608,
212
+ "mean": 9.789,
213
+ "median": 9.21,
214
+ "min": 9.06,
215
+ "max": 114.85,
216
+ "p95": 11.23,
217
+ "stddev": 2.964
218
+ }
219
+ }
220
+ }
dataset/summary.json ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_utc": "2026-10-10T05:42:01Z",
3
+ "builder_version": "2.0.1",
4
+ "rows": 54617,
5
+ "columns": 67,
6
+ "runs": [
7
+ {
8
+ "run_id": "desktop-eth_20260920_123407",
9
+ "host_label": "desktop-eth",
10
+ "rows": 54617,
11
+ "first_utc": "2026-09-20T16:34:22Z",
12
+ "last_utc": "2026-10-09T19:49:43Z",
13
+ "span_hours": 459.26,
14
+ "interval_s": 30.0,
15
+ "coverage_pct": 99.1,
16
+ "link_types": {
17
+ "unknown": 54617
18
+ },
19
+ "collector_version": "2.0.0",
20
+ "os": "Windows-11-10.0.26200-SP0",
21
+ "status": "running",
22
+ "thresholds": {
23
+ "rtt_avg_ms": {
24
+ "n": 54599,
25
+ "median": 11.1,
26
+ "mad": 0.678,
27
+ "threshold": 21.1
28
+ },
29
+ "jitter_ms": {
30
+ "n": 54599,
31
+ "median": 1.0,
32
+ "mad": 0.556,
33
+ "threshold": 6.0
34
+ },
35
+ "gateway_rtt_avg_ms": {
36
+ "n": 54599,
37
+ "median": 0.2,
38
+ "mad": 0.2,
39
+ "threshold": 5.2
40
+ }
41
+ }
42
+ }
43
+ ],
44
+ "first_utc": "2026-09-20T16:34:22Z",
45
+ "last_utc": "2026-10-09T19:49:43Z",
46
+ "span_days": 19.14,
47
+ "coverage_pct": 99.1,
48
+ "label_rule": {
49
+ "mad_k": 5.0,
50
+ "description": "threshold = median + max(k * 1.4826 * MAD, absolute floor, relative floor * median), computed per run",
51
+ "floors": {
52
+ "rtt_avg_ms": {
53
+ "absolute_ms": 10.0,
54
+ "relative": 0.5
55
+ },
56
+ "jitter_ms": {
57
+ "absolute_ms": 5.0,
58
+ "relative": 1.0
59
+ },
60
+ "gateway_rtt_avg_ms": {
61
+ "absolute_ms": 5.0,
62
+ "relative": 1.0
63
+ }
64
+ }
65
+ },
66
+ "labels": {
67
+ "label_outage": {
68
+ "rows": 18,
69
+ "share_pct": 0.033
70
+ },
71
+ "label_packet_loss": {
72
+ "rows": 7692,
73
+ "share_pct": 14.084
74
+ },
75
+ "label_high_latency": {
76
+ "rows": 3067,
77
+ "share_pct": 5.615
78
+ },
79
+ "label_high_jitter": {
80
+ "rows": 5074,
81
+ "share_pct": 9.29
82
+ },
83
+ "label_gateway_degraded": {
84
+ "rows": 560,
85
+ "share_pct": 1.025
86
+ },
87
+ "label_anomaly": {
88
+ "rows": 13036,
89
+ "share_pct": 23.868
90
+ }
91
+ },
92
+ "events": 0,
93
+ "metrics": {
94
+ "rtt_avg_ms": {
95
+ "count": 54599,
96
+ "mean": 12.581,
97
+ "median": 11.1,
98
+ "p95": 22.3,
99
+ "min": 9.3,
100
+ "max": 288.6
101
+ },
102
+ "rtt_min_ms": {
103
+ "count": 54599,
104
+ "mean": 10.432,
105
+ "median": 10.0,
106
+ "p95": 14.0,
107
+ "min": 5.0,
108
+ "max": 263.0
109
+ },
110
+ "rtt_max_ms": {
111
+ "count": 54599,
112
+ "mean": 17.869,
113
+ "median": 13.0,
114
+ "p95": 32.0,
115
+ "min": 10.0,
116
+ "max": 373.0
117
+ },
118
+ "jitter_ms": {
119
+ "count": 54599,
120
+ "mean": 2.306,
121
+ "median": 1.0,
122
+ "p95": 7.667,
123
+ "min": 0.0,
124
+ "max": 59.778
125
+ },
126
+ "packet_loss_pct": {
127
+ "count": 54617,
128
+ "mean": 1.763,
129
+ "median": 0.0,
130
+ "p95": 10.0,
131
+ "min": 0.0,
132
+ "max": 100.0
133
+ },
134
+ "gateway_rtt_avg_ms": {
135
+ "count": 54599,
136
+ "mean": 0.321,
137
+ "median": 0.2,
138
+ "p95": 0.8,
139
+ "min": 0.0,
140
+ "max": 89.4
141
+ },
142
+ "gateway_packet_loss_pct": {
143
+ "count": 54617,
144
+ "mean": 0.033,
145
+ "median": 0.0,
146
+ "p95": 0.0,
147
+ "min": 0.0,
148
+ "max": 100.0
149
+ },
150
+ "tcp_connect_median_ms": {
151
+ "count": 54598,
152
+ "mean": 19.311,
153
+ "median": 14.484,
154
+ "p95": 32.127,
155
+ "min": 11.262,
156
+ "max": 1524.463
157
+ },
158
+ "dns_resolve_ms": {
159
+ "count": 54595,
160
+ "mean": 43.594,
161
+ "median": 36.026,
162
+ "p95": 74.878,
163
+ "min": 3.743,
164
+ "max": 3252.214
165
+ },
166
+ "dns_recursive_ms": {
167
+ "count": 54590,
168
+ "mean": 87.275,
169
+ "median": 59.242,
170
+ "p95": 106.31,
171
+ "min": 16.657,
172
+ "max": 25645.041
173
+ },
174
+ "http_ms": {
175
+ "count": 54565,
176
+ "mean": 154.745,
177
+ "median": 81.911,
178
+ "p95": 271.36,
179
+ "min": 23.451,
180
+ "max": 13111.02
181
+ },
182
+ "wifi_signal_pct": {
183
+ "count": 4,
184
+ "mean": 85.75,
185
+ "median": 85.0,
186
+ "p95": 88.4,
187
+ "min": 84.0,
188
+ "max": 89.0
189
+ },
190
+ "wifi_rssi_dbm": {
191
+ "count": 4,
192
+ "mean": -57.125,
193
+ "median": -57.5,
194
+ "p95": -55.8,
195
+ "min": -58.0,
196
+ "max": -55.5
197
+ },
198
+ "wifi_rx_mbps": {
199
+ "count": 4,
200
+ "mean": 866.7,
201
+ "median": 866.7,
202
+ "p95": 866.7,
203
+ "min": 866.7,
204
+ "max": 866.7
205
+ },
206
+ "download_mbps": {
207
+ "count": 460,
208
+ "mean": 68.463,
209
+ "median": 34.725,
210
+ "p95": 318.275,
211
+ "min": 0.0,
212
+ "max": 480.72
213
+ },
214
+ "upload_mbps": {
215
+ "count": 460,
216
+ "mean": 26.121,
217
+ "median": 28.625,
218
+ "p95": 41.142,
219
+ "min": 0.0,
220
+ "max": 54.17
221
+ },
222
+ "speedtest_ping_ms": {
223
+ "count": 381,
224
+ "mean": 93.665,
225
+ "median": 52.058,
226
+ "p95": 196.381,
227
+ "min": 16.672,
228
+ "max": 1167.189
229
+ }
230
+ }
231
+ }
figures/pdf/autocorrelation.pdf ADDED
Binary file (30.3 kB). View file
 
figures/pdf/calendar_heatmaps.pdf ADDED
Binary file (44.6 kB). View file
 
figures/pdf/degradation_anatomy.pdf ADDED
Binary file (98.7 kB). View file
 
figures/pdf/diurnal_profile.pdf ADDED
Binary file (31.9 kB). View file
 
figures/pdf/labels.pdf ADDED
Binary file (25.5 kB). View file
 
figures/pdf/loss_anatomy.pdf ADDED
Binary file (40.3 kB). View file
 
figures/pdf/overview_timeline.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98d60d1ef32d2a2bc99d4161c04cbbcace3443132b6800836102bb054a448904
3
+ size 417997
figures/pdf/regimes.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6432a5b991cb038ddaf02e79914252b6fc0168934079266b7dd066d483c0fb62
3
+ size 162338
figures/pdf/speedtest.pdf ADDED
Binary file (52.5 kB). View file
 
figures/pdf/tcp_vs_icmp.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c1ad55efbb3baa639349a262270464ed3530cba9ed3ca3b68c68d735af85c4e
3
+ size 125522
figures/png/autocorrelation.png ADDED

Git LFS Details

  • SHA256: 6dd47cfce534e5ff3b0b7b01761c6f043360f8ecc47572b19d6554e0d390db86
  • Pointer size: 131 Bytes
  • Size of remote file: 211 kB
figures/png/calendar_heatmaps.png ADDED

Git LFS Details

  • SHA256: 92cc676a687a7dfa27ab6f3c6fb865c95d8d659eeaf837be1eb31f63d1837893
  • Pointer size: 131 Bytes
  • Size of remote file: 189 kB
figures/png/degradation_anatomy.png ADDED

Git LFS Details

  • SHA256: 56014082bd2e7e846c77d1eddde594ecf4b74b221df85f7fc0914d3c5184e2ea
  • Pointer size: 131 Bytes
  • Size of remote file: 587 kB
figures/png/diurnal_profile.png ADDED

Git LFS Details

  • SHA256: bf1db4eb66f675ed4877aae327a1c64d4de95c4490b1384efe827787808f08b7
  • Pointer size: 131 Bytes
  • Size of remote file: 298 kB
figures/png/labels.png ADDED

Git LFS Details

  • SHA256: 014b74bff202a9fb455c9edd224e792e4aef2235b328d7b3ad1d53a4da66266e
  • Pointer size: 131 Bytes
  • Size of remote file: 136 kB
figures/png/loss_anatomy.png ADDED

Git LFS Details

  • SHA256: 38c6fad5ce8dab57f01286842c439ce4f783a8b47d56e94d40c370759493ac34
  • Pointer size: 131 Bytes
  • Size of remote file: 296 kB
figures/png/overview_timeline.png ADDED

Git LFS Details

  • SHA256: 24aeb40928878f418789f2ebae4ca23dfc14a600275298ce6663915e58ab68e7
  • Pointer size: 131 Bytes
  • Size of remote file: 744 kB
figures/png/regimes.png ADDED

Git LFS Details

  • SHA256: 9c281d7612c41d6e49dda37860dd445148c31664086ab2e836f7151ebe9ffbb0
  • Pointer size: 131 Bytes
  • Size of remote file: 286 kB
figures/png/speedtest.png ADDED

Git LFS Details

  • SHA256: f85e6929340bb305788c575b4a48f72d8404b1ed0ebac58b9940a855bb01cc19
  • Pointer size: 131 Bytes
  • Size of remote file: 520 kB
figures/png/tcp_vs_icmp.png ADDED

Git LFS Details

  • SHA256: bedd58c76abb8df39b9f4186667a02ad3de6ee9c16a12cf99a4d9b6859a5ef1f
  • Pointer size: 131 Bytes
  • Size of remote file: 604 kB
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # The collector (scripts/collect_data.py) needs only the Python standard library.
2
+ # These packages are used by the build, analysis, plotting, packaging and test
3
+ # scripts, and by the speed-test fallback when the Ookla CLI is not installed.
4
+ pandas>=1.5
5
+ numpy>=1.21
6
+ pyarrow>=12.0
7
+ matplotlib>=3.6
8
+ pytest>=7.0
9
+ speedtest-cli>=2.1.3
scripts/analyze.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Analyse the consolidated LocalNet-Dynamics dataset.
4
+
5
+ Reads dataset/localnet_dynamics.parquet (or .csv), prints a text report and
6
+ writes dataset/analysis.json with every number the documentation quotes:
7
+ overall statistics, hour-of-day and day-by-day profiles, the two regimes
8
+ separated by a change point in the daily loss share, outage and high-latency
9
+ episodes with their diagnosis (path change, first hop, queueing), the
10
+ conditional effect of ICMP loss on the other probes, the ICMP/TCP path split,
11
+ DNS and HTTP facts, autocorrelation, speed-test quality and label statistics.
12
+
13
+ python analyze.py
14
+ python analyze.py --input dataset/localnet_dynamics.csv --no-report
15
+
16
+ The figures are rendered by plot_figures.py from the same functions.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import sys
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+
32
+ METRICS = ["rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct",
33
+ "gateway_rtt_avg_ms", "tcp_connect_min_ms", "tcp_connect_median_ms",
34
+ "dns_resolve_ms", "dns_recursive_ms", "http_ms", "download_mbps", "upload_mbps"]
35
+ LABELS = ["label_outage", "label_packet_loss", "label_high_latency", "label_high_jitter",
36
+ "label_gateway_degraded", "label_anomaly"]
37
+ ACF_LAGS_MIN = [0.5, 1, 2.5, 5, 10, 30, 60, 180, 360, 720, 1440]
38
+
39
+ # Latency episodes: runs of label_high_latency, merged across gaps of at most
40
+ # MERGE_GAP samples and kept when they span at least MIN_EPISODE_MIN minutes.
41
+ MERGE_GAP = 10
42
+ MIN_EPISODE_MIN = 30
43
+ # An episode whose first-hop RTT exceeds the run's gateway threshold is a
44
+ # first-hop event; one whose ICMP or TCP latency floor rises by at least
45
+ # FLOOR_SHIFT_MS over the run median is a path change; anything else is queueing.
46
+ FLOOR_SHIFT_MS = 5.0
47
+ TCP_SPLIT_MS = 5.0 # TCP floor above ICMP floor by more than this
48
+ SPEEDTEST_PING_FAILED_MS = 600_000 # speedtest-cli counts a failed latency probe as 3600 s
49
+
50
+
51
+ # --------------------------------------------------------------------------- #
52
+ # Loading and helpers
53
+ # --------------------------------------------------------------------------- #
54
+
55
+ def load(path: Path) -> pd.DataFrame:
56
+ df = pd.read_parquet(path) if path.suffix == ".parquet" else pd.read_csv(path, low_memory=False)
57
+ df["ts"] = pd.to_datetime(df["timestamp_utc"], utc=True)
58
+ df["ts_local"] = pd.to_datetime(df["timestamp_local"].astype(str).str[:19],
59
+ format="%Y-%m-%dT%H:%M:%S", errors="coerce")
60
+ for col in LABELS:
61
+ if col in df.columns:
62
+ df[col] = df[col].fillna(0).astype(int)
63
+ for col in METRICS + ["gateway_packet_loss_pct", "packets_received", "speedtest_ping_ms"]:
64
+ if col in df.columns:
65
+ df[col] = pd.to_numeric(df[col], errors="coerce").astype(float)
66
+ return df.sort_values("ts").reset_index(drop=True)
67
+
68
+
69
+ def q(series: pd.Series, p: float) -> float | None:
70
+ v = series.dropna()
71
+ return round(float(v.quantile(p)), 3) if len(v) else None
72
+
73
+
74
+ def describe(series: pd.Series) -> dict | None:
75
+ v = series.dropna().astype(float)
76
+ if v.empty:
77
+ return None
78
+ return {"n": int(v.size), "median": round(float(v.median()), 3), "mean": round(float(v.mean()), 3),
79
+ "p95": round(float(v.quantile(0.95)), 3), "p99": round(float(v.quantile(0.99)), 3),
80
+ "max": round(float(v.max()), 3)}
81
+
82
+
83
+ def share(mask: pd.Series) -> float:
84
+ return round(100.0 * float(mask.mean()), 2) if len(mask) else 0.0
85
+
86
+
87
+ def change_point(series: pd.Series) -> tuple:
88
+ """Split index that minimises the within-segment sum of squares (one break)."""
89
+ x = series.dropna().values.astype(float)
90
+ n = len(x)
91
+ if n < 4:
92
+ k = max(1, n // 2)
93
+ return series.dropna().index[k], float(x[:k].mean()), float(x[k:].mean())
94
+ cs, cs2 = np.cumsum(x), np.cumsum(x * x)
95
+ best = None
96
+ for k in range(2, n - 1):
97
+ a = cs2[k - 1] - cs[k - 1] ** 2 / k
98
+ b = (cs2[-1] - cs2[k - 1]) - (cs[-1] - cs[k - 1]) ** 2 / (n - k)
99
+ if best is None or a + b < best[0]:
100
+ best = (a + b, k)
101
+ k = best[1]
102
+ return series.dropna().index[k], float(x[:k].mean()), float(x[k:].mean())
103
+
104
+
105
+ def runs_of(mask: np.ndarray, merge_gap: int) -> list[tuple[int, int]]:
106
+ idx = np.flatnonzero(mask)
107
+ if idx.size == 0:
108
+ return []
109
+ runs, start, prev = [], idx[0], idx[0]
110
+ for i in idx[1:]:
111
+ if i - prev > merge_gap:
112
+ runs.append((start, prev))
113
+ start = i
114
+ prev = i
115
+ runs.append((start, prev))
116
+ return runs
117
+
118
+
119
+ def acf(series: pd.Series, lag: int) -> float | None:
120
+ s = series.astype(float)
121
+ if lag >= len(s) - 2:
122
+ return None
123
+ value = s.autocorr(lag)
124
+ return round(float(value), 3) if np.isfinite(value) else None
125
+
126
+
127
+ # --------------------------------------------------------------------------- #
128
+ # Sections
129
+ # --------------------------------------------------------------------------- #
130
+
131
+ def overview(df: pd.DataFrame, summary: dict | None) -> dict:
132
+ span = (df["ts"].max() - df["ts"].min()).total_seconds() / 86400.0
133
+ out = {
134
+ "rows": int(len(df)),
135
+ "runs": int(df["run_id"].nunique()),
136
+ "first_utc": df["ts"].min().strftime("%Y-%m-%dT%H:%M:%SZ"),
137
+ "last_utc": df["ts"].max().strftime("%Y-%m-%dT%H:%M:%SZ"),
138
+ "first_local": str(df["timestamp_local"].iloc[0]),
139
+ "last_local": str(df["timestamp_local"].iloc[-1]),
140
+ "span_days": round(span, 2),
141
+ "full_days": int((df.groupby("date_local").size() >= 2700).sum()),
142
+ "coverage_pct": summary.get("coverage_pct") if summary else None,
143
+ "max_gap_s": float(df["gap_before_s"].max()),
144
+ "gaps_of_2_intervals": int((df["gap_before_s"] == 2 * df["interval_s"].median()).sum()),
145
+ "gaps_over_2_intervals": int((df["gap_before_s"] > 2 * df["interval_s"].median()).sum()),
146
+ "gaps_over_2_intervals_after_speedtest": int((df["download_mbps"].shift(1).notna()
147
+ & (df["gap_before_s"] > 2 * df["interval_s"].median())).sum()),
148
+ "rows_with_notes": int(df["notes"].fillna("").astype(str).str.len().gt(0).sum()),
149
+ "wifi_rows": int(df["wifi_signal_pct"].notna().sum()) if "wifi_signal_pct" in df else 0,
150
+ "link_types": {str(k): int(v) for k, v in df["link_type"].value_counts().items()},
151
+ "metrics": {c: describe(df[c]) for c in METRICS if c in df.columns and describe(df[c])},
152
+ }
153
+ return out
154
+
155
+
156
+ def hour_profile(df: pd.DataFrame) -> list[dict]:
157
+ rows = []
158
+ for hour, part in df.groupby("hour_local"):
159
+ rows.append({
160
+ "hour": int(hour), "n": int(len(part)),
161
+ "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p25": q(part["rtt_avg_ms"], 0.25),
162
+ "rtt_p75": q(part["rtt_avg_ms"], 0.75), "rtt_p95": q(part["rtt_avg_ms"], 0.95),
163
+ "jitter_median": q(part["jitter_ms"], 0.5),
164
+ "loss_share_pct": share(part["packet_loss_pct"] > 0),
165
+ "loss_share_weekday_pct": share(part.loc[part["is_weekend"] == 0, "packet_loss_pct"] > 0),
166
+ "loss_share_weekend_pct": share(part.loc[part["is_weekend"] == 1, "packet_loss_pct"] > 0),
167
+ "http_p95": q(part["http_ms"], 0.95),
168
+ "http_over_1s_pct": share(part["http_ms"].dropna() > 1000),
169
+ "high_latency_pct": share(part["label_high_latency"] == 1),
170
+ "gateway_p95": q(part["gateway_rtt_avg_ms"], 0.95),
171
+ })
172
+ return rows
173
+
174
+
175
+ def weekday_weekend(df: pd.DataFrame) -> dict:
176
+ out = {}
177
+ for name, part in (("weekday", df[df["is_weekend"] == 0]), ("weekend", df[df["is_weekend"] == 1])):
178
+ out[name] = {"n": int(len(part)), "rtt_median": q(part["rtt_avg_ms"], 0.5),
179
+ "rtt_p95": q(part["rtt_avg_ms"], 0.95), "loss_share_pct": share(part["packet_loss_pct"] > 0),
180
+ "jitter_median": q(part["jitter_ms"], 0.5), "http_median": q(part["http_ms"], 0.5)}
181
+ return out
182
+
183
+
184
+ def daily(df: pd.DataFrame) -> list[dict]:
185
+ rows = []
186
+ for date, part in df.groupby("date_local"):
187
+ rows.append({
188
+ "date": str(date), "weekday": int(part["weekday_local"].iloc[0]), "n": int(len(part)),
189
+ "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p95": q(part["rtt_avg_ms"], 0.95),
190
+ "rtt_min_median": q(part["rtt_min_ms"], 0.5),
191
+ "tcp_min_median": q(part["tcp_connect_min_ms"], 0.5),
192
+ "loss_share_pct": share(part["packet_loss_pct"] > 0),
193
+ "mean_loss_pct": round(float(part["packet_loss_pct"].mean()), 3),
194
+ "jitter_median": q(part["jitter_ms"], 0.5),
195
+ "http_p95": q(part["http_ms"], 0.95),
196
+ "anomaly_pct": share(part["label_anomaly"] == 1),
197
+ "gateway_degraded": int(part["label_gateway_degraded"].sum()),
198
+ })
199
+ return rows
200
+
201
+
202
+ def period_stats(part: pd.DataFrame) -> dict:
203
+ return {
204
+ "n": int(len(part)),
205
+ "days": int(part["date_local"].nunique()),
206
+ "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p95": q(part["rtt_avg_ms"], 0.95),
207
+ "rtt_p99": q(part["rtt_avg_ms"], 0.99),
208
+ "jitter_median": q(part["jitter_ms"], 0.5), "jitter_p95": q(part["jitter_ms"], 0.95),
209
+ "loss_share_pct": share(part["packet_loss_pct"] > 0),
210
+ "mean_loss_pct": round(float(part["packet_loss_pct"].mean()), 3),
211
+ "tcp_median": q(part["tcp_connect_median_ms"], 0.5),
212
+ "dns_cached_median": q(part["dns_resolve_ms"], 0.5),
213
+ "dns_recursive_median": q(part["dns_recursive_ms"], 0.5),
214
+ "http_median": q(part["http_ms"], 0.5), "http_p95": q(part["http_ms"], 0.95),
215
+ "http_over_1s_pct": share(part["http_ms"].dropna() > 1000),
216
+ "labels_pct": {c: share(part[c] == 1) for c in LABELS},
217
+ }
218
+
219
+
220
+ def regimes(df: pd.DataFrame) -> dict:
221
+ daily_loss = df.groupby("date_local")["packet_loss_pct"].apply(lambda s: float((s > 0).mean()))
222
+ if len(daily_loss) < 2:
223
+ split, before, after = daily_loss.index[0], float(daily_loss.iloc[0]), float(daily_loss.iloc[0])
224
+ first = second = df
225
+ else:
226
+ split, before, after = change_point(daily_loss)
227
+ first = df[df["date_local"] < split]
228
+ second = df[df["date_local"] >= split]
229
+ return {
230
+ "method": "single least-squares change point in the daily share of samples with ICMP loss",
231
+ "split_date": str(split),
232
+ "daily_loss_share_before_pct": round(100 * before, 2),
233
+ "daily_loss_share_after_pct": round(100 * after, 2),
234
+ "before": {"first_date": str(first["date_local"].min()), "last_date": str(first["date_local"].max()),
235
+ **period_stats(first)},
236
+ "after": {"first_date": str(second["date_local"].min()), "last_date": str(second["date_local"].max()),
237
+ **period_stats(second)},
238
+ }
239
+
240
+
241
+ def outages(df: pd.DataFrame) -> list[dict]:
242
+ out = []
243
+ for a, b in runs_of(df["label_outage"].values == 1, merge_gap=2):
244
+ part = df.iloc[a:b + 1]
245
+ interval = float(df["interval_s"].median())
246
+ out.append({
247
+ "start_local": str(part["timestamp_local"].iloc[0]),
248
+ "end_local": str(part["timestamp_local"].iloc[-1]),
249
+ "weekday": int(part["weekday_local"].iloc[0]),
250
+ "samples": int(len(part)),
251
+ "minutes": round((float(part["epoch_s"].iloc[-1] - part["epoch_s"].iloc[0]) + interval) / 60.0, 1),
252
+ "gateway_unreachable": bool((part["gateway_packet_loss_pct"] == 100).all()),
253
+ "gateway_loss_sample_before": float(df["gateway_packet_loss_pct"].iloc[a - 1]) if a > 0 else None,
254
+ })
255
+ return out
256
+
257
+
258
+ def latency_episodes(df: pd.DataFrame, thresholds: dict) -> list[dict]:
259
+ """High-latency episodes with a diagnosis from the probe that moved."""
260
+ out = []
261
+ for run_id, part in df.groupby("run_id", sort=False):
262
+ part = part.reset_index(drop=True)
263
+ rtt_floor = float(part["rtt_min_ms"].median())
264
+ tcp_floor = float(part["tcp_connect_min_ms"].median())
265
+ gw_thr = (thresholds.get(run_id, {}).get("gateway_rtt_avg_ms") or {}).get("threshold")
266
+ for a, b in runs_of(part["label_high_latency"].values == 1, MERGE_GAP):
267
+ ep = part.iloc[a:b + 1]
268
+ minutes = (float(ep["epoch_s"].iloc[-1] - ep["epoch_s"].iloc[0])) / 60.0
269
+ if minutes < MIN_EPISODE_MIN:
270
+ continue
271
+ rtt_min_med = float(ep["rtt_min_ms"].median())
272
+ tcp_min_med = float(ep["tcp_connect_min_ms"].median())
273
+ gw_med = float(ep["gateway_rtt_avg_ms"].median())
274
+ if gw_thr is not None and gw_med > gw_thr:
275
+ kind = "first hop"
276
+ elif max(rtt_min_med - rtt_floor, tcp_min_med - tcp_floor) >= FLOOR_SHIFT_MS:
277
+ kind = "path change"
278
+ else:
279
+ kind = "queueing"
280
+ out.append({
281
+ "run_id": run_id,
282
+ "start_local": str(ep["timestamp_local"].iloc[0]),
283
+ "end_local": str(ep["timestamp_local"].iloc[-1]),
284
+ "weekday": int(ep["weekday_local"].iloc[0]),
285
+ "hours": round(minutes / 60.0, 2),
286
+ "samples": int(len(ep)),
287
+ "labelled_samples": int(ep["label_high_latency"].sum()),
288
+ "rtt_min_median": round(rtt_min_med, 2),
289
+ "rtt_avg_median": q(ep["rtt_avg_ms"], 0.5),
290
+ "tcp_min_median": round(tcp_min_med, 2),
291
+ "gateway_median": round(gw_med, 2),
292
+ "jitter_median": q(ep["jitter_ms"], 0.5),
293
+ "dns_cached_median": q(ep["dns_resolve_ms"], 0.5),
294
+ "http_median": q(ep["http_ms"], 0.5),
295
+ "loss_share_pct": share(ep["packet_loss_pct"] > 0),
296
+ "run_rtt_min_median": round(rtt_floor, 2),
297
+ "run_tcp_min_median": round(tcp_floor, 2),
298
+ "kind": kind,
299
+ })
300
+ return out
301
+
302
+
303
+ def loss_analysis(df: pd.DataFrame) -> dict:
304
+ ok = df[df["label_outage"] == 0]
305
+ received = ok["packets_received"].dropna().astype(int)
306
+ classes = {
307
+ "no_loss": ok[ok["packet_loss_pct"] == 0],
308
+ "one_lost": ok[ok["packets_received"] == ok["packets_sent"] - 1],
309
+ "two_plus_lost": ok[(ok["packets_received"] <= ok["packets_sent"] - 2) & (ok["packets_received"] > 0)],
310
+ }
311
+ conditional = {}
312
+ for name, part in classes.items():
313
+ conditional[name] = {
314
+ "n": int(len(part)),
315
+ "rtt_median": q(part["rtt_avg_ms"], 0.5),
316
+ "jitter_median": q(part["jitter_ms"], 0.5),
317
+ "tcp_median": q(part["tcp_connect_median_ms"], 0.5),
318
+ "tcp_p95": q(part["tcp_connect_median_ms"], 0.95),
319
+ "tcp_missing_pct": share(part["tcp_connect_median_ms"].isna()),
320
+ "http_median": q(part["http_ms"], 0.5),
321
+ "http_p95": q(part["http_ms"], 0.95),
322
+ "http_over_1s_pct": share(part["http_ms"].dropna() > 1000),
323
+ "dns_recursive_over_200ms_pct": share(part["dns_recursive_ms"].dropna() > 200),
324
+ "gateway_loss_pct": share(part["gateway_packet_loss_pct"] > 0),
325
+ }
326
+ indicator = (df["packet_loss_pct"] > 0).astype(int)
327
+ p_loss = float(indicator.mean())
328
+ p_cond = float(indicator[1:][indicator[:-1].values == 1].mean())
329
+ return {
330
+ "samples_with_loss_pct": share(df["packet_loss_pct"] > 0),
331
+ "mean_loss_pct": round(float(df["packet_loss_pct"].mean()), 3),
332
+ "packets_received_counts": {int(k): int(v) for k, v in received.value_counts().sort_index().items()},
333
+ "gateway_loss_samples_pct": share(df["gateway_packet_loss_pct"] > 0),
334
+ "gateway_loss_outside_outages_samples": int((ok["gateway_packet_loss_pct"] > 0).sum()),
335
+ "persistence": {"p_loss": round(p_loss, 4), "p_loss_given_previous_loss": round(p_cond, 4),
336
+ "ratio": round(p_cond / p_loss, 2) if p_loss else None},
337
+ "conditional": conditional,
338
+ }
339
+
340
+
341
+ def tcp_icmp(df: pd.DataFrame) -> dict:
342
+ gap = df["tcp_connect_min_ms"] - df["rtt_min_ms"]
343
+ hourly = (gap > TCP_SPLIT_MS).astype(float).groupby(df["ts_local"].dt.floor("h")).mean()
344
+ split, before, after = change_point(hourly)
345
+ sec = df[df["ts_local"] >= split]
346
+ v = sec["tcp_connect_min_ms"].dropna()
347
+ return {
348
+ "tcp_min_minus_icmp_min_median_ms": round(float(gap.median()), 3),
349
+ "tcp_median_minus_icmp_avg_median_ms": round(float((df["tcp_connect_median_ms"] - df["rtt_avg_ms"]).median()), 3),
350
+ "split_local": split.strftime("%Y-%m-%dT%H:%M"),
351
+ "long_path_share_before_pct": round(100 * before, 2),
352
+ "long_path_share_after_pct": round(100 * after, 2),
353
+ "after_split": {
354
+ "tcp_min_p25": q(v, 0.25), "tcp_min_median": q(v, 0.5), "tcp_min_p75": q(v, 0.75),
355
+ "icmp_min_median": q(sec["rtt_min_ms"], 0.5), "icmp_avg_median": q(sec["rtt_avg_ms"], 0.5),
356
+ "share_tcp_min_over_17ms_pct": share(v > 17),
357
+ },
358
+ "before_split": {
359
+ "tcp_min_median": q(df.loc[df["ts_local"] < split, "tcp_connect_min_ms"], 0.5),
360
+ "icmp_min_median": q(df.loc[df["ts_local"] < split, "rtt_min_ms"], 0.5),
361
+ },
362
+ }
363
+
364
+
365
+ def dns_http(df: pd.DataFrame) -> dict:
366
+ c, r, h = df["dns_resolve_ms"].dropna(), df["dns_recursive_ms"].dropna(), df["http_ms"].dropna()
367
+ return {
368
+ "dns_cached": {"median": q(c, 0.5), "p05": q(c, 0.05), "p95": q(c, 0.95),
369
+ "share_under_15ms_pct": share(c < 15), "share_under_5ms_pct": share(c < 5)},
370
+ "dns_recursive": {"median": q(r, 0.5), "p95": q(r, 0.95), "p99": q(r, 0.99),
371
+ "share_over_200ms_pct": share(r > 200)},
372
+ "dns_recursive_minus_cached_median_ms": round(float((df["dns_recursive_ms"] - df["dns_resolve_ms"]).median()), 2),
373
+ "dns_timeouts": int(df["notes"].fillna("").astype(str).str.contains("dns: timeout|dns recursive: timeout").sum()),
374
+ "dns_timeouts_during_outages": int((df["notes"].fillna("").astype(str).str.contains("dns: timeout|dns recursive: timeout")
375
+ & (df["label_outage"] == 1)).sum()),
376
+ "http": {"median": q(h, 0.5), "p90": q(h, 0.9), "p95": q(h, 0.95), "p99": q(h, 0.99),
377
+ "share_1000_1400ms_pct": share((h >= 1000) & (h < 1400)),
378
+ "share_3900_4400ms_pct": share((h >= 3900) & (h < 4400)),
379
+ "share_over_1s_pct": share(h > 1000), "share_over_5s_pct": share(h > 5000),
380
+ "timeouts": int(df["notes"].fillna("").astype(str).str.contains("http: timed out").sum()),
381
+ "status_counts": {str(int(k)): int(v) for k, v in df["http_status"].dropna().value_counts().items()}},
382
+ }
383
+
384
+
385
+ def autocorrelation(df: pd.DataFrame) -> dict:
386
+ interval = float(df["interval_s"].median())
387
+ lags = [max(1, int(round(m * 60 / interval))) for m in ACF_LAGS_MIN]
388
+ series = {
389
+ "rtt_avg_ms": df["rtt_avg_ms"],
390
+ "log_rtt_avg_ms": np.log(df["rtt_avg_ms"]),
391
+ "jitter_ms": df["jitter_ms"],
392
+ "loss_indicator": (df["packet_loss_pct"] > 0).astype(float),
393
+ "tcp_connect_min_ms": df["tcp_connect_min_ms"],
394
+ "dns_recursive_ms": df["dns_recursive_ms"],
395
+ "http_ms": df["http_ms"],
396
+ }
397
+ return {"lag_minutes": ACF_LAGS_MIN, "lag_samples": lags,
398
+ "values": {name: [acf(s, l) for l in lags] for name, s in series.items()}}
399
+
400
+
401
+ def speedtest(df: pd.DataFrame) -> dict:
402
+ sp = df[df["download_mbps"].notna()].copy()
403
+ if sp.empty:
404
+ return {"tests": 0}
405
+ failed_ping = sp["speedtest_ping_ms"].isna() | (sp["speedtest_ping_ms"] >= SPEEDTEST_PING_FAILED_MS)
406
+ top = (sp.groupby("speedtest_server")
407
+ .agg(n=("download_mbps", "size"), download_median=("download_mbps", "median"),
408
+ download_max=("download_mbps", "max"), upload_median=("upload_mbps", "median"),
409
+ ping_median=("speedtest_ping_ms", "median"))
410
+ .sort_values("n", ascending=False).head(10))
411
+ return {
412
+ "tests": int(len(sp)),
413
+ "servers": int(sp["speedtest_server"].nunique()),
414
+ "failed_latency_probe": int(failed_ping.sum()),
415
+ "zero_download": int((sp["download_mbps"] == 0).sum()),
416
+ "zero_upload": int((sp["upload_mbps"] == 0).sum()),
417
+ "download": describe(sp["download_mbps"]),
418
+ "upload": describe(sp["upload_mbps"]),
419
+ "download_quantiles": {str(p): q(sp["download_mbps"], p) for p in (0.1, 0.25, 0.5, 0.75, 0.9)},
420
+ "upload_quantiles": {str(p): q(sp["upload_mbps"], p) for p in (0.1, 0.25, 0.5, 0.75, 0.9)},
421
+ "ping_valid": describe(sp.loc[~failed_ping, "speedtest_ping_ms"]),
422
+ "download_median_night_0_4": q(sp.loc[sp["hour_local"].between(0, 4), "download_mbps"], 0.5),
423
+ "download_median_day_9_16": q(sp.loc[sp["hour_local"].between(9, 16), "download_mbps"], 0.5),
424
+ "sample_duration_median_s": q(sp["sample_duration_s"], 0.5),
425
+ "top_servers": [{"server": str(k), **{c: (int(v) if c == "n" else round(float(v), 1)) for c, v in row.items()}}
426
+ for k, row in top.iterrows()],
427
+ }
428
+
429
+
430
+ def labels(df: pd.DataFrame) -> dict:
431
+ M = df[LABELS[:-1]]
432
+ return {
433
+ "counts": {c: int(df[c].sum()) for c in LABELS},
434
+ "share_pct": {c: share(df[c] == 1) for c in LABELS},
435
+ "exactly_one_label": int((M.sum(axis=1) == 1).sum()),
436
+ "two_or_more_labels": int((M.sum(axis=1) >= 2).sum()),
437
+ "high_latency_in_episodes_pct": None,
438
+ }
439
+
440
+
441
+ # --------------------------------------------------------------------------- #
442
+ # Report
443
+ # --------------------------------------------------------------------------- #
444
+
445
+ def analyse(df: pd.DataFrame, summary: dict | None) -> dict:
446
+ thresholds = {r["run_id"]: r.get("thresholds", {}) for r in (summary or {}).get("runs", [])}
447
+ eps = latency_episodes(df, thresholds)
448
+ result = {
449
+ "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
450
+ "overview": overview(df, summary),
451
+ "hour_profile": hour_profile(df),
452
+ "weekday_weekend": weekday_weekend(df),
453
+ "daily": daily(df),
454
+ "regimes": regimes(df),
455
+ "outages": outages(df),
456
+ "latency_episodes": eps,
457
+ "loss": loss_analysis(df),
458
+ "tcp_icmp": tcp_icmp(df),
459
+ "dns_http": dns_http(df),
460
+ "autocorrelation": autocorrelation(df),
461
+ "speedtest": speedtest(df),
462
+ "labels": labels(df),
463
+ }
464
+ total = int(df["label_high_latency"].sum())
465
+ inside = sum(e["labelled_samples"] for e in eps)
466
+ result["labels"]["high_latency_in_episodes_pct"] = round(100.0 * inside / total, 1) if total else None
467
+ result["labels"]["episode_kinds"] = {k: sum(1 for e in eps if e["kind"] == k)
468
+ for k in ("path change", "first hop", "queueing")}
469
+ return result
470
+
471
+
472
+ def print_report(r: dict) -> None:
473
+ o = r["overview"]
474
+ print(f"rows {o['rows']:,} runs {o['runs']} span {o['span_days']} days "
475
+ f"{o['first_utc']} -> {o['last_utc']} coverage {o['coverage_pct']} %")
476
+ print()
477
+ print(f"{'metric':<24}{'n':>8}{'median':>10}{'mean':>10}{'p95':>10}{'p99':>10}{'max':>12}")
478
+ for col, d in o["metrics"].items():
479
+ print(f"{col:<24}{d['n']:>8}{d['median']:>10.2f}{d['mean']:>10.2f}{d['p95']:>10.2f}"
480
+ f"{d['p99']:>10.2f}{d['max']:>12.2f}")
481
+ g = r["regimes"]
482
+ print()
483
+ print(f"regimes (split {g['split_date']}):")
484
+ for name in ("before", "after"):
485
+ p = g[name]
486
+ print(f" {name:<7}{p['first_date']} .. {p['last_date']} n={p['n']:,} rtt med {p['rtt_median']} "
487
+ f"p95 {p['rtt_p95']} loss {p['loss_share_pct']} % jitter med {p['jitter_median']} "
488
+ f"http>1s {p['http_over_1s_pct']} % anomaly {p['labels_pct']['label_anomaly']} %")
489
+ print()
490
+ print(f"outages: {len(r['outages'])}")
491
+ for e in r["outages"]:
492
+ print(f" {e['start_local'][:16]} {e['minutes']} min {e['samples']} samples "
493
+ f"gateway unreachable: {e['gateway_unreachable']}")
494
+ print()
495
+ print(f"high-latency episodes >= {MIN_EPISODE_MIN} min: {len(r['latency_episodes'])}")
496
+ for e in r["latency_episodes"]:
497
+ print(f" {e['start_local'][:16]} -> {e['end_local'][11:16]} {e['hours']:>5.2f} h "
498
+ f"rtt min {e['rtt_min_median']:>5.1f} avg {e['rtt_avg_median']:>5.1f} tcp min {e['tcp_min_median']:>5.1f} "
499
+ f"gw {e['gateway_median']:>5.1f} {e['kind']}")
500
+ t = r["tcp_icmp"]
501
+ print()
502
+ print(f"tcp/icmp: floor offset {t['tcp_min_minus_icmp_min_median_ms']} ms; long-path share "
503
+ f"{t['long_path_share_before_pct']} % -> {t['long_path_share_after_pct']} % from {t['split_local']}")
504
+ L = r["loss"]
505
+ print(f"loss: {L['samples_with_loss_pct']} % of samples; P(loss|loss) = {L['persistence']['p_loss_given_previous_loss']}"
506
+ f" vs {L['persistence']['p_loss']}")
507
+ for name, c in L["conditional"].items():
508
+ print(f" {name:<14}n={c['n']:>6} jitter med {c['jitter_median']:.2f} tcp med {c['tcp_median']:.2f} "
509
+ f"http>1s {c['http_over_1s_pct']:.2f} % dns rec>200ms {c['dns_recursive_over_200ms_pct']:.2f} %")
510
+ s = r["speedtest"]
511
+ if s.get("tests"):
512
+ print(f"speed tests: {s['tests']} on {s['servers']} servers, {s['failed_latency_probe']} failed latency probes, "
513
+ f"{s['zero_download']} zero downloads; download median {s['download']['median']} max {s['download']['max']}; "
514
+ f"upload median {s['upload']['median']} p95 {s['upload']['p95']}")
515
+ print()
516
+ print("labels:")
517
+ for col, n in r["labels"]["counts"].items():
518
+ print(f" {col:<24}{n:>8} ({r['labels']['share_pct'][col]} %)")
519
+ print()
520
+ print("hour-of-day (local):")
521
+ print(f"{'hour':>4}{'n':>7}{'rtt med':>9}{'rtt p95':>9}{'loss %':>8}{'wkday %':>9}{'wkend %':>9}{'http>1s %':>11}{'hi-lat %':>10}")
522
+ for h in r["hour_profile"]:
523
+ print(f"{h['hour']:>4}{h['n']:>7}{h['rtt_median']:>9.2f}{h['rtt_p95']:>9.2f}{h['loss_share_pct']:>8.2f}"
524
+ f"{h['loss_share_weekday_pct']:>9.2f}{h['loss_share_weekend_pct']:>9.2f}{h['http_over_1s_pct']:>11.2f}"
525
+ f"{h['high_latency_pct']:>10.2f}")
526
+
527
+
528
+ def main(argv: list[str] | None = None) -> int:
529
+ p = argparse.ArgumentParser(description="Statistics and findings for the consolidated dataset.")
530
+ p.add_argument("--input", default=None,
531
+ help="consolidated parquet or CSV (default: dataset/localnet_dynamics.parquet)")
532
+ p.add_argument("--summary", default=None, help="summary.json written by build_dataset.py")
533
+ p.add_argument("--output", default=None, help="analysis JSON (default: dataset/analysis.json)")
534
+ p.add_argument("--no-report", action="store_true", help="write the JSON without printing the report")
535
+ args = p.parse_args(argv)
536
+
537
+ path = Path(args.input) if args.input else ROOT / "dataset" / "localnet_dynamics.parquet"
538
+ if not path.exists() and not args.input:
539
+ path = ROOT / "dataset" / "localnet_dynamics.csv"
540
+ if not path.exists():
541
+ raise SystemExit(f"{path} not found; run build_dataset.py first")
542
+ summary_path = Path(args.summary) if args.summary else path.parent / "summary.json"
543
+ summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.exists() else None
544
+
545
+ df = load(path)
546
+ result = analyse(df, summary)
547
+ out = Path(args.output) if args.output else path.parent / "analysis.json"
548
+ out.write_text(json.dumps(result, indent=2), encoding="utf-8")
549
+ if not args.no_report:
550
+ print_report(result)
551
+ print()
552
+ print(f"analysis written to {out}")
553
+ return 0
554
+
555
+
556
+ if __name__ == "__main__":
557
+ sys.exit(main())
scripts/annotate.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Record a manual event annotation for the LocalNet-Dynamics dataset.
4
+
5
+ Events describe things the collector cannot observe by itself: a household
6
+ member starting a 4K stream, a router reboot, a laptop moved to another room,
7
+ a known ISP maintenance window. `build_dataset.py` joins them onto every
8
+ sample whose timestamp falls inside the event window, producing the
9
+ `event_category` and `event_description` columns.
10
+
11
+ Events are appended to dataset/raw/events.csv with UTC timestamps.
12
+
13
+ python annotate.py "4K streaming on the living-room TV" --category load --minutes 45
14
+ python annotate.py "router rebooted" --category maintenance
15
+ python annotate.py "moved laptop to the garden" --category environment \
16
+ --start "2026-09-12 16:00" --end "2026-09-12 18:30"
17
+ python annotate.py --list
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import csv
24
+ import sys
25
+ from datetime import datetime, timedelta, timezone
26
+ from pathlib import Path
27
+
28
+ CATEGORIES = ["load", "outage", "maintenance", "environment", "isp", "device", "other"]
29
+ COLUMNS = ["start_utc", "end_utc", "category", "description"]
30
+ DEFAULT_PATH = Path(__file__).resolve().parent.parent / "dataset" / "raw" / "events.csv"
31
+
32
+
33
+ def parse_time(text: str | None) -> datetime:
34
+ """Interpret a timestamp; naive values are local time."""
35
+ if not text or text.lower() == "now":
36
+ return datetime.now(timezone.utc)
37
+ text = text.strip().replace("Z", "+00:00")
38
+ if " " in text and "T" not in text:
39
+ text = text.replace(" ", "T", 1)
40
+ dt = datetime.fromisoformat(text)
41
+ if dt.tzinfo is None:
42
+ dt = dt.astimezone() # attach the local zone
43
+ return dt.astimezone(timezone.utc)
44
+
45
+
46
+ def fmt(dt: datetime) -> str:
47
+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
48
+
49
+
50
+ def append_event(path: Path, start: datetime, end: datetime, category: str, description: str) -> None:
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ new_file = not path.exists() or path.stat().st_size == 0
53
+ with path.open("a", newline="", encoding="utf-8") as f:
54
+ writer = csv.writer(f)
55
+ if new_file:
56
+ writer.writerow(COLUMNS)
57
+ writer.writerow([fmt(start), fmt(end), category, description])
58
+
59
+
60
+ def list_events(path: Path) -> None:
61
+ if not path.exists():
62
+ print(f"no events recorded yet ({path})")
63
+ return
64
+ with path.open(newline="", encoding="utf-8") as f:
65
+ rows = list(csv.DictReader(f))
66
+ if not rows:
67
+ print("no events recorded yet")
68
+ return
69
+ print(f"{'start (UTC)':<21}{'end (UTC)':<21}{'category':<13}description")
70
+ for r in rows:
71
+ print(f"{r['start_utc']:<21}{r['end_utc']:<21}{r['category']:<13}{r['description']}")
72
+
73
+
74
+ def main(argv: list[str] | None = None) -> int:
75
+ p = argparse.ArgumentParser(description="Append a manual event annotation.")
76
+ p.add_argument("description", nargs="?", help="what happened, in one short sentence")
77
+ p.add_argument("--category", choices=CATEGORIES, default="other")
78
+ p.add_argument("--start", default=None,
79
+ help="event start, local time unless an offset/Z is given "
80
+ "(e.g. '2026-09-12 16:00'); default: now")
81
+ p.add_argument("--end", default=None, help="event end (same format)")
82
+ p.add_argument("--minutes", type=float, default=1.0,
83
+ help="event length when --end is not given")
84
+ p.add_argument("--file", default=str(DEFAULT_PATH), help="events CSV to append to")
85
+ p.add_argument("--list", action="store_true", help="print the recorded events and exit")
86
+ args = p.parse_args(argv)
87
+
88
+ path = Path(args.file)
89
+ if args.list:
90
+ list_events(path)
91
+ return 0
92
+ if not args.description:
93
+ p.error("a description is required (or use --list)")
94
+ try:
95
+ start = parse_time(args.start)
96
+ end = parse_time(args.end) if args.end else start + timedelta(minutes=args.minutes)
97
+ except ValueError as exc:
98
+ p.error(f"invalid timestamp: {exc}")
99
+ if end < start:
100
+ p.error("--end is before --start")
101
+ append_event(path, start, end, args.category, args.description.strip())
102
+ print(f"recorded [{args.category}] {fmt(start)} -> {fmt(end)}: {args.description.strip()}")
103
+ print(f"file: {path}")
104
+ return 0
105
+
106
+
107
+ if __name__ == "__main__":
108
+ sys.exit(main())
scripts/build_dataset.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Consolidate raw collector runs into the published LocalNet-Dynamics dataset.
4
+
5
+ Reads every `localnet_*.csv` (and its `.json` run metadata) from the raw
6
+ directory, validates and merges them (malformed timestamps, duplicates, loss
7
+ percentages outside 0-100 and failed speed-test latency probes are handled),
8
+ adds time-of-day features, gap information, rule-based reference labels and
9
+ manual event annotations, and writes:
10
+
11
+ dataset/localnet_dynamics.csv consolidated dataset
12
+ dataset/localnet_dynamics.parquet same content (needs pyarrow)
13
+ dataset/summary.json statistics, per-run thresholds, label counts
14
+
15
+ It also refreshes the auto-generated statistics section of DATASET_CARD.md so
16
+ the documentation always matches the data.
17
+
18
+ python build_dataset.py
19
+ python build_dataset.py --raw-dir dataset/raw --out-dir dataset --mad-k 5
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import re
27
+ import sys
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+ from collect_data import COLLECTOR_VERSION, CSV_FIELDS # noqa: E402
36
+
37
+ ROOT = Path(__file__).resolve().parent.parent
38
+
39
+ STRING_COLUMNS = ["run_id", "host_label", "timestamp_utc", "timestamp_local", "link_type",
40
+ "gateway_ip", "dns_server", "target", "wifi_ssid", "wifi_phy",
41
+ "speedtest_server", "notes"]
42
+ INT_COLUMNS = ["sample_index", "epoch_s", "packets_sent", "packets_received", "http_status",
43
+ "wifi_signal_pct", "wifi_channel", "speedtest_server_id", "lan_retransmits"]
44
+
45
+ RUN_COLUMNS = ["collector_version", "collector_os", "interval_s", "rtt_resolution_ms"]
46
+ TIME_COLUMNS = ["date_local", "hour_local", "weekday_local", "is_weekend", "gap_before_s"]
47
+ LABEL_COLUMNS = ["label_outage", "label_packet_loss", "label_high_latency",
48
+ "label_high_jitter", "label_gateway_degraded", "label_anomaly"]
49
+ EVENT_COLUMNS = ["event_category", "event_description"]
50
+
51
+ # (column, absolute floor in ms, floor as a fraction of the median)
52
+ THRESHOLD_RULES = {
53
+ "rtt_avg_ms": (10.0, 0.5),
54
+ "jitter_ms": (5.0, 1.0),
55
+ "gateway_rtt_avg_ms": (5.0, 1.0),
56
+ }
57
+
58
+ STATS_COLUMNS = [
59
+ "rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct",
60
+ "gateway_rtt_avg_ms", "gateway_packet_loss_pct", "tcp_connect_median_ms",
61
+ "dns_resolve_ms", "dns_recursive_ms", "http_ms", "wifi_signal_pct", "wifi_rssi_dbm",
62
+ "wifi_rx_mbps", "download_mbps", "upload_mbps", "speedtest_ping_ms",
63
+ "download_loaded_latency_ms", "upload_loaded_latency_ms", "lan_throughput_mbps",
64
+ ]
65
+
66
+ # speedtest-cli scores a failed latency attempt as 3600 s and averages three attempts
67
+ # over six, so one failed attempt already yields a value of at least 600,000 ms.
68
+ SPEEDTEST_PING_FAILED_MS = 600_000
69
+
70
+ CARD_BEGIN = "<!-- BEGIN GENERATED STATISTICS -->"
71
+ CARD_END = "<!-- END GENERATED STATISTICS -->"
72
+
73
+
74
+ # --------------------------------------------------------------------------- #
75
+ # Loading
76
+ # --------------------------------------------------------------------------- #
77
+
78
+ def os_family(platform_string: str) -> str:
79
+ p = (platform_string or "").lower()
80
+ if p.startswith("windows"):
81
+ return "Windows"
82
+ if p.startswith("macos") or p.startswith("darwin"):
83
+ return "macOS"
84
+ if p.startswith("linux"):
85
+ return "Linux"
86
+ return platform_string.split("-")[0] if platform_string else ""
87
+
88
+
89
+ def load_run(csv_path: Path) -> tuple[pd.DataFrame, dict]:
90
+ dtypes = {c: "string" for c in STRING_COLUMNS}
91
+ df = pd.read_csv(csv_path, dtype=dtypes, keep_default_na=True, na_values=[""])
92
+ for c in STRING_COLUMNS:
93
+ if c in df.columns:
94
+ df[c] = df[c].fillna("").astype(str)
95
+ meta: dict = {}
96
+ json_path = csv_path.with_suffix(".json")
97
+ if json_path.exists():
98
+ try:
99
+ meta = json.loads(json_path.read_text(encoding="utf-8"))
100
+ except ValueError:
101
+ meta = {}
102
+ if "run_id" not in df.columns or df["run_id"].eq("").all():
103
+ df["run_id"] = meta.get("run_id") or csv_path.stem.replace("localnet_", "")
104
+ df["collector_version"] = meta.get("collector_version", "")
105
+ df["collector_os"] = os_family((meta.get("environment") or {}).get("os", ""))
106
+ interval = meta.get("interval_s")
107
+ if interval is None and "epoch_s" in df.columns and len(df) > 1:
108
+ interval = float(np.nanmedian(np.diff(df["epoch_s"].astype(float).values)))
109
+ df["interval_s"] = interval
110
+ df["rtt_resolution_ms"] = (meta.get("environment") or {}).get("ping_resolution_ms")
111
+ return df, meta
112
+
113
+
114
+ def load_raw(raw_dir: Path) -> tuple[pd.DataFrame, dict[str, dict]]:
115
+ files = sorted(raw_dir.glob("localnet_*.csv"))
116
+ if not files:
117
+ raise SystemExit(f"no localnet_*.csv files found in {raw_dir}")
118
+ frames, metas = [], {}
119
+ for path in files:
120
+ df, meta = load_run(path)
121
+ if df.empty:
122
+ print(f"skipping empty file {path.name}")
123
+ continue
124
+ frames.append(df)
125
+ metas[str(df["run_id"].iloc[0])] = meta
126
+ print(f"loaded {path.name}: {len(df)} rows")
127
+ df = pd.concat(frames, ignore_index=True, sort=False)
128
+ for c in CSV_FIELDS:
129
+ if c not in df.columns:
130
+ df[c] = "" if c in STRING_COLUMNS else np.nan
131
+ return df, metas
132
+
133
+
134
+ # --------------------------------------------------------------------------- #
135
+ # Validation and derived columns
136
+ # --------------------------------------------------------------------------- #
137
+
138
+ def validate(df: pd.DataFrame) -> pd.DataFrame:
139
+ before = len(df)
140
+ df = df[df["timestamp_utc"].str.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")]
141
+ dropped = before - len(df)
142
+ if dropped:
143
+ print(f"dropped {dropped} rows with malformed timestamps")
144
+ df = df.drop_duplicates(subset=["run_id", "timestamp_utc"], keep="first")
145
+ df = df.sort_values(["run_id", "epoch_s"], kind="stable").reset_index(drop=True)
146
+ for col in ("packet_loss_pct", "gateway_packet_loss_pct"):
147
+ bad = (df[col] < 0) | (df[col] > 100)
148
+ if bad.any():
149
+ print(f"warning: {int(bad.sum())} rows have {col} outside 0-100; set to missing")
150
+ df.loc[bad, col] = np.nan
151
+ failed = df["speedtest_ping_ms"] >= SPEEDTEST_PING_FAILED_MS
152
+ if failed.any():
153
+ print(f"{int(failed.sum())} speed-test rows have a failed server latency probe "
154
+ f"(speedtest_ping_ms >= {SPEEDTEST_PING_FAILED_MS:,}); set to missing")
155
+ df.loc[failed, "speedtest_ping_ms"] = np.nan
156
+ return df
157
+
158
+
159
+ def add_time_features(df: pd.DataFrame) -> pd.DataFrame:
160
+ local = pd.to_datetime(df["timestamp_local"].str[:19], format="%Y-%m-%dT%H:%M:%S", errors="coerce")
161
+ df["date_local"] = local.dt.strftime("%Y-%m-%d")
162
+ df["hour_local"] = local.dt.hour
163
+ df["weekday_local"] = local.dt.dayofweek
164
+ df["is_weekend"] = (local.dt.dayofweek >= 5).astype(int)
165
+ df["gap_before_s"] = df.groupby("run_id")["epoch_s"].diff()
166
+ return df
167
+
168
+
169
+ def robust_threshold(values: pd.Series, floor_abs: float, floor_rel: float, k: float) -> dict:
170
+ v = values.dropna().astype(float)
171
+ if len(v) < 20:
172
+ return {"n": int(len(v)), "median": None, "mad": None, "threshold": None}
173
+ median = float(v.median())
174
+ mad = float((v - median).abs().median())
175
+ threshold = median + max(k * 1.4826 * mad, floor_abs, floor_rel * median)
176
+ return {"n": int(len(v)), "median": round(median, 3), "mad": round(mad, 3),
177
+ "threshold": round(threshold, 3)}
178
+
179
+
180
+ def add_labels(df: pd.DataFrame, k: float) -> tuple[pd.DataFrame, dict]:
181
+ thresholds: dict[str, dict] = {}
182
+ for col in LABEL_COLUMNS:
183
+ df[col] = 0
184
+ sent = df["packets_sent"].fillna(0)
185
+ received = df["packets_received"].fillna(0)
186
+ outage = (sent > 0) & (received == 0)
187
+ df["label_outage"] = outage.astype(int)
188
+ df["label_packet_loss"] = (df["packet_loss_pct"].gt(0) & ~outage).astype(int)
189
+
190
+ for run_id, idx in df.groupby("run_id").groups.items():
191
+ part = df.loc[idx]
192
+ rules = {col: robust_threshold(part[col], fa, fr, k) for col, (fa, fr) in THRESHOLD_RULES.items()}
193
+ thresholds[run_id] = rules
194
+ t = rules["rtt_avg_ms"]["threshold"]
195
+ if t is not None:
196
+ df.loc[idx, "label_high_latency"] = part["rtt_avg_ms"].gt(t).astype(int)
197
+ t = rules["jitter_ms"]["threshold"]
198
+ if t is not None:
199
+ df.loc[idx, "label_high_jitter"] = part["jitter_ms"].gt(t).astype(int)
200
+ t = rules["gateway_rtt_avg_ms"]["threshold"]
201
+ gw = part["gateway_packet_loss_pct"].gt(0)
202
+ if t is not None:
203
+ gw |= part["gateway_rtt_avg_ms"].gt(t)
204
+ df.loc[idx, "label_gateway_degraded"] = gw.astype(int)
205
+
206
+ df["label_anomaly"] = df[LABEL_COLUMNS[:-1]].max(axis=1).astype(int)
207
+ return df, thresholds
208
+
209
+
210
+ def load_events(path: Path) -> pd.DataFrame:
211
+ columns = ["start_utc", "end_utc", "category", "description"]
212
+ if not path.exists():
213
+ return pd.DataFrame(columns=columns)
214
+ ev = pd.read_csv(path, dtype=str, keep_default_na=False)
215
+ missing = [c for c in columns if c not in ev.columns]
216
+ if missing:
217
+ raise SystemExit(f"{path}: missing columns {missing}")
218
+ ev["start"] = pd.to_datetime(ev["start_utc"], utc=True, errors="coerce")
219
+ ev["end"] = pd.to_datetime(ev["end_utc"], utc=True, errors="coerce")
220
+ bad = ev["start"].isna() | ev["end"].isna()
221
+ if bad.any():
222
+ print(f"warning: ignoring {int(bad.sum())} events with unparsable timestamps")
223
+ ev = ev[~bad]
224
+ return ev.reset_index(drop=True)
225
+
226
+
227
+ def add_events(df: pd.DataFrame, events: pd.DataFrame) -> pd.DataFrame:
228
+ df["event_category"] = ""
229
+ df["event_description"] = ""
230
+ if events.empty:
231
+ return df
232
+ ts = pd.to_datetime(df["timestamp_utc"], utc=True)
233
+ cats = [[] for _ in range(len(df))]
234
+ descs = [[] for _ in range(len(df))]
235
+ for _, ev in events.iterrows():
236
+ hit = np.flatnonzero((ts >= ev["start"]) & (ts <= ev["end"]))
237
+ for i in hit:
238
+ cats[i].append(str(ev["category"]))
239
+ descs[i].append(str(ev["description"]))
240
+ df["event_category"] = [" | ".join(c) for c in cats]
241
+ df["event_description"] = [" | ".join(d) for d in descs]
242
+ return df
243
+
244
+
245
+ def order_columns(df: pd.DataFrame) -> pd.DataFrame:
246
+ base = [c for c in CSV_FIELDS if c != "notes"]
247
+ head = base[:11]
248
+ body = base[11:]
249
+ ordered = head + RUN_COLUMNS + TIME_COLUMNS + body + LABEL_COLUMNS + EVENT_COLUMNS + ["notes"]
250
+ extra = [c for c in df.columns if c not in ordered]
251
+ return df[ordered + extra]
252
+
253
+
254
+ def cast_types(df: pd.DataFrame) -> pd.DataFrame:
255
+ for col in INT_COLUMNS + ["hour_local", "weekday_local", "is_weekend"] + LABEL_COLUMNS:
256
+ if col in df.columns:
257
+ df[col] = df[col].astype("Int64")
258
+ return df
259
+
260
+
261
+ # --------------------------------------------------------------------------- #
262
+ # Summary and dataset card
263
+ # --------------------------------------------------------------------------- #
264
+
265
+ def column_summary(series: pd.Series) -> dict | None:
266
+ v = series.dropna().astype(float)
267
+ if v.empty:
268
+ return None
269
+ return {"count": int(v.size), "mean": round(float(v.mean()), 3),
270
+ "median": round(float(v.median()), 3), "p95": round(float(v.quantile(0.95)), 3),
271
+ "min": round(float(v.min()), 3), "max": round(float(v.max()), 3)}
272
+
273
+
274
+ def build_summary(df: pd.DataFrame, metas: dict, thresholds: dict, events: pd.DataFrame,
275
+ k: float) -> dict:
276
+ ts = pd.to_datetime(df["timestamp_utc"], utc=True)
277
+ runs = []
278
+ expected_total = 0.0
279
+ for run_id, part in df.groupby("run_id", sort=True):
280
+ meta = metas.get(run_id, {})
281
+ interval = part["interval_s"].iloc[0]
282
+ span = float(part["epoch_s"].max() - part["epoch_s"].min())
283
+ expected = span / float(interval) + 1 if interval and interval > 0 else len(part)
284
+ expected_total += expected
285
+ runs.append({
286
+ "run_id": run_id,
287
+ "host_label": part["host_label"].iloc[0],
288
+ "rows": int(len(part)),
289
+ "first_utc": part["timestamp_utc"].iloc[0],
290
+ "last_utc": part["timestamp_utc"].iloc[-1],
291
+ "span_hours": round(span / 3600.0, 2),
292
+ "interval_s": float(interval) if interval else None,
293
+ "coverage_pct": round(100.0 * len(part) / expected, 2) if expected else None,
294
+ "link_types": {str(k_): int(v) for k_, v in part["link_type"].value_counts().items()},
295
+ "collector_version": meta.get("collector_version", ""),
296
+ "os": (meta.get("environment") or {}).get("os", ""),
297
+ "status": meta.get("status", ""),
298
+ "thresholds": thresholds.get(run_id, {}),
299
+ })
300
+ labels = {col: {"rows": int(df[col].sum()), "share_pct": round(100.0 * float(df[col].mean()), 3)}
301
+ for col in LABEL_COLUMNS}
302
+ return {
303
+ "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
304
+ "builder_version": COLLECTOR_VERSION,
305
+ "rows": int(len(df)),
306
+ "columns": int(df.shape[1]),
307
+ "runs": runs,
308
+ "first_utc": ts.min().strftime("%Y-%m-%dT%H:%M:%SZ"),
309
+ "last_utc": ts.max().strftime("%Y-%m-%dT%H:%M:%SZ"),
310
+ "span_days": round((ts.max() - ts.min()).total_seconds() / 86400.0, 2),
311
+ "coverage_pct": round(100.0 * len(df) / expected_total, 2) if expected_total else None,
312
+ "label_rule": {
313
+ "mad_k": k,
314
+ "description": "threshold = median + max(k * 1.4826 * MAD, absolute floor, "
315
+ "relative floor * median), computed per run",
316
+ "floors": {c: {"absolute_ms": fa, "relative": fr} for c, (fa, fr) in THRESHOLD_RULES.items()},
317
+ },
318
+ "labels": labels,
319
+ "events": int(len(events)),
320
+ "metrics": {c: column_summary(df[c]) for c in STATS_COLUMNS if column_summary(df[c])},
321
+ }
322
+
323
+
324
+ def size_category(n: int) -> str:
325
+ bounds = [(1_000, "n<1K"), (10_000, "1K<n<10K"), (100_000, "10K<n<100K"),
326
+ (1_000_000, "100K<n<1M"), (10_000_000, "1M<n<10M")]
327
+ for limit, label in bounds:
328
+ if n < limit:
329
+ return label
330
+ return "10M<n<100M"
331
+
332
+
333
+ def render_card_block(summary: dict) -> str:
334
+ lines = [CARD_BEGIN,
335
+ f"Generated by `scripts/build_dataset.py` on {summary['generated_utc']} "
336
+ f"from {len(summary['runs'])} collection run(s).", "",
337
+ "| Item | Value |", "|---|---|",
338
+ f"| Rows | {summary['rows']:,} |",
339
+ f"| Columns | {summary['columns']} |",
340
+ f"| First sample (UTC) | {summary['first_utc']} |",
341
+ f"| Last sample (UTC) | {summary['last_utc']} |",
342
+ f"| Span | {summary['span_days']} days |",
343
+ f"| Sampling coverage | {summary['coverage_pct']} % of the samples expected at the configured interval |",
344
+ f"| Manual event annotations | {summary['events']} |", ""]
345
+ lines += ["| Run | Vantage | Link | OS | Interval | Rows | Span | Coverage |",
346
+ "|---|---|---|---|---|---|---|---|"]
347
+ for r in summary["runs"]:
348
+ links = ", ".join(f"{k_} ({v})" for k_, v in r["link_types"].items())
349
+ interval = f"{r['interval_s']:.0f} s" if r["interval_s"] else "-"
350
+ lines.append(f"| {r['run_id']} | {r['host_label'] or '-'} | {links} | {os_family(r['os']) or '-'} | "
351
+ f"{interval} | {r['rows']:,} | {r['span_hours']} h | {r['coverage_pct']} % |")
352
+ lines += ["", "| Metric | n | Median | Mean | p95 | Max |", "|---|---|---|---|---|---|"]
353
+ for col, st in summary["metrics"].items():
354
+ lines.append(f"| {col} | {st['count']:,} | {st['median']} | {st['mean']} | {st['p95']} | {st['max']} |")
355
+ lines += ["", "| Reference label | Rows | Share |", "|---|---|---|"]
356
+ for col, st in summary["labels"].items():
357
+ lines.append(f"| {col} | {st['rows']:,} | {st['share_pct']} % |")
358
+ lines += ["", CARD_END]
359
+ return "\n".join(lines)
360
+
361
+
362
+ def update_card(card_path: Path, summary: dict) -> None:
363
+ text = card_path.read_text(encoding="utf-8")
364
+ if CARD_BEGIN not in text or CARD_END not in text:
365
+ print(f"warning: {card_path.name} has no generated-statistics markers; not updated")
366
+ return
367
+ block = render_card_block(summary)
368
+ pattern = re.compile(re.escape(CARD_BEGIN) + r".*?" + re.escape(CARD_END), re.DOTALL)
369
+ text = pattern.sub(lambda _: block, text, count=1)
370
+ text = re.sub(r"(size_categories:\s*\n\s*-\s*)(\S+)", lambda m: m.group(1) + size_category(summary["rows"]),
371
+ text, count=1)
372
+ card_path.write_text(text, encoding="utf-8")
373
+ print(f"updated statistics in {card_path}")
374
+
375
+
376
+ # --------------------------------------------------------------------------- #
377
+ # CLI
378
+ # --------------------------------------------------------------------------- #
379
+
380
+ def main(argv: list[str] | None = None) -> int:
381
+ p = argparse.ArgumentParser(description="Build the consolidated LocalNet-Dynamics dataset.")
382
+ p.add_argument("--raw-dir", default=str(ROOT / "dataset" / "raw"))
383
+ p.add_argument("--out-dir", default=str(ROOT / "dataset"))
384
+ p.add_argument("--events", default=None, help="events CSV (default: <raw-dir>/events.csv)")
385
+ p.add_argument("--card", default=str(ROOT / "DATASET_CARD.md"))
386
+ p.add_argument("--no-card", action="store_true", help="do not touch the dataset card")
387
+ p.add_argument("--no-parquet", action="store_true")
388
+ p.add_argument("--mad-k", type=float, default=5.0,
389
+ help="MAD multiplier for the high-latency / high-jitter / gateway rules")
390
+ args = p.parse_args(argv)
391
+
392
+ raw_dir, out_dir = Path(args.raw_dir), Path(args.out_dir)
393
+ out_dir.mkdir(parents=True, exist_ok=True)
394
+ events_path = Path(args.events) if args.events else raw_dir / "events.csv"
395
+
396
+ df, metas = load_raw(raw_dir)
397
+ df = validate(df)
398
+ df = add_time_features(df)
399
+ df, thresholds = add_labels(df, args.mad_k)
400
+ events = load_events(events_path)
401
+ df = add_events(df, events)
402
+ df = cast_types(order_columns(df))
403
+
404
+ csv_out = out_dir / "localnet_dynamics.csv"
405
+ df.to_csv(csv_out, index=False)
406
+ print(f"wrote {csv_out} ({len(df):,} rows, {df.shape[1]} columns)")
407
+ if not args.no_parquet:
408
+ try:
409
+ parquet_out = out_dir / "localnet_dynamics.parquet"
410
+ df.to_parquet(parquet_out, index=False)
411
+ print(f"wrote {parquet_out}")
412
+ except (ImportError, ValueError) as exc:
413
+ print(f"parquet not written ({exc}); install pyarrow to enable it")
414
+
415
+ summary = build_summary(df, metas, thresholds, events, args.mad_k)
416
+ (out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
417
+ print(f"wrote {out_dir / 'summary.json'}")
418
+ if not args.no_card and Path(args.card).exists():
419
+ update_card(Path(args.card), summary)
420
+
421
+ print(f"\nrows: {summary['rows']:,} span: {summary['span_days']} days "
422
+ f"coverage: {summary['coverage_pct']} %")
423
+ for col, st in summary["labels"].items():
424
+ print(f" {col:<24}{st['rows']:>8} ({st['share_pct']} %)")
425
+ return 0
426
+
427
+
428
+ if __name__ == "__main__":
429
+ sys.exit(main())
scripts/collect_data.py ADDED
@@ -0,0 +1,1583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ LocalNet-Dynamics telemetry collector.
4
+
5
+ Samples the network at a fixed cadence from a single client machine and
6
+ appends one row per sample to a CSV file in real time. Each sample records:
7
+
8
+ * ICMP round-trip time to a reference target (min/avg/median/max/stddev),
9
+ inter-packet jitter and packet loss
10
+ * ICMP round-trip time and loss to the default gateway (first hop)
11
+ * TCP connect time to the target (sub-millisecond resolution on every OS)
12
+ * DNS response time of the configured resolver for a fixed name and for a
13
+ never-before-seen name (forces a full recursive lookup)
14
+ * HTTP time-to-first-response for a small connectivity-check URL
15
+ * Wi-Fi link metrics when the machine is on wireless (signal, PHY rate,
16
+ channel, band, standard)
17
+ * WAN throughput (Ookla Speedtest) and LAN throughput (iperf3) on their own,
18
+ slower cadence
19
+
20
+ The collector depends only on the Python standard library and the operating
21
+ system's `ping` utility. Optional external tools: Ookla `speedtest` CLI or the
22
+ `speedtest-cli` Python package (WAN throughput), `iperf3` (LAN throughput).
23
+
24
+ Typical use, 30-second cadence for 30 days with an hourly WAN speed test:
25
+
26
+ python collect_data.py --duration 30d --interval 30s --speedtest --speedtest-every 1h
27
+
28
+ Run `python collect_data.py --check` to verify the environment and print one
29
+ sample without writing any files.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import base64
36
+ import contextlib
37
+ import csv
38
+ import json
39
+ import os
40
+ import platform
41
+ import random
42
+ import re
43
+ import shutil
44
+ import signal
45
+ import socket
46
+ import statistics
47
+ import struct
48
+ import subprocess
49
+ import sys
50
+ import time
51
+ import urllib.error
52
+ import urllib.request
53
+ from concurrent.futures import ThreadPoolExecutor
54
+ from dataclasses import asdict, dataclass, fields
55
+ from datetime import datetime, timezone
56
+ from pathlib import Path
57
+ from typing import Optional
58
+
59
+ COLLECTOR_VERSION = "2.0.1"
60
+
61
+ IS_WINDOWS = sys.platform.startswith("win")
62
+ IS_MACOS = sys.platform == "darwin"
63
+ IS_LINUX = sys.platform.startswith("linux")
64
+
65
+ ROUTE_REFRESH_S = 900.0 # re-detect gateway / link type every 15 min
66
+ META_REFRESH_S = 300.0 # rewrite the run metadata JSON every 5 min
67
+ SPEEDTEST_PING_FAILED_MS = 600_000.0 # speedtest-cli scores a failed latency attempt as 3600 s
68
+ USER_AGENT = f"LocalNet-Dynamics/{COLLECTOR_VERSION}"
69
+
70
+
71
+ # --------------------------------------------------------------------------- #
72
+ # Duration parsing
73
+ # --------------------------------------------------------------------------- #
74
+
75
+ _DURATION_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([smhd]?)\s*$", re.IGNORECASE)
76
+ _UNIT_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}
77
+
78
+
79
+ def parse_duration(text: str) -> float:
80
+ """Parse '90', '30s', '10m', '2h', '1.5d' into seconds."""
81
+ m = _DURATION_RE.match(str(text))
82
+ if not m:
83
+ raise argparse.ArgumentTypeError(
84
+ f"invalid duration {text!r} (examples: 30s, 10m, 2h, 7d)"
85
+ )
86
+ value, unit = float(m.group(1)), m.group(2).lower()
87
+ return value * _UNIT_SECONDS[unit]
88
+
89
+
90
+ def human_duration(seconds: float) -> str:
91
+ seconds = int(round(seconds))
92
+ parts = []
93
+ for label, size in (("d", 86400), ("h", 3600), ("m", 60), ("s", 1)):
94
+ if seconds >= size:
95
+ parts.append(f"{seconds // size}{label}")
96
+ seconds %= size
97
+ return " ".join(parts) or "0s"
98
+
99
+
100
+ # --------------------------------------------------------------------------- #
101
+ # Sample schema
102
+ # --------------------------------------------------------------------------- #
103
+
104
+ @dataclass
105
+ class Sample:
106
+ run_id: str = ""
107
+ host_label: str = ""
108
+ sample_index: int = 0
109
+ timestamp_utc: str = ""
110
+ timestamp_local: str = ""
111
+ epoch_s: int = 0
112
+ elapsed_s: float = 0.0
113
+ link_type: str = ""
114
+ gateway_ip: str = ""
115
+ dns_server: str = ""
116
+ target: str = ""
117
+ rtt_min_ms: Optional[float] = None
118
+ rtt_avg_ms: Optional[float] = None
119
+ rtt_median_ms: Optional[float] = None
120
+ rtt_max_ms: Optional[float] = None
121
+ rtt_stddev_ms: Optional[float] = None
122
+ jitter_ms: Optional[float] = None
123
+ packets_sent: Optional[int] = None
124
+ packets_received: Optional[int] = None
125
+ packet_loss_pct: Optional[float] = None
126
+ gateway_rtt_min_ms: Optional[float] = None
127
+ gateway_rtt_avg_ms: Optional[float] = None
128
+ gateway_rtt_max_ms: Optional[float] = None
129
+ gateway_jitter_ms: Optional[float] = None
130
+ gateway_packet_loss_pct: Optional[float] = None
131
+ tcp_connect_min_ms: Optional[float] = None
132
+ tcp_connect_median_ms: Optional[float] = None
133
+ dns_resolve_ms: Optional[float] = None
134
+ dns_recursive_ms: Optional[float] = None
135
+ http_ms: Optional[float] = None
136
+ http_status: Optional[int] = None
137
+ wifi_ssid: str = ""
138
+ wifi_signal_pct: Optional[int] = None
139
+ wifi_rssi_dbm: Optional[float] = None
140
+ wifi_rx_mbps: Optional[float] = None
141
+ wifi_tx_mbps: Optional[float] = None
142
+ wifi_channel: Optional[int] = None
143
+ wifi_band_ghz: Optional[float] = None
144
+ wifi_phy: str = ""
145
+ download_mbps: Optional[float] = None
146
+ upload_mbps: Optional[float] = None
147
+ speedtest_ping_ms: Optional[float] = None
148
+ download_loaded_latency_ms: Optional[float] = None
149
+ upload_loaded_latency_ms: Optional[float] = None
150
+ speedtest_server_id: Optional[int] = None
151
+ speedtest_server: str = ""
152
+ lan_throughput_mbps: Optional[float] = None
153
+ lan_retransmits: Optional[int] = None
154
+ sample_duration_s: Optional[float] = None
155
+ notes: str = ""
156
+
157
+
158
+ CSV_FIELDS = [f.name for f in fields(Sample)]
159
+
160
+ SUMMARY_KEYS = [
161
+ "rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct",
162
+ "gateway_rtt_avg_ms", "gateway_packet_loss_pct",
163
+ "tcp_connect_median_ms", "dns_resolve_ms", "dns_recursive_ms", "http_ms",
164
+ "wifi_signal_pct", "wifi_rssi_dbm", "wifi_rx_mbps",
165
+ "download_mbps", "upload_mbps", "speedtest_ping_ms",
166
+ "download_loaded_latency_ms", "upload_loaded_latency_ms",
167
+ "lan_throughput_mbps", "sample_duration_s",
168
+ ]
169
+
170
+
171
+ # --------------------------------------------------------------------------- #
172
+ # Subprocess helpers
173
+ # --------------------------------------------------------------------------- #
174
+
175
+ def _console_encoding() -> str:
176
+ """Encoding used by console tools (OEM code page on Windows)."""
177
+ if IS_WINDOWS:
178
+ try:
179
+ import ctypes
180
+ cp = ctypes.windll.kernel32.GetOEMCP() # type: ignore[attr-defined]
181
+ if cp:
182
+ return f"cp{cp}"
183
+ except Exception:
184
+ pass
185
+ return "utf-8"
186
+
187
+
188
+ def decode_output(data: bytes, encoding: Optional[str] = None) -> str:
189
+ for enc in ((encoding,) if encoding else ()) + ("utf-8", _console_encoding(), "latin-1"):
190
+ try:
191
+ return data.decode(enc)
192
+ except (UnicodeDecodeError, LookupError):
193
+ continue
194
+ return data.decode("utf-8", errors="replace")
195
+
196
+
197
+ def run_cmd(args: list[str], timeout: float = 20.0,
198
+ encoding: Optional[str] = None) -> tuple[Optional[int], str]:
199
+ """Run a command, returning (exit code, combined decoded output).
200
+
201
+ The exit code is None when the command timed out or could not be started.
202
+ """
203
+ try:
204
+ proc = subprocess.run(args, capture_output=True, timeout=timeout)
205
+ except subprocess.TimeoutExpired as exc:
206
+ out = (exc.stdout or b"") + (exc.stderr or b"")
207
+ return None, decode_output(out, encoding)
208
+ except (FileNotFoundError, OSError):
209
+ return None, ""
210
+ return proc.returncode, decode_output(proc.stdout + proc.stderr, encoding)
211
+
212
+
213
+ def run_powershell(script: str, timeout: float = 30.0) -> str:
214
+ """Run a PowerShell script (Windows only) and return its UTF-8 stdout."""
215
+ if not IS_WINDOWS:
216
+ return ""
217
+ wrapped = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n" + script
218
+ encoded = base64.b64encode(wrapped.encode("utf-16-le")).decode("ascii")
219
+ for exe in ("powershell", "pwsh"):
220
+ if shutil.which(exe) is None:
221
+ continue
222
+ code, out = run_cmd(
223
+ [exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
224
+ "-EncodedCommand", encoded],
225
+ timeout=timeout, encoding="utf-8",
226
+ )
227
+ if code == 0 and out.strip():
228
+ return out
229
+ return ""
230
+
231
+
232
+ # --------------------------------------------------------------------------- #
233
+ # ICMP ping
234
+ # --------------------------------------------------------------------------- #
235
+
236
+ @dataclass
237
+ class PingResult:
238
+ sent: int = 0
239
+ received: int = 0
240
+ rtts: Optional[list[float]] = None
241
+ error: Optional[str] = None
242
+
243
+ @property
244
+ def loss_pct(self) -> Optional[float]:
245
+ if self.sent <= 0:
246
+ return None
247
+ lost = max(0, self.sent - self.received)
248
+ return round(100.0 * lost / self.sent, 1)
249
+
250
+
251
+ # RTT token of a reply line: "time=14.2 ms", "time=14ms", "time<1ms",
252
+ # "Zeit=14ms", "时间=14ms", "temps=14 ms", "время=14мс". The localized label
253
+ # before the operator is irrelevant; the unit is matched in Latin and Cyrillic.
254
+ # The operator must directly follow a non-space character, which excludes the
255
+ # summary lines ("Minimum = 14ms", "min/avg/max = 13.9/14.5/15.2 ms").
256
+ _RTT_RE = re.compile(r"\S([=<])\s*(\d+(?:[.,]\d+)?)\s*(?:ms|мс)\b", re.IGNORECASE)
257
+
258
+
259
+ def parse_ping_output(text: str, sent: int) -> PingResult:
260
+ """Extract per-reply RTTs from `ping` output in a locale-independent way.
261
+
262
+ Windows prints integer milliseconds and reports sub-millisecond replies as
263
+ "<1ms"; those are stored as 0.0.
264
+ """
265
+ rtts: list[float] = []
266
+ for line in text.splitlines():
267
+ if "DUP!" in line: # duplicate reply (Linux) - not a new echo
268
+ continue
269
+ m = _RTT_RE.search(line)
270
+ if not m:
271
+ continue
272
+ if m.group(1) == "<":
273
+ rtts.append(0.0)
274
+ else:
275
+ rtts.append(float(m.group(2).replace(",", ".")))
276
+ return PingResult(sent=sent, received=len(rtts), rtts=rtts)
277
+
278
+
279
+ _PING_FLAVOR: Optional[str] = None
280
+
281
+
282
+ def ping_flavor() -> str:
283
+ """windows | iputils | busybox | bsd (cached)."""
284
+ global _PING_FLAVOR
285
+ if _PING_FLAVOR is None:
286
+ if IS_WINDOWS:
287
+ _PING_FLAVOR = "windows"
288
+ elif IS_LINUX:
289
+ _, out = run_cmd(["ping", "-V"], timeout=5.0)
290
+ _PING_FLAVOR = "busybox" if "busybox" in out.lower() else "iputils"
291
+ else:
292
+ _PING_FLAVOR = "bsd"
293
+ return _PING_FLAVOR
294
+
295
+
296
+ def ping_command(host: str, count: int, timeout_s: float, flavor: str) -> list[str]:
297
+ ipv6 = ":" in host
298
+ if flavor == "windows":
299
+ cmd = ["ping", "-n", str(count), "-w", str(int(timeout_s * 1000))]
300
+ cmd.append("-6" if ipv6 else "-4")
301
+ return cmd + [host]
302
+ wait_s = str(max(1, int(round(timeout_s))))
303
+ if flavor == "iputils":
304
+ return ["ping", "-n", "-c", str(count), "-W", wait_s, host]
305
+ if flavor == "busybox":
306
+ return ["ping", "-c", str(count), "-W", wait_s, host]
307
+ # macOS / BSD: -W is the per-reply wait in milliseconds
308
+ return ["ping", "-n", "-c", str(count), "-W", str(int(timeout_s * 1000)), host]
309
+
310
+
311
+ def ping(host: str, count: int, timeout_s: float) -> PingResult:
312
+ if shutil.which("ping") is None:
313
+ return PingResult(sent=0, received=0, rtts=[], error="ping utility not found")
314
+ budget = count * (1.0 + timeout_s) + 5.0
315
+ code, out = run_cmd(ping_command(host, count, timeout_s, ping_flavor()), timeout=budget)
316
+ result = parse_ping_output(out, sent=count)
317
+ if code is None and not out:
318
+ result.error = "ping could not be started"
319
+ result.sent = 0
320
+ elif result.received == 0:
321
+ result.error = "no replies"
322
+ return result
323
+
324
+
325
+ def rtt_stats(rtts: list[float]) -> dict:
326
+ """min/avg/median/max/stddev/jitter for a burst of RTT samples."""
327
+ if not rtts:
328
+ return {"min": None, "avg": None, "median": None, "max": None,
329
+ "stddev": None, "jitter": None}
330
+ jitter = None
331
+ if len(rtts) > 1:
332
+ diffs = [abs(rtts[i] - rtts[i - 1]) for i in range(1, len(rtts))]
333
+ jitter = round(sum(diffs) / len(diffs), 3)
334
+ return {
335
+ "min": round(min(rtts), 3),
336
+ "avg": round(sum(rtts) / len(rtts), 3),
337
+ "median": round(statistics.median(rtts), 3),
338
+ "max": round(max(rtts), 3),
339
+ "stddev": round(statistics.pstdev(rtts), 3) if len(rtts) > 1 else 0.0,
340
+ "jitter": jitter,
341
+ }
342
+
343
+
344
+ # --------------------------------------------------------------------------- #
345
+ # Route, gateway, resolver and link-type detection
346
+ # --------------------------------------------------------------------------- #
347
+
348
+ @dataclass
349
+ class NetworkInfo:
350
+ gateway: Optional[str] = None
351
+ interface: Optional[str] = None
352
+ local_ip: Optional[str] = None
353
+ link_type: str = "unknown" # wifi | ethernet | other | unknown
354
+ dns_servers: Optional[list[str]] = None
355
+ source: str = ""
356
+
357
+
358
+ _WINDOWS_ROUTE_PS = r"""
359
+ $ErrorActionPreference = 'SilentlyContinue'
360
+ $routes = Get-NetRoute -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' |
361
+ Where-Object { $_.NextHop -ne '0.0.0.0' } |
362
+ Where-Object { (Get-NetAdapter -InterfaceIndex $_.ifIndex).Status -eq 'Up' }
363
+ $r = $routes | Sort-Object { $_.RouteMetric + $_.InterfaceMetric } | Select-Object -First 1
364
+ if ($r) {
365
+ $a = Get-NetAdapter -InterfaceIndex $r.ifIndex
366
+ $ip = (Get-NetIPAddress -InterfaceIndex $r.ifIndex -AddressFamily IPv4 | Select-Object -First 1).IPAddress
367
+ $dns = (Get-DnsClientServerAddress -InterfaceIndex $r.ifIndex -AddressFamily IPv4).ServerAddresses
368
+ $o = [ordered]@{ gateway = [string]$r.NextHop; ifindex = $r.ifIndex; alias = [string]$a.Name;
369
+ media = [string]$a.PhysicalMediaType; ip = [string]$ip; dns = @($dns) }
370
+ $o | ConvertTo-Json -Compress
371
+ }
372
+ """
373
+
374
+ _ROUTE_PRINT_RE = re.compile(
375
+ r"^\s*0\.0\.0\.0\s+0\.0\.0\.0\s+([\d.]+)\s+([\d.]+)\s+(\d+)\s*$", re.MULTILINE)
376
+
377
+
378
+ def parse_route_print(text: str) -> Optional[tuple[str, str]]:
379
+ """Parse `route print -4 0.0.0.0` output -> (gateway, interface_ip)."""
380
+ best = None
381
+ for gw, iface_ip, metric in _ROUTE_PRINT_RE.findall(text):
382
+ m = int(metric)
383
+ if best is None or m < best[0]:
384
+ best = (m, gw, iface_ip)
385
+ return (best[1], best[2]) if best else None
386
+
387
+
388
+ def _link_type_from_media(media: str) -> str:
389
+ media = (media or "").lower()
390
+ if "802.11" in media or "wireless" in media or "wi-fi" in media:
391
+ return "wifi"
392
+ if "802.3" in media or "ethernet" in media:
393
+ return "ethernet"
394
+ if not media or media == "unspecified":
395
+ return "unknown"
396
+ return "other"
397
+
398
+
399
+ def detect_network_windows() -> NetworkInfo:
400
+ info = NetworkInfo()
401
+ out = run_powershell(_WINDOWS_ROUTE_PS, timeout=40.0)
402
+ if out.strip():
403
+ try:
404
+ data = json.loads(out.strip().splitlines()[-1])
405
+ info.gateway = data.get("gateway") or None
406
+ info.interface = data.get("alias") or None
407
+ info.local_ip = data.get("ip") or None
408
+ info.link_type = _link_type_from_media(data.get("media", ""))
409
+ dns = data.get("dns") or []
410
+ if isinstance(dns, str):
411
+ dns = [dns]
412
+ info.dns_servers = [d for d in dns if d and ":" not in d] or None
413
+ info.source = "powershell"
414
+ if info.gateway:
415
+ return info
416
+ except (ValueError, AttributeError):
417
+ pass
418
+ code, out = run_cmd(["route", "print", "-4", "0.0.0.0"], timeout=20.0)
419
+ parsed = parse_route_print(out)
420
+ if parsed:
421
+ info.gateway, info.local_ip = parsed
422
+ info.source = "route print"
423
+ return info
424
+
425
+
426
+ def parse_ip_route_get(text: str) -> dict:
427
+ """Parse `ip -o route get <ip>` output into via/dev/src."""
428
+ out = {}
429
+ for key in ("via", "dev", "src"):
430
+ m = re.search(rf"\b{key}\s+(\S+)", text)
431
+ if m:
432
+ out[key] = m.group(1)
433
+ return out
434
+
435
+
436
+ def _linux_is_wireless(dev: str) -> bool:
437
+ base = Path("/sys/class/net") / dev
438
+ return (base / "wireless").exists() or (base / "phy80211").exists()
439
+
440
+
441
+ def parse_resolv_conf(text: str) -> list[str]:
442
+ servers = []
443
+ for line in text.splitlines():
444
+ line = line.split("#", 1)[0].strip()
445
+ if line.startswith("nameserver"):
446
+ parts = line.split()
447
+ if len(parts) >= 2:
448
+ servers.append(parts[1])
449
+ return servers
450
+
451
+
452
+ def detect_network_linux(target: str) -> NetworkInfo:
453
+ info = NetworkInfo(source="ip route")
454
+ code, out = run_cmd(["ip", "-o", "route", "get", target], timeout=10.0)
455
+ parsed = parse_ip_route_get(out) if code == 0 else {}
456
+ if not parsed.get("via"):
457
+ code, out = run_cmd(["ip", "-o", "route", "show", "default"], timeout=10.0)
458
+ parsed = parse_ip_route_get(out) if code == 0 else {}
459
+ info.gateway = parsed.get("via")
460
+ info.interface = parsed.get("dev")
461
+ info.local_ip = parsed.get("src")
462
+ if info.interface:
463
+ info.link_type = "wifi" if _linux_is_wireless(info.interface) else "ethernet"
464
+ if info.interface.startswith(("tun", "tap", "wg", "ppp")):
465
+ info.link_type = "other"
466
+ servers: list[str] = []
467
+ try:
468
+ servers = parse_resolv_conf(Path("/etc/resolv.conf").read_text(encoding="utf-8"))
469
+ except OSError:
470
+ pass
471
+ if servers and servers[0].startswith("127.") and shutil.which("resolvectl"):
472
+ code, out = run_cmd(["resolvectl", "dns"], timeout=10.0)
473
+ upstream = []
474
+ for line in out.splitlines():
475
+ if info.interface and f"({info.interface})" in line:
476
+ upstream += re.findall(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b", line.split(":", 1)[-1])
477
+ if not upstream:
478
+ upstream = re.findall(r":\s*(\d{1,3}(?:\.\d{1,3}){3})", out)
479
+ if upstream:
480
+ servers = upstream
481
+ info.dns_servers = [s for s in servers if ":" not in s] or None
482
+ return info
483
+
484
+
485
+ def parse_route_get_default(text: str) -> dict:
486
+ out = {}
487
+ for key in ("gateway", "interface"):
488
+ m = re.search(rf"^\s*{key}:\s*(\S+)", text, re.MULTILINE)
489
+ if m:
490
+ out[key] = m.group(1)
491
+ return out
492
+
493
+
494
+ def parse_hardware_ports(text: str) -> dict:
495
+ """`networksetup -listallhardwareports` -> {device: port name}."""
496
+ mapping = {}
497
+ port = None
498
+ for line in text.splitlines():
499
+ line = line.strip()
500
+ if line.startswith("Hardware Port:"):
501
+ port = line.split(":", 1)[1].strip()
502
+ elif line.startswith("Device:") and port:
503
+ mapping[line.split(":", 1)[1].strip()] = port
504
+ return mapping
505
+
506
+
507
+ def detect_network_macos() -> NetworkInfo:
508
+ info = NetworkInfo(source="route get")
509
+ code, out = run_cmd(["route", "-n", "get", "default"], timeout=10.0)
510
+ parsed = parse_route_get_default(out)
511
+ info.gateway = parsed.get("gateway")
512
+ info.interface = parsed.get("interface")
513
+ if info.interface:
514
+ code, out = run_cmd(["networksetup", "-listallhardwareports"], timeout=10.0)
515
+ port = parse_hardware_ports(out).get(info.interface, "")
516
+ if "wi-fi" in port.lower() or "airport" in port.lower():
517
+ info.link_type = "wifi"
518
+ elif "ethernet" in port.lower() or "lan" in port.lower():
519
+ info.link_type = "ethernet"
520
+ elif port:
521
+ info.link_type = "other"
522
+ code, out = run_cmd(["scutil", "--dns"], timeout=10.0)
523
+ servers = re.findall(r"nameserver\[\d+\]\s*:\s*(\d{1,3}(?:\.\d{1,3}){3})", out)
524
+ info.dns_servers = list(dict.fromkeys(servers)) or None
525
+ return info
526
+
527
+
528
+ def local_ip_for(target: str) -> Optional[str]:
529
+ """Local address the OS would use to reach `target` (no packet is sent)."""
530
+ family = socket.AF_INET6 if ":" in target else socket.AF_INET
531
+ try:
532
+ with socket.socket(family, socket.SOCK_DGRAM) as s:
533
+ s.connect((target, 53))
534
+ return s.getsockname()[0]
535
+ except OSError:
536
+ return None
537
+
538
+
539
+ def detect_network(target: str) -> NetworkInfo:
540
+ try:
541
+ if IS_WINDOWS:
542
+ info = detect_network_windows()
543
+ elif IS_MACOS:
544
+ info = detect_network_macos()
545
+ else:
546
+ info = detect_network_linux(target)
547
+ except Exception as exc: # detection must never stop the collector
548
+ info = NetworkInfo(source=f"failed: {exc}")
549
+ if not info.local_ip:
550
+ info.local_ip = local_ip_for(target)
551
+ return info
552
+
553
+
554
+ # --------------------------------------------------------------------------- #
555
+ # DNS probe (raw UDP query, bypasses the operating-system cache)
556
+ # --------------------------------------------------------------------------- #
557
+
558
+ def build_dns_query(name: str, qid: int, qtype: int = 1) -> bytes:
559
+ header = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 0) # RD=1, 1 question
560
+ qname = b""
561
+ for label in name.strip(".").split("."):
562
+ raw = label.encode("idna") if label else b""
563
+ qname += struct.pack("B", len(raw)) + raw
564
+ return header + qname + b"\x00" + struct.pack(">HH", qtype, 1)
565
+
566
+
567
+ def parse_dns_response(data: bytes, qid: int) -> Optional[int]:
568
+ """Return the response code, or None if the datagram does not match."""
569
+ if len(data) < 12:
570
+ return None
571
+ rid, flags = struct.unpack(">HH", data[:4])
572
+ if rid != qid or not flags & 0x8000:
573
+ return None
574
+ return flags & 0x000F
575
+
576
+
577
+ def dns_query(server: str, name: str, timeout_s: float = 3.0) -> tuple[Optional[float], Optional[int], Optional[str]]:
578
+ """Time one UDP DNS query. Returns (milliseconds, rcode, error)."""
579
+ qid = random.randint(0, 0xFFFF)
580
+ packet = build_dns_query(name, qid)
581
+ family = socket.AF_INET6 if ":" in server else socket.AF_INET
582
+ try:
583
+ with socket.socket(family, socket.SOCK_DGRAM) as s:
584
+ s.settimeout(timeout_s)
585
+ start = time.perf_counter()
586
+ s.sendto(packet, (server, 53))
587
+ deadline = start + timeout_s
588
+ while True:
589
+ remaining = deadline - time.perf_counter()
590
+ if remaining <= 0:
591
+ return None, None, "timeout"
592
+ s.settimeout(remaining)
593
+ data, _ = s.recvfrom(4096)
594
+ elapsed = (time.perf_counter() - start) * 1000.0
595
+ rcode = parse_dns_response(data, qid)
596
+ if rcode is None:
597
+ continue
598
+ if rcode in (0, 3): # NOERROR / NXDOMAIN are valid answers
599
+ return round(elapsed, 3), rcode, None
600
+ return None, rcode, f"rcode {rcode}"
601
+ except socket.timeout:
602
+ return None, None, "timeout"
603
+ except OSError as exc:
604
+ return None, None, f"{exc.__class__.__name__}"
605
+
606
+
607
+ def random_label() -> str:
608
+ return "%012x" % random.getrandbits(48)
609
+
610
+
611
+ # --------------------------------------------------------------------------- #
612
+ # TCP connect and HTTP probes
613
+ # --------------------------------------------------------------------------- #
614
+
615
+ def tcp_connect_times(host: str, port: int, count: int = 5, timeout_s: float = 3.0,
616
+ gap_s: float = 0.2) -> tuple[list[float], Optional[str]]:
617
+ try:
618
+ addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
619
+ except (socket.gaierror, IndexError) as exc:
620
+ return [], f"resolve failed ({exc.__class__.__name__})"
621
+ family, _, _, _, sockaddr = addr
622
+ times: list[float] = []
623
+ error = None
624
+ for i in range(count):
625
+ s = socket.socket(family, socket.SOCK_STREAM)
626
+ s.settimeout(timeout_s)
627
+ try:
628
+ start = time.perf_counter()
629
+ s.connect(sockaddr)
630
+ times.append((time.perf_counter() - start) * 1000.0)
631
+ except socket.timeout:
632
+ error = "timeout"
633
+ except OSError as exc:
634
+ error = exc.__class__.__name__
635
+ finally:
636
+ try:
637
+ s.close()
638
+ except OSError:
639
+ pass
640
+ if i < count - 1:
641
+ time.sleep(gap_s)
642
+ return times, (error if not times else None)
643
+
644
+
645
+ def http_probe(url: str, timeout_s: float = 5.0) -> tuple[Optional[float], Optional[int], Optional[str]]:
646
+ """Time-to-first-response for a small URL, bypassing any system proxy."""
647
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
648
+ req = urllib.request.Request(url, headers={
649
+ "User-Agent": USER_AGENT, "Cache-Control": "no-cache", "Pragma": "no-cache",
650
+ })
651
+ start = time.perf_counter()
652
+ try:
653
+ with opener.open(req, timeout=timeout_s) as resp:
654
+ elapsed = (time.perf_counter() - start) * 1000.0
655
+ resp.read(4096)
656
+ return round(elapsed, 3), resp.status, None
657
+ except urllib.error.HTTPError as exc:
658
+ elapsed = (time.perf_counter() - start) * 1000.0
659
+ return round(elapsed, 3), exc.code, None
660
+ except (urllib.error.URLError, socket.timeout, OSError, ValueError) as exc:
661
+ reason = getattr(exc, "reason", exc)
662
+ return None, None, f"{reason}"[:80]
663
+
664
+
665
+ # --------------------------------------------------------------------------- #
666
+ # Wi-Fi link metrics
667
+ # --------------------------------------------------------------------------- #
668
+
669
+ @dataclass
670
+ class WifiInfo:
671
+ connected: bool = False
672
+ ssid: Optional[str] = None
673
+ signal_pct: Optional[int] = None
674
+ rssi_dbm: Optional[float] = None
675
+ rx_mbps: Optional[float] = None
676
+ tx_mbps: Optional[float] = None
677
+ channel: Optional[int] = None
678
+ band_ghz: Optional[float] = None
679
+ phy: Optional[str] = None
680
+
681
+
682
+ def rssi_from_quality(pct: int) -> float:
683
+ """Windows WLAN mapping: quality 0 -> -100 dBm, 100 -> -50 dBm (linear)."""
684
+ return round(pct / 2.0 - 100.0, 1)
685
+
686
+
687
+ def quality_from_rssi(rssi: float) -> int:
688
+ return int(max(0, min(100, round((rssi + 100.0) * 2.0))))
689
+
690
+
691
+ def channel_from_freq_mhz(freq: int) -> tuple[Optional[int], Optional[float]]:
692
+ if 2412 <= freq <= 2472:
693
+ return (freq - 2407) // 5, 2.4
694
+ if freq == 2484:
695
+ return 14, 2.4
696
+ if 5000 <= freq <= 5900:
697
+ return (freq - 5000) // 5, 5.0
698
+ if 5925 <= freq <= 7125:
699
+ return (freq - 5950) // 5, 6.0
700
+ if 57000 <= freq <= 71000:
701
+ return None, 60.0
702
+ return None, None
703
+
704
+
705
+ def band_from_channel(channel: int) -> Optional[float]:
706
+ if 1 <= channel <= 14:
707
+ return 2.4
708
+ if 32 <= channel <= 177:
709
+ return 5.0
710
+ return None
711
+
712
+
713
+ _NETSH_KV_RE = re.compile(r"^\s*([^:]+?)\s*:\s*(.*?)\s*$")
714
+ _PCT_RE = re.compile(r"^(\d{1,3})\s*%$")
715
+ _INT_RE = re.compile(r"^\d{1,3}$")
716
+ _GHZ_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*GHz$", re.IGNORECASE)
717
+ _PHY_RE = re.compile(r"^802\.11[a-z]{1,2}$", re.IGNORECASE)
718
+ _MBPS_KEY_RE = re.compile(r"\(\s*Mbps\s*\)", re.IGNORECASE)
719
+
720
+
721
+ def parse_netsh_wlan(text: str) -> WifiInfo:
722
+ """Parse `netsh wlan show interfaces` output without relying on localized labels.
723
+
724
+ Only the SSID/BSSID keys are language independent; every other field is
725
+ recognised by the shape of its value (a percentage, "(Mbps)" in the key,
726
+ "802.11xx", "x GHz", a bare channel number).
727
+ """
728
+ blocks: list[list[tuple[str, str]]] = [[]]
729
+ for line in text.splitlines():
730
+ if not line.strip():
731
+ if blocks[-1]:
732
+ blocks.append([])
733
+ continue
734
+ m = _NETSH_KV_RE.match(line)
735
+ if m:
736
+ blocks[-1].append((m.group(1), m.group(2)))
737
+ info = WifiInfo()
738
+ for block in blocks:
739
+ kv = dict(block)
740
+ ssid = kv.get("SSID")
741
+ if not ssid or not any(_PCT_RE.match(v) for _, v in block):
742
+ continue
743
+ info.connected = True
744
+ info.ssid = ssid
745
+ rates: list[tuple[str, float]] = []
746
+ for key, value in block:
747
+ if key in ("SSID", "BSSID"):
748
+ continue
749
+ if info.signal_pct is None and _PCT_RE.match(value):
750
+ info.signal_pct = int(_PCT_RE.match(value).group(1))
751
+ elif _MBPS_KEY_RE.search(key):
752
+ try:
753
+ rates.append((key.lower(), float(value.replace(",", "."))))
754
+ except ValueError:
755
+ pass
756
+ elif info.phy is None and _PHY_RE.match(value):
757
+ info.phy = value.lower()
758
+ elif info.band_ghz is None and _GHZ_RE.match(value):
759
+ info.band_ghz = float(_GHZ_RE.match(value).group(1))
760
+ elif info.channel is None and _INT_RE.match(value):
761
+ info.channel = int(value)
762
+ for key, rate in rates:
763
+ if "transmit" in key or "tx" in key.split():
764
+ info.tx_mbps = rate
765
+ elif "receive" in key or "rx" in key.split():
766
+ info.rx_mbps = rate
767
+ if info.rx_mbps is None and rates:
768
+ info.rx_mbps = rates[0][1]
769
+ if info.tx_mbps is None and len(rates) > 1:
770
+ info.tx_mbps = rates[1][1]
771
+ if info.signal_pct is not None:
772
+ info.rssi_dbm = rssi_from_quality(info.signal_pct)
773
+ if info.band_ghz is None and info.channel is not None:
774
+ info.band_ghz = band_from_channel(info.channel)
775
+ break
776
+ return info
777
+
778
+
779
+ def wifi_info_windows() -> WifiInfo:
780
+ code, out = run_cmd(["netsh", "wlan", "show", "interfaces"], timeout=15.0)
781
+ return parse_netsh_wlan(out) if out else WifiInfo()
782
+
783
+
784
+ _IW_PHY = (("EHT", "802.11be"), ("HE", "802.11ax"), ("VHT", "802.11ac"), ("HT", "802.11n"))
785
+
786
+
787
+ def parse_iw_link(text: str) -> WifiInfo:
788
+ info = WifiInfo()
789
+ if "Not connected" in text or "SSID:" not in text:
790
+ return info
791
+ info.connected = True
792
+ m = re.search(r"^\s*SSID:\s*(.+?)\s*$", text, re.MULTILINE)
793
+ info.ssid = m.group(1) if m else None
794
+ m = re.search(r"^\s*freq:\s*(\d+)", text, re.MULTILINE)
795
+ if m:
796
+ info.channel, info.band_ghz = channel_from_freq_mhz(int(m.group(1)))
797
+ m = re.search(r"^\s*signal:\s*(-?\d+(?:\.\d+)?)\s*dBm", text, re.MULTILINE)
798
+ if m:
799
+ info.rssi_dbm = float(m.group(1))
800
+ info.signal_pct = quality_from_rssi(info.rssi_dbm)
801
+ for key, attr in (("rx bitrate", "rx_mbps"), ("tx bitrate", "tx_mbps")):
802
+ m = re.search(rf"^\s*{key}:\s*(\d+(?:\.\d+)?)\s*MBit/s(.*)$", text, re.MULTILINE | re.IGNORECASE)
803
+ if m:
804
+ setattr(info, attr, float(m.group(1)))
805
+ if info.phy is None:
806
+ rest = m.group(2).upper()
807
+ for token, phy in _IW_PHY:
808
+ if re.search(rf"\b{token}-", rest):
809
+ info.phy = phy
810
+ break
811
+ if info.phy is None and re.search(r"\bMCS\b", rest):
812
+ info.phy = "802.11n" # HT rates are printed as bare "MCS n"
813
+ return info
814
+
815
+
816
+ def parse_proc_net_wireless(text: str, iface: str) -> WifiInfo:
817
+ info = WifiInfo()
818
+ for line in text.splitlines():
819
+ if line.strip().startswith(iface + ":"):
820
+ parts = line.split()
821
+ try:
822
+ level = float(parts[3].rstrip("."))
823
+ except (IndexError, ValueError):
824
+ break
825
+ info.connected = True
826
+ info.rssi_dbm = level
827
+ info.signal_pct = quality_from_rssi(level)
828
+ break
829
+ return info
830
+
831
+
832
+ def wifi_info_linux(iface: Optional[str]) -> WifiInfo:
833
+ if not iface or not _linux_is_wireless(iface):
834
+ return WifiInfo()
835
+ if shutil.which("iw"):
836
+ code, out = run_cmd(["iw", "dev", iface, "link"], timeout=10.0)
837
+ if code == 0 and out:
838
+ return parse_iw_link(out)
839
+ try:
840
+ return parse_proc_net_wireless(Path("/proc/net/wireless").read_text(), iface)
841
+ except OSError:
842
+ return WifiInfo()
843
+
844
+
845
+ def parse_system_profiler_airport(data: dict) -> WifiInfo:
846
+ info = WifiInfo()
847
+ try:
848
+ interfaces = data["SPAirPortDataType"][0]["spairport_airport_interfaces"]
849
+ except (KeyError, IndexError, TypeError):
850
+ return info
851
+ for entry in interfaces:
852
+ net = entry.get("spairport_current_network_information")
853
+ if not isinstance(net, dict):
854
+ continue
855
+ info.connected = True
856
+ info.ssid = net.get("_name")
857
+ m = re.search(r"(-?\d+)\s*dBm", str(net.get("spairport_signal_noise", "")))
858
+ if m:
859
+ info.rssi_dbm = float(m.group(1))
860
+ info.signal_pct = quality_from_rssi(info.rssi_dbm)
861
+ m = re.search(r"(\d+)\s*\((\d+(?:\.\d+)?)\s*GHz", str(net.get("spairport_network_channel", "")))
862
+ if m:
863
+ info.channel = int(m.group(1))
864
+ info.band_ghz = float(m.group(2))
865
+ phy = str(net.get("spairport_network_phymode", "")).lower()
866
+ info.phy = phy if phy.startswith("802.11") else None
867
+ rate = net.get("spairport_network_rate")
868
+ try:
869
+ info.rx_mbps = float(rate) if rate is not None else None
870
+ info.tx_mbps = info.rx_mbps
871
+ except (TypeError, ValueError):
872
+ pass
873
+ break
874
+ return info
875
+
876
+
877
+ def wifi_info_macos() -> WifiInfo:
878
+ code, out = run_cmd(["system_profiler", "SPAirPortDataType", "-json"], timeout=25.0)
879
+ if code != 0 or not out:
880
+ return WifiInfo()
881
+ try:
882
+ return parse_system_profiler_airport(json.loads(out))
883
+ except ValueError:
884
+ return WifiInfo()
885
+
886
+
887
+ def wifi_info(net: NetworkInfo) -> WifiInfo:
888
+ try:
889
+ if IS_WINDOWS:
890
+ return wifi_info_windows()
891
+ if IS_MACOS:
892
+ return wifi_info_macos()
893
+ return wifi_info_linux(net.interface)
894
+ except Exception:
895
+ return WifiInfo()
896
+
897
+
898
+ # --------------------------------------------------------------------------- #
899
+ # Throughput tests (slow cadence)
900
+ # --------------------------------------------------------------------------- #
901
+
902
+ def _ookla_cli_path() -> Optional[str]:
903
+ """Path of the official Ookla CLI, distinguishing it from speedtest-cli."""
904
+ exe = shutil.which("speedtest")
905
+ if not exe:
906
+ return None
907
+ code, out = run_cmd([exe, "--version"], timeout=15.0)
908
+ return exe if "ookla" in out.lower() else None
909
+
910
+
911
+ def parse_ookla_json(data: dict) -> dict:
912
+ result = {}
913
+ down = data.get("download") or {}
914
+ up = data.get("upload") or {}
915
+ if "bandwidth" in down:
916
+ result["download_mbps"] = round(down["bandwidth"] * 8 / 1e6, 2)
917
+ if "bandwidth" in up:
918
+ result["upload_mbps"] = round(up["bandwidth"] * 8 / 1e6, 2)
919
+ ping_info = data.get("ping") or {}
920
+ if ping_info.get("latency") is not None:
921
+ result["speedtest_ping_ms"] = round(float(ping_info["latency"]), 3)
922
+ for key, col in (("download", "download_loaded_latency_ms"),
923
+ ("upload", "upload_loaded_latency_ms")):
924
+ lat = (data.get(key) or {}).get("latency") or {}
925
+ if lat.get("iqm") is not None:
926
+ result[col] = round(float(lat["iqm"]), 3)
927
+ server = data.get("server") or {}
928
+ if server.get("id") is not None:
929
+ result["speedtest_server_id"] = int(server["id"])
930
+ name = ", ".join(str(server[k]) for k in ("name", "location") if server.get(k))
931
+ if name:
932
+ result["speedtest_server"] = name
933
+ return result
934
+
935
+
936
+ def run_speedtest(server_id: Optional[int] = None, timeout_s: float = 180.0) -> dict:
937
+ exe = _ookla_cli_path()
938
+ if exe:
939
+ cmd = [exe, "--accept-license", "--accept-gdpr", "--format=json", "--progress=no"]
940
+ if server_id:
941
+ cmd += ["--server-id", str(server_id)]
942
+ code, out = run_cmd(cmd, timeout=timeout_s, encoding="utf-8")
943
+ for line in out.splitlines():
944
+ line = line.strip()
945
+ if line.startswith("{"):
946
+ try:
947
+ data = json.loads(line)
948
+ except ValueError:
949
+ continue
950
+ if data.get("type") == "result":
951
+ return parse_ookla_json(data)
952
+ return {"error": "speedtest (ookla) failed: " + (out.strip().splitlines() or ["no output"])[-1][:80]}
953
+ try:
954
+ import speedtest # type: ignore
955
+ except ImportError:
956
+ return {"error": "no speedtest tool (install the Ookla CLI or `pip install speedtest-cli`)"}
957
+ try:
958
+ st = speedtest.Speedtest(secure=True)
959
+ if server_id:
960
+ st.get_servers([server_id])
961
+ st.get_best_server()
962
+ down = st.download() / 1e6
963
+ up = st.upload(pre_allocate=False) / 1e6
964
+ res = st.results
965
+ out = {"download_mbps": round(down, 2), "upload_mbps": round(up, 2)}
966
+ if res.ping is not None and float(res.ping) < SPEEDTEST_PING_FAILED_MS:
967
+ out["speedtest_ping_ms"] = round(float(res.ping), 3)
968
+ elif res.ping is not None:
969
+ out["error"] = "speedtest-cli: server latency probe failed"
970
+ server = res.server or {}
971
+ if server.get("id"):
972
+ out["speedtest_server_id"] = int(server["id"])
973
+ name = ", ".join(str(server[k]) for k in ("sponsor", "name") if server.get(k))
974
+ if name:
975
+ out["speedtest_server"] = name
976
+ return out
977
+ except Exception as exc:
978
+ return {"error": f"speedtest-cli failed: {exc}"[:120]}
979
+
980
+
981
+ def run_iperf3(server: str, port: int, duration_s: int, reverse: bool) -> dict:
982
+ if not shutil.which("iperf3"):
983
+ return {"error": "iperf3 not found"}
984
+ cmd = ["iperf3", "-c", server, "-p", str(port), "-t", str(duration_s), "-J"]
985
+ if reverse:
986
+ cmd.append("-R")
987
+ code, out = run_cmd(cmd, timeout=duration_s + 30, encoding="utf-8")
988
+ try:
989
+ data = json.loads(out)
990
+ except ValueError:
991
+ return {"error": "iperf3 failed: " + (out.strip().splitlines() or ["no output"])[-1][:80]}
992
+ if data.get("error"):
993
+ return {"error": f"iperf3 failed: {data['error']}"[:120]}
994
+ try:
995
+ end = data["end"]
996
+ received = end.get("sum_received") or end.get("sum") or {}
997
+ result = {"lan_throughput_mbps": round(received["bits_per_second"] / 1e6, 2)}
998
+ sent = end.get("sum_sent") or {}
999
+ if sent.get("retransmits") is not None:
1000
+ result["lan_retransmits"] = int(sent["retransmits"])
1001
+ return result
1002
+ except (KeyError, TypeError):
1003
+ return {"error": "iperf3 failed: unexpected JSON"}
1004
+
1005
+
1006
+ # --------------------------------------------------------------------------- #
1007
+ # Keep the machine awake while collecting
1008
+ # --------------------------------------------------------------------------- #
1009
+
1010
+ class KeepAwake:
1011
+ """System sleep inhibitor (display may still turn off)."""
1012
+
1013
+ ES_CONTINUOUS = 0x80000000
1014
+ ES_SYSTEM_REQUIRED = 0x00000001
1015
+
1016
+ def __init__(self) -> None:
1017
+ self.proc: Optional[subprocess.Popen] = None
1018
+ self.active = False
1019
+
1020
+ def __enter__(self) -> "KeepAwake":
1021
+ try:
1022
+ if IS_WINDOWS:
1023
+ import ctypes
1024
+ ok = ctypes.windll.kernel32.SetThreadExecutionState( # type: ignore[attr-defined]
1025
+ self.ES_CONTINUOUS | self.ES_SYSTEM_REQUIRED)
1026
+ self.active = bool(ok)
1027
+ elif IS_MACOS and shutil.which("caffeinate"):
1028
+ self.proc = subprocess.Popen(["caffeinate", "-i", "-w", str(os.getpid())])
1029
+ self.active = True
1030
+ elif IS_LINUX and shutil.which("systemd-inhibit"):
1031
+ self.proc = subprocess.Popen(
1032
+ ["systemd-inhibit", "--what=sleep:idle", "--who=LocalNet-Dynamics",
1033
+ "--why=telemetry collection in progress", "--mode=block",
1034
+ "sleep", "infinity"],
1035
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1036
+ self.active = True
1037
+ except Exception:
1038
+ self.active = False
1039
+ return self
1040
+
1041
+ def __exit__(self, *exc) -> None:
1042
+ try:
1043
+ if IS_WINDOWS:
1044
+ import ctypes
1045
+ ctypes.windll.kernel32.SetThreadExecutionState(self.ES_CONTINUOUS) # type: ignore[attr-defined]
1046
+ if self.proc:
1047
+ self.proc.terminate()
1048
+ except Exception:
1049
+ pass
1050
+
1051
+
1052
+ # --------------------------------------------------------------------------- #
1053
+ # One sample
1054
+ # --------------------------------------------------------------------------- #
1055
+
1056
+ def now_timestamps() -> tuple[str, str, int]:
1057
+ utc = datetime.now(timezone.utc)
1058
+ local = utc.astimezone()
1059
+ return (utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
1060
+ local.isoformat(timespec="seconds"),
1061
+ int(utc.timestamp()))
1062
+
1063
+
1064
+ def collect_sample(cfg: argparse.Namespace, net: NetworkInfo, dns_server: Optional[str],
1065
+ pool: ThreadPoolExecutor, run_speed: bool, run_lan: bool) -> Sample:
1066
+ s = Sample(run_id=cfg.run_id, host_label=cfg.host_label, target=cfg.target,
1067
+ link_type=net.link_type, gateway_ip=net.gateway or "",
1068
+ dns_server=dns_server or "")
1069
+ s.timestamp_utc, s.timestamp_local, s.epoch_s = now_timestamps()
1070
+ t0 = time.perf_counter()
1071
+ notes: list[str] = []
1072
+
1073
+ futures = {
1074
+ "ping": pool.submit(ping, cfg.target, cfg.ping_count, cfg.ping_timeout),
1075
+ }
1076
+ if net.gateway:
1077
+ futures["gw"] = pool.submit(ping, net.gateway, cfg.gateway_ping_count, cfg.ping_timeout)
1078
+ if cfg.tcp_port:
1079
+ futures["tcp"] = pool.submit(tcp_connect_times, cfg.target, cfg.tcp_port,
1080
+ cfg.tcp_count, cfg.ping_timeout)
1081
+ if dns_server:
1082
+ futures["dns"] = pool.submit(dns_query, dns_server, cfg.dns_host, cfg.dns_timeout)
1083
+ futures["dnsr"] = pool.submit(dns_query, dns_server,
1084
+ f"{random_label()}.{cfg.dns_host}", cfg.dns_timeout)
1085
+ if cfg.http_url:
1086
+ futures["http"] = pool.submit(http_probe, cfg.http_url, cfg.http_timeout)
1087
+ if cfg.wifi and net.link_type in ("wifi", "unknown"):
1088
+ futures["wifi"] = pool.submit(wifi_info, net)
1089
+
1090
+ p: PingResult = futures["ping"].result()
1091
+ st = rtt_stats(p.rtts or [])
1092
+ s.rtt_min_ms, s.rtt_avg_ms, s.rtt_median_ms = st["min"], st["avg"], st["median"]
1093
+ s.rtt_max_ms, s.rtt_stddev_ms, s.jitter_ms = st["max"], st["stddev"], st["jitter"]
1094
+ s.packets_sent, s.packets_received = p.sent, p.received
1095
+ s.packet_loss_pct = p.loss_pct
1096
+ if p.error:
1097
+ notes.append(f"ping: {p.error}")
1098
+
1099
+ if "gw" in futures:
1100
+ g: PingResult = futures["gw"].result()
1101
+ gst = rtt_stats(g.rtts or [])
1102
+ s.gateway_rtt_min_ms, s.gateway_rtt_avg_ms = gst["min"], gst["avg"]
1103
+ s.gateway_rtt_max_ms, s.gateway_jitter_ms = gst["max"], gst["jitter"]
1104
+ s.gateway_packet_loss_pct = g.loss_pct
1105
+ if g.error:
1106
+ notes.append(f"gateway ping: {g.error}")
1107
+
1108
+ if "tcp" in futures:
1109
+ times, err = futures["tcp"].result()
1110
+ if times:
1111
+ s.tcp_connect_min_ms = round(min(times), 3)
1112
+ s.tcp_connect_median_ms = round(statistics.median(times), 3)
1113
+ if err:
1114
+ notes.append(f"tcp: {err}")
1115
+
1116
+ if "dns" in futures:
1117
+ ms, rcode, err = futures["dns"].result()
1118
+ s.dns_resolve_ms = ms
1119
+ if err:
1120
+ notes.append(f"dns: {err}")
1121
+ ms, rcode, err = futures["dnsr"].result()
1122
+ s.dns_recursive_ms = ms
1123
+ if err:
1124
+ notes.append(f"dns recursive: {err}")
1125
+
1126
+ if "http" in futures:
1127
+ ms, status, err = futures["http"].result()
1128
+ s.http_ms, s.http_status = ms, status
1129
+ if err:
1130
+ notes.append(f"http: {err}")
1131
+
1132
+ if "wifi" in futures:
1133
+ w: WifiInfo = futures["wifi"].result()
1134
+ if w.connected:
1135
+ s.wifi_ssid = w.ssid if (cfg.record_ssid and w.ssid) else ""
1136
+ s.wifi_signal_pct, s.wifi_rssi_dbm = w.signal_pct, w.rssi_dbm
1137
+ s.wifi_rx_mbps, s.wifi_tx_mbps = w.rx_mbps, w.tx_mbps
1138
+ s.wifi_channel, s.wifi_band_ghz = w.channel, w.band_ghz
1139
+ s.wifi_phy = w.phy or ""
1140
+
1141
+ # Heavy tests run after the latency probes so they cannot bias them.
1142
+ if run_speed:
1143
+ r = run_speedtest(cfg.speedtest_server)
1144
+ for key, value in r.items():
1145
+ if key != "error":
1146
+ setattr(s, key, value)
1147
+ if r.get("error"):
1148
+ notes.append(r["error"])
1149
+ if run_lan:
1150
+ r = run_iperf3(cfg.iperf_server, cfg.iperf_port, cfg.iperf_duration, cfg.iperf_reverse)
1151
+ for key, value in r.items():
1152
+ if key != "error":
1153
+ setattr(s, key, value)
1154
+ if r.get("error"):
1155
+ notes.append(r["error"])
1156
+
1157
+ s.sample_duration_s = round(time.perf_counter() - t0, 2)
1158
+ s.notes = "; ".join(notes)
1159
+ return s
1160
+
1161
+
1162
+ # --------------------------------------------------------------------------- #
1163
+ # Summary statistics and run metadata
1164
+ # --------------------------------------------------------------------------- #
1165
+
1166
+ def column_stats(values: list) -> Optional[dict]:
1167
+ vals = [float(v) for v in values if v is not None and v != ""]
1168
+ if not vals:
1169
+ return None
1170
+ vals_sorted = sorted(vals)
1171
+ p95 = vals_sorted[min(len(vals_sorted) - 1, int(0.95 * len(vals_sorted)))]
1172
+ return {
1173
+ "count": len(vals),
1174
+ "mean": round(statistics.mean(vals), 3),
1175
+ "median": round(statistics.median(vals), 3),
1176
+ "min": round(vals_sorted[0], 3),
1177
+ "max": round(vals_sorted[-1], 3),
1178
+ "p95": round(p95, 3),
1179
+ "stddev": round(statistics.pstdev(vals), 3) if len(vals) > 1 else 0.0,
1180
+ }
1181
+
1182
+
1183
+ class RunningSummary:
1184
+ """Keeps per-column value lists so the JSON summary can be refreshed cheaply."""
1185
+
1186
+ def __init__(self) -> None:
1187
+ self.values: dict[str, list] = {k: [] for k in SUMMARY_KEYS}
1188
+ self.count = 0
1189
+ self.first_utc = ""
1190
+ self.last_utc = ""
1191
+ self.link_types: dict[str, int] = {}
1192
+
1193
+ def add(self, s: Sample) -> None:
1194
+ self.count += 1
1195
+ self.first_utc = self.first_utc or s.timestamp_utc
1196
+ self.last_utc = s.timestamp_utc
1197
+ self.link_types[s.link_type] = self.link_types.get(s.link_type, 0) + 1
1198
+ for k in SUMMARY_KEYS:
1199
+ v = getattr(s, k)
1200
+ if v is not None:
1201
+ self.values[k].append(v)
1202
+
1203
+ def summary(self) -> dict:
1204
+ out = {k: column_stats(v) for k, v in self.values.items()}
1205
+ return {k: v for k, v in out.items() if v is not None}
1206
+
1207
+
1208
+ def timezone_name() -> str:
1209
+ local = datetime.now(timezone.utc).astimezone()
1210
+ return local.tzname() or ""
1211
+
1212
+
1213
+ def write_meta(path: Path, cfg: argparse.Namespace, net: NetworkInfo, dns_server: Optional[str],
1214
+ summary: RunningSummary, status: str, started_utc: str,
1215
+ elapsed_s: float, csv_name: str) -> None:
1216
+ local = datetime.now(timezone.utc).astimezone()
1217
+ payload = {
1218
+ "run_id": cfg.run_id,
1219
+ "host_label": cfg.host_label,
1220
+ "collector_version": COLLECTOR_VERSION,
1221
+ "status": status,
1222
+ "started_utc": started_utc,
1223
+ "updated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
1224
+ "planned_duration_s": cfg.duration,
1225
+ "elapsed_s": round(elapsed_s, 1),
1226
+ "interval_s": cfg.interval,
1227
+ "sample_count": summary.count,
1228
+ "first_sample_utc": summary.first_utc,
1229
+ "last_sample_utc": summary.last_utc,
1230
+ "csv_file": csv_name,
1231
+ "config": {
1232
+ "target": cfg.target,
1233
+ "ping_count": cfg.ping_count,
1234
+ "gateway_ping_count": cfg.gateway_ping_count,
1235
+ "ping_timeout_s": cfg.ping_timeout,
1236
+ "tcp_port": cfg.tcp_port,
1237
+ "tcp_count": cfg.tcp_count,
1238
+ "dns_host": cfg.dns_host,
1239
+ "dns_server": dns_server,
1240
+ "dns_timeout_s": cfg.dns_timeout,
1241
+ "http_url": cfg.http_url,
1242
+ "http_timeout_s": cfg.http_timeout,
1243
+ "wifi": cfg.wifi,
1244
+ "record_ssid": cfg.record_ssid,
1245
+ "speedtest": cfg.speedtest,
1246
+ "speedtest_every_s": cfg.speedtest_every if cfg.speedtest else None,
1247
+ "speedtest_server_id": cfg.speedtest_server,
1248
+ "iperf_server": cfg.iperf_server,
1249
+ "iperf_port": cfg.iperf_port,
1250
+ "iperf_every_s": cfg.iperf_every if cfg.iperf_server else None,
1251
+ "iperf_duration_s": cfg.iperf_duration,
1252
+ "iperf_reverse": cfg.iperf_reverse,
1253
+ },
1254
+ "environment": {
1255
+ "os": platform.platform(),
1256
+ "python": platform.python_version(),
1257
+ "machine": platform.machine(),
1258
+ "timezone": timezone_name(),
1259
+ "utc_offset_s": int(local.utcoffset().total_seconds()) if local.utcoffset() else 0,
1260
+ "ping_resolution_ms": 1.0 if IS_WINDOWS else 0.001,
1261
+ },
1262
+ "network": {
1263
+ "gateway_ip": net.gateway,
1264
+ "interface": net.interface,
1265
+ "local_ip": net.local_ip,
1266
+ "link_type": net.link_type,
1267
+ "link_types_seen": summary.link_types,
1268
+ "detection_source": net.source,
1269
+ },
1270
+ "summary": summary.summary(),
1271
+ }
1272
+ tmp = path.with_suffix(".json.tmp")
1273
+ tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
1274
+ os.replace(tmp, path)
1275
+
1276
+
1277
+ def print_summary(summary: RunningSummary, elapsed: float) -> None:
1278
+ stats = summary.summary()
1279
+ print()
1280
+ print("=" * 72)
1281
+ print(f" SUMMARY: {summary.count} samples over {human_duration(elapsed)}")
1282
+ print("=" * 72)
1283
+ header = f"{'metric':<28}{'n':>7}{'median':>10}{'mean':>10}{'p95':>10}{'max':>10}"
1284
+ print(header)
1285
+ print("-" * len(header))
1286
+ for key in SUMMARY_KEYS:
1287
+ st = stats.get(key)
1288
+ if not st:
1289
+ continue
1290
+ print(f"{key:<28}{st['count']:>7}{st['median']:>10}{st['mean']:>10}"
1291
+ f"{st['p95']:>10}{st['max']:>10}")
1292
+ print("=" * 72)
1293
+
1294
+
1295
+ def format_progress(s: Sample) -> str:
1296
+ def f(v, suffix="", nd=1):
1297
+ return "-" if v is None else f"{v:.{nd}f}{suffix}"
1298
+ parts = [
1299
+ f"[{s.sample_index + 1:>5}] {s.timestamp_utc}",
1300
+ f"rtt={f(s.rtt_avg_ms, 'ms')}",
1301
+ f"jit={f(s.jitter_ms, 'ms')}",
1302
+ f"loss={f(s.packet_loss_pct, '%', 0)}",
1303
+ f"gw={f(s.gateway_rtt_avg_ms, 'ms')}",
1304
+ f"tcp={f(s.tcp_connect_median_ms, 'ms')}",
1305
+ f"dns={f(s.dns_resolve_ms, '', 0)}/{f(s.dns_recursive_ms, 'ms', 0)}",
1306
+ f"http={f(s.http_ms, 'ms', 0)}",
1307
+ ]
1308
+ if s.wifi_signal_pct is not None:
1309
+ parts.append(f"wifi={s.wifi_signal_pct}%/{f(s.wifi_rx_mbps, 'Mbps', 0)}")
1310
+ if s.download_mbps is not None:
1311
+ parts.append(f"down={f(s.download_mbps, '', 1)} up={f(s.upload_mbps, 'Mbps', 1)}")
1312
+ if s.lan_throughput_mbps is not None:
1313
+ parts.append(f"lan={f(s.lan_throughput_mbps, 'Mbps', 0)}")
1314
+ if s.notes:
1315
+ parts.append(f"! {s.notes}")
1316
+ return " ".join(parts)
1317
+
1318
+
1319
+ # --------------------------------------------------------------------------- #
1320
+ # CLI
1321
+ # --------------------------------------------------------------------------- #
1322
+
1323
+ def build_parser() -> argparse.ArgumentParser:
1324
+ p = argparse.ArgumentParser(
1325
+ description="LocalNet-Dynamics: continuous network telemetry collector.",
1326
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1327
+ )
1328
+ default_out = Path(__file__).resolve().parent.parent / "dataset" / "raw"
1329
+
1330
+ g = p.add_argument_group("schedule")
1331
+ g.add_argument("--duration", type=parse_duration, default="24h",
1332
+ help="total run time (e.g. 6h, 7d, 30d)")
1333
+ g.add_argument("--interval", type=parse_duration, default="30s",
1334
+ help="time between sample starts (e.g. 30s, 1m, 5m)")
1335
+
1336
+ g = p.add_argument_group("latency probes")
1337
+ g.add_argument("--target", default="8.8.8.8",
1338
+ help="reference host for ICMP and TCP probes")
1339
+ g.add_argument("--ping-count", type=int, default=10,
1340
+ help="ICMP echo requests per sample (sent 1 s apart)")
1341
+ g.add_argument("--gateway-ping-count", type=int, default=5,
1342
+ help="ICMP echo requests to the default gateway per sample")
1343
+ g.add_argument("--ping-timeout", type=float, default=2.0,
1344
+ help="seconds to wait for each ICMP reply / TCP connect")
1345
+ g.add_argument("--tcp-port", type=int, default=443,
1346
+ help="TCP port on the target for connect-time probes (0 disables)")
1347
+ g.add_argument("--tcp-count", type=int, default=5,
1348
+ help="TCP connections per sample")
1349
+ g.add_argument("--dns-host", default="example.com",
1350
+ help="name queried for DNS timing; the recursive probe queries a "
1351
+ "random subdomain of it")
1352
+ g.add_argument("--dns-server", default=None,
1353
+ help="resolver IP to query (default: the system resolver of the "
1354
+ "default-route interface, then the gateway)")
1355
+ g.add_argument("--dns-timeout", type=float, default=3.0, help="DNS query timeout (s)")
1356
+ g.add_argument("--http-url", default="http://www.msftconnecttest.com/connecttest.txt",
1357
+ help="small URL for the HTTP time-to-first-response probe "
1358
+ "('' disables)")
1359
+ g.add_argument("--http-timeout", type=float, default=5.0, help="HTTP probe timeout (s)")
1360
+
1361
+ g = p.add_argument_group("wireless")
1362
+ g.add_argument("--no-wifi", dest="wifi", action="store_false",
1363
+ help="do not query Wi-Fi link metrics")
1364
+ g.add_argument("--record-ssid", action="store_true",
1365
+ help="store the Wi-Fi network name in the dataset (off by default "
1366
+ "because it can identify the collection site)")
1367
+
1368
+ g = p.add_argument_group("throughput tests")
1369
+ g.add_argument("--speedtest", action="store_true",
1370
+ help="run a WAN speed test periodically (Ookla CLI or speedtest-cli)")
1371
+ g.add_argument("--speedtest-every", type=parse_duration, default="30m",
1372
+ help="interval between WAN speed tests")
1373
+ g.add_argument("--speedtest-server", type=int, default=None,
1374
+ help="Ookla server id to pin (recommended for consistency)")
1375
+ g.add_argument("--iperf-server", default=None,
1376
+ help="address of an `iperf3 -s` host on the LAN")
1377
+ g.add_argument("--iperf-port", type=int, default=5201, help="iperf3 server port")
1378
+ g.add_argument("--iperf-every", type=parse_duration, default="30m",
1379
+ help="interval between LAN throughput tests")
1380
+ g.add_argument("--iperf-duration", type=int, default=10, help="seconds per iperf3 test")
1381
+ g.add_argument("--iperf-reverse", action="store_true",
1382
+ help="measure server-to-client (download) direction instead")
1383
+
1384
+ g = p.add_argument_group("output")
1385
+ g.add_argument("--output-dir", default=str(default_out),
1386
+ help="directory for the run's CSV and JSON files")
1387
+ g.add_argument("--run-id", default=None,
1388
+ help="run identifier and file stem (default: <label_>YYYYMMDD_HHMMSS)")
1389
+ g.add_argument("--host-label", default="",
1390
+ help="free-text label for this vantage point, e.g. desktop-eth or "
1391
+ "laptop-wifi (stored in every row)")
1392
+ g.add_argument("--no-keep-awake", dest="keep_awake", action="store_false",
1393
+ help="do not inhibit system sleep while collecting")
1394
+ g.add_argument("--quiet", action="store_true", help="print only the summary")
1395
+ g.add_argument("--check", action="store_true",
1396
+ help="detect the environment, take one sample, print it as JSON "
1397
+ "and exit without writing files")
1398
+ return p
1399
+
1400
+
1401
+ def resolve_dns_server(cfg: argparse.Namespace, net: NetworkInfo) -> Optional[str]:
1402
+ if cfg.dns_server:
1403
+ return cfg.dns_server
1404
+ if net.dns_servers:
1405
+ return net.dns_servers[0]
1406
+ return net.gateway
1407
+
1408
+
1409
+ def sanitize_label(text: str) -> str:
1410
+ return re.sub(r"[^A-Za-z0-9_-]+", "-", text.strip()).strip("-")
1411
+
1412
+
1413
+ def install_sigterm_handler() -> None:
1414
+ def handler(signum, frame):
1415
+ raise KeyboardInterrupt
1416
+ try:
1417
+ signal.signal(signal.SIGTERM, handler)
1418
+ except (ValueError, OSError, AttributeError):
1419
+ pass
1420
+
1421
+
1422
+ def main(argv: Optional[list[str]] = None) -> int:
1423
+ for stream in (sys.stdout, sys.stderr): # never crash on an unprintable path
1424
+ try:
1425
+ stream.reconfigure(errors="replace")
1426
+ except (AttributeError, ValueError):
1427
+ pass
1428
+ cfg = build_parser().parse_args(argv)
1429
+ cfg.duration = float(cfg.duration)
1430
+ cfg.interval = float(cfg.interval)
1431
+ cfg.speedtest_every = float(cfg.speedtest_every)
1432
+ cfg.iperf_every = float(cfg.iperf_every)
1433
+ cfg.host_label = sanitize_label(cfg.host_label)
1434
+ if cfg.interval <= 0:
1435
+ print("error: --interval must be positive", file=sys.stderr)
1436
+ return 2
1437
+ if cfg.ping_count < 1 or cfg.gateway_ping_count < 1:
1438
+ print("error: ping counts must be at least 1", file=sys.stderr)
1439
+ return 2
1440
+ stamp = f"{datetime.now():%Y%m%d_%H%M%S}"
1441
+ cfg.run_id = sanitize_label(cfg.run_id) if cfg.run_id else \
1442
+ (f"{cfg.host_label}_{stamp}" if cfg.host_label else stamp)
1443
+
1444
+ net = detect_network(cfg.target)
1445
+ dns_server = resolve_dns_server(cfg, net)
1446
+ pool = ThreadPoolExecutor(max_workers=8)
1447
+
1448
+ if cfg.check:
1449
+ print(json.dumps({
1450
+ "collector_version": COLLECTOR_VERSION,
1451
+ "os": platform.platform(),
1452
+ "python": platform.python_version(),
1453
+ "ping_utility": shutil.which("ping"),
1454
+ "ookla_cli": _ookla_cli_path(),
1455
+ "iperf3": shutil.which("iperf3"),
1456
+ "network": asdict(net),
1457
+ "dns_server": dns_server,
1458
+ }, indent=2))
1459
+ s = collect_sample(cfg, net, dns_server, pool, run_speed=cfg.speedtest,
1460
+ run_lan=bool(cfg.iperf_server))
1461
+ print(json.dumps(asdict(s), indent=2))
1462
+ pool.shutdown(wait=False)
1463
+ return 0
1464
+
1465
+ out_dir = Path(cfg.output_dir)
1466
+ out_dir.mkdir(parents=True, exist_ok=True)
1467
+ csv_path = out_dir / f"localnet_{cfg.run_id}.csv"
1468
+ json_path = out_dir / f"localnet_{cfg.run_id}.json"
1469
+ if csv_path.exists():
1470
+ print(f"error: {csv_path} already exists; choose another --run-id", file=sys.stderr)
1471
+ return 2
1472
+
1473
+ light_budget = max(cfg.ping_count, cfg.gateway_ping_count) * max(1.0, cfg.ping_timeout) + 2.0
1474
+ print(f"LocalNet-Dynamics collector {COLLECTOR_VERSION}")
1475
+ print(f"run id : {cfg.run_id}")
1476
+ print(f"target : {cfg.target} (ICMP x{cfg.ping_count}, TCP :{cfg.tcp_port} x{cfg.tcp_count})")
1477
+ print(f"gateway : {net.gateway or 'not detected'} link: {net.link_type}"
1478
+ f" interface: {net.interface or '?'} local ip: {net.local_ip or '?'}")
1479
+ print(f"dns server : {dns_server or 'none (DNS probes disabled)'} name: {cfg.dns_host}")
1480
+ print(f"http probe : {cfg.http_url or 'disabled'}")
1481
+ print(f"schedule : every {human_duration(cfg.interval)} for {human_duration(cfg.duration)}"
1482
+ f" (~{int(cfg.duration // cfg.interval) + 1} samples)")
1483
+ if cfg.speedtest:
1484
+ print(f"wan speed : every {human_duration(cfg.speedtest_every)}"
1485
+ f" ({'ookla cli' if _ookla_cli_path() else 'speedtest-cli module'})")
1486
+ if cfg.iperf_server:
1487
+ print(f"lan iperf3 : {cfg.iperf_server}:{cfg.iperf_port} every "
1488
+ f"{human_duration(cfg.iperf_every)}, {cfg.iperf_duration}s per test")
1489
+ print(f"output : {csv_path}")
1490
+ if cfg.interval < light_budget:
1491
+ print(f"warning: the worst-case probe time ({light_budget:.0f}s) exceeds the interval;"
1492
+ f" samples will be skipped during outages")
1493
+ if not net.gateway:
1494
+ print("warning: default gateway not detected; gateway metrics will be empty")
1495
+ print("Press Ctrl-C to stop; every completed sample is already on disk.\n")
1496
+
1497
+ install_sigterm_handler()
1498
+ started_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1499
+ summary = RunningSummary()
1500
+ status = "completed"
1501
+
1502
+ csv_file = csv_path.open("w", newline="", encoding="utf-8")
1503
+ writer = csv.DictWriter(csv_file, fieldnames=CSV_FIELDS)
1504
+ writer.writeheader()
1505
+ csv_file.flush()
1506
+ write_meta(json_path, cfg, net, dns_server, summary, "running", started_utc, 0.0, csv_path.name)
1507
+
1508
+ start_mono = time.monotonic()
1509
+ next_speed = start_mono if cfg.speedtest else None
1510
+ next_lan = start_mono if cfg.iperf_server else None
1511
+ next_route = start_mono + ROUTE_REFRESH_S
1512
+ next_meta = start_mono + META_REFRESH_S
1513
+ tick = 0
1514
+ index = 0
1515
+
1516
+ try:
1517
+ with (KeepAwake() if cfg.keep_awake else contextlib.nullcontext()) as awake:
1518
+ if cfg.keep_awake and not (awake and awake.active):
1519
+ print("note: could not inhibit system sleep; disable sleep in the OS power settings")
1520
+ while True:
1521
+ due = start_mono + tick * cfg.interval
1522
+ if due - start_mono >= cfg.duration:
1523
+ break
1524
+ now = time.monotonic()
1525
+ if due > now:
1526
+ time.sleep(due - now)
1527
+ elapsed = time.monotonic() - start_mono
1528
+
1529
+ if time.monotonic() >= next_route:
1530
+ fresh = detect_network(cfg.target)
1531
+ if fresh.gateway:
1532
+ net = fresh
1533
+ dns_server = resolve_dns_server(cfg, net)
1534
+ next_route = time.monotonic() + ROUTE_REFRESH_S
1535
+
1536
+ run_speed = next_speed is not None and time.monotonic() >= next_speed
1537
+ run_lan = next_lan is not None and time.monotonic() >= next_lan
1538
+ s = collect_sample(cfg, net, dns_server, pool, run_speed, run_lan)
1539
+ s.sample_index = index
1540
+ s.elapsed_s = round(elapsed, 1)
1541
+ if run_speed:
1542
+ next_speed += cfg.speedtest_every
1543
+ if run_lan:
1544
+ next_lan += cfg.iperf_every
1545
+ if s.gateway_packet_loss_pct == 100.0:
1546
+ next_route = min(next_route, time.monotonic() + 60.0)
1547
+
1548
+ writer.writerow(asdict(s))
1549
+ csv_file.flush()
1550
+ summary.add(s)
1551
+ index += 1
1552
+ if not cfg.quiet:
1553
+ print(format_progress(s), flush=True)
1554
+
1555
+ if time.monotonic() >= next_meta:
1556
+ write_meta(json_path, cfg, net, dns_server, summary, "running",
1557
+ started_utc, time.monotonic() - start_mono, csv_path.name)
1558
+ next_meta = time.monotonic() + META_REFRESH_S
1559
+
1560
+ tick += 1
1561
+ finished = time.monotonic()
1562
+ if finished > start_mono + tick * cfg.interval:
1563
+ skipped = int((finished - start_mono) // cfg.interval) - tick + 1
1564
+ tick += skipped
1565
+ if not cfg.quiet:
1566
+ print(f" sample took {s.sample_duration_s}s; skipping {skipped} tick(s)")
1567
+ except KeyboardInterrupt:
1568
+ status = "interrupted"
1569
+ print("\nStopping; finalizing files...")
1570
+ finally:
1571
+ csv_file.close()
1572
+ pool.shutdown(wait=False)
1573
+
1574
+ elapsed = time.monotonic() - start_mono
1575
+ write_meta(json_path, cfg, net, dns_server, summary, status, started_utc, elapsed, csv_path.name)
1576
+ if summary.count:
1577
+ print_summary(summary, elapsed)
1578
+ print(f"\n{summary.count} samples written to {csv_path}\nrun metadata: {json_path}")
1579
+ return 0
1580
+
1581
+
1582
+ if __name__ == "__main__":
1583
+ sys.exit(main())
scripts/package_huggingface.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Assemble the huggingface/ folder: a self-contained copy of everything that is
4
+ published on the Hugging Face Hub, ready for `hf upload`.
5
+
6
+ huggingface/
7
+ ├── README.md the dataset card (DATASET_CARD.md, unchanged)
8
+ ├── LICENSE
9
+ ├── CITATION.cff citation metadata for the dataset
10
+ ├── requirements.txt
11
+ ├── dataset/ consolidated files, analysis, raw run files
12
+ ├── figures/png, pdf the figures the card embeds
13
+ ├── scripts/ collector, builder, analysis, plotting, packaging
14
+ └── tests/
15
+
16
+ Run it after build_dataset.py, analyze.py and plot_figures.py. The folder is
17
+ rebuilt from scratch on every run and is ignored by git.
18
+
19
+ python package_huggingface.py
20
+ python package_huggingface.py --out-dir /some/other/place
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import re
27
+ import shutil
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ ROOT = Path(__file__).resolve().parent.parent
32
+
33
+ DATASET_CITATION = """cff-version: 1.2.0
34
+ message: "If you use this dataset, please cite it as below. The toolkit that produced it has its own citation in the source repository."
35
+ type: dataset
36
+ title: "LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset"
37
+ authors:
38
+ - family-names: "Ezharjan"
39
+ given-names: "Alexander"
40
+ version: {version}
41
+ date-released: "{date}"
42
+ license: MIT
43
+ url: "https://huggingface.co/datasets/ezharjan/LocalNetDynamics"
44
+ repository-code: "https://github.com/Ezharjan/LocalNetDynamicsDataset"
45
+ abstract: >-
46
+ A longitudinal telemetry dataset of a residential local area network,
47
+ sampled every 30 seconds around the clock from a wired desktop for 19 days.
48
+ Each sample records ICMP latency, jitter and loss to a reference host and to
49
+ the gateway, TCP connect time, cached and recursive DNS response time, HTTP
50
+ time-to-first-response and hourly WAN throughput tests, with time-of-day
51
+ features and rule-based reference labels for forecasting, anomaly detection
52
+ and quality-of-service research.
53
+ keywords:
54
+ - network telemetry
55
+ - latency
56
+ - jitter
57
+ - packet loss
58
+ - DNS
59
+ - throughput
60
+ - quality of service
61
+ - anomaly detection
62
+ - time series
63
+ """
64
+
65
+
66
+ def field(text: str, name: str) -> str:
67
+ m = re.search(rf"^{name}:\s*\"?([^\"\n]+)\"?\s*$", text, re.MULTILINE)
68
+ if not m:
69
+ raise SystemExit(f"CITATION.cff has no '{name}' field")
70
+ return m.group(1).strip()
71
+
72
+
73
+ def copy_tree(src: Path, dst: Path, patterns: tuple[str, ...]) -> list[Path]:
74
+ copied = []
75
+ for pattern in patterns:
76
+ for path in sorted(src.glob(pattern)):
77
+ if path.is_file():
78
+ target = dst / path.relative_to(src)
79
+ target.parent.mkdir(parents=True, exist_ok=True)
80
+ shutil.copy2(path, target)
81
+ copied.append(target)
82
+ return copied
83
+
84
+
85
+ def main(argv: list[str] | None = None) -> int:
86
+ p = argparse.ArgumentParser(description="Assemble the folder that is uploaded to Hugging Face.")
87
+ p.add_argument("--out-dir", default=str(ROOT / "huggingface"))
88
+ args = p.parse_args(argv)
89
+ out = Path(args.out_dir)
90
+
91
+ required = [ROOT / "DATASET_CARD.md", ROOT / "LICENSE", ROOT / "CITATION.cff",
92
+ ROOT / "dataset" / "localnet_dynamics.parquet", ROOT / "dataset" / "analysis.json",
93
+ ROOT / "figures" / "png"]
94
+ missing = [str(path) for path in required if not path.exists()]
95
+ if missing:
96
+ raise SystemExit("missing, run build_dataset.py, analyze.py and plot_figures.py first:\n " + "\n ".join(missing))
97
+
98
+ if out.exists():
99
+ shutil.rmtree(out)
100
+ out.mkdir(parents=True)
101
+
102
+ shutil.copy2(ROOT / "DATASET_CARD.md", out / "README.md")
103
+ shutil.copy2(ROOT / "LICENSE", out / "LICENSE")
104
+ shutil.copy2(ROOT / "requirements.txt", out / "requirements.txt")
105
+ code_citation = (ROOT / "CITATION.cff").read_text(encoding="utf-8")
106
+ (out / "CITATION.cff").write_text(
107
+ DATASET_CITATION.format(version=field(code_citation, "version"), date=field(code_citation, "date-released")),
108
+ encoding="utf-8")
109
+
110
+ files = [out / "README.md", out / "LICENSE", out / "requirements.txt", out / "CITATION.cff"]
111
+ files += copy_tree(ROOT / "dataset", out / "dataset",
112
+ ("localnet_dynamics.csv", "localnet_dynamics.parquet", "summary.json", "analysis.json",
113
+ "raw/localnet_*.csv", "raw/localnet_*.json", "raw/events.csv"))
114
+ files += copy_tree(ROOT / "figures", out / "figures", ("png/*.png", "pdf/*.pdf"))
115
+ files += copy_tree(ROOT / "scripts", out / "scripts", ("*.py",))
116
+ files += copy_tree(ROOT / "tests", out / "tests", ("*.py",))
117
+
118
+ total = sum(f.stat().st_size for f in files)
119
+ for f in files:
120
+ print(f" {f.relative_to(out).as_posix():<60}{f.stat().st_size / 1e6:>9.2f} MB")
121
+ print(f"{len(files)} files, {total / 1e6:.1f} MB written to {out}")
122
+ return 0
123
+
124
+
125
+ if __name__ == "__main__":
126
+ sys.exit(main())
scripts/plot_figures.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Render the LocalNet-Dynamics figures as PNG and PDF.
4
+
5
+ Reads the consolidated dataset and dataset/analysis.json (written by
6
+ analyze.py) and writes every figure twice, figures/png/<name>.png and
7
+ figures/pdf/<name>.pdf, cropped to the drawn area with no margin:
8
+
9
+ overview_timeline the whole capture: target RTT, TCP connect, first hop, loss
10
+ diurnal_profile hour-of-day latency, loss (weekday/weekend) and tail shares
11
+ calendar_heatmaps day-by-hour loss share, high-latency share, HTTP > 1 s share
12
+ degradation_anatomy a path change next to a first-hop event, probe by probe
13
+ tcp_vs_icmp the TCP/ICMP floor split that ping cannot see
14
+ loss_anatomy what a lost echo means for the other probes
15
+ regimes distributions before and after the change point
16
+ autocorrelation persistence of every metric up to a one-day lag
17
+ speedtest WAN throughput by time and by server
18
+ labels reference-label shares in the two regimes
19
+
20
+ python plot_figures.py
21
+ python plot_figures.py --input dataset/localnet_dynamics.parquet --out-dir figures
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+ from analyze import ROOT, analyse, load # noqa: E402
36
+
37
+ BLUE, ORANGE, AQUA, YELLOW = "#2a78d6", "#eb6834", "#1baf7a", "#eda100"
38
+ MAGENTA, GREEN, VIOLET, RED = "#e87ba4", "#008300", "#6250d6", "#e34948"
39
+ INK, INK2, MUTED, GRID, AXIS = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
40
+ BLUES = ["#f3f7fd", "#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", "#0d366b"]
41
+ NAVY = "#0d366b"
42
+ LOSS_CLASSES = [("no_loss", "no loss"), ("one_lost", "1 of 10 lost"), ("two_plus_lost", "2+ of 10 lost")]
43
+ WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
44
+
45
+
46
+ def style(plt) -> None:
47
+ plt.rcParams.update({
48
+ "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white",
49
+ "font.family": "sans-serif",
50
+ "font.sans-serif": ["Inter", "Segoe UI", "Helvetica Neue", "Arial", "DejaVu Sans"],
51
+ "font.size": 15, "axes.titlesize": 18, "axes.titleweight": "semibold", "axes.titlepad": 14,
52
+ "axes.labelsize": 15, "axes.labelcolor": INK2, "xtick.labelsize": 13, "ytick.labelsize": 13,
53
+ "xtick.color": INK2, "ytick.color": INK2, "legend.fontsize": 13, "legend.frameon": False,
54
+ "axes.edgecolor": AXIS, "axes.linewidth": 1.0, "axes.grid": True, "grid.color": GRID,
55
+ "grid.linewidth": 0.8, "axes.axisbelow": True, "axes.spines.top": False, "axes.spines.right": False,
56
+ "lines.linewidth": 2.0, "xtick.major.size": 0, "ytick.major.size": 0,
57
+ "xtick.major.pad": 8, "ytick.major.pad": 8, "legend.handlelength": 1.6,
58
+ })
59
+
60
+
61
+ def save(fig, out: Path, name: str) -> None:
62
+ (out / "png").mkdir(parents=True, exist_ok=True)
63
+ (out / "pdf").mkdir(parents=True, exist_ok=True)
64
+ fig.savefig(out / "png" / f"{name}.png", dpi=200, bbox_inches="tight", pad_inches=0)
65
+ fig.savefig(out / "pdf" / f"{name}.pdf", bbox_inches="tight", pad_inches=0,
66
+ metadata={"CreationDate": None, "ModDate": None})
67
+
68
+
69
+ def month_day(ts) -> str:
70
+ return f"{ts:%b %-d}" if sys.platform != "win32" else f"{ts:%b %d}".replace(" 0", " ")
71
+
72
+
73
+ def period_label(g: dict, key: str) -> str:
74
+ first, last = pd.Timestamp(g[key]["first_date"]), pd.Timestamp(g[key]["last_date"])
75
+ return f"{month_day(first)} to {month_day(last)}"
76
+
77
+
78
+ def date_axis(ax, mdates) -> None:
79
+ ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
80
+ ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
81
+ ax.xaxis.set_minor_locator(mdates.DayLocator())
82
+ for label in ax.get_xticklabels():
83
+ label.set_rotation(0)
84
+
85
+
86
+ def shade_episodes(ax, a: dict, labels: bool = False) -> list:
87
+ handles = []
88
+ kinds = {"path change": (BLUE, 0.14, "path change (latency floor moved)"),
89
+ "first hop": (AQUA, 0.22, "first-hop degradation"),
90
+ "queueing": (YELLOW, 0.22, "queueing")}
91
+ seen = set()
92
+ for e in a["latency_episodes"]:
93
+ color, alpha, text = kinds[e["kind"]]
94
+ s, t = pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19])
95
+ ax.axvspan(s, t, color=color, alpha=alpha, linewidth=0, zorder=0)
96
+ if e["kind"] not in seen:
97
+ seen.add(e["kind"])
98
+ handles.append((color, alpha, text))
99
+ for o in a["outages"]:
100
+ ax.axvline(pd.Timestamp(o["start_local"][:19]), color=RED, linewidth=2.2, alpha=0.9, zorder=1)
101
+ split = pd.Timestamp(a["regimes"]["split_date"])
102
+ ax.axvline(split, color=INK2, linewidth=1.6, linestyle=(0, (5, 4)), zorder=1)
103
+ return handles
104
+
105
+
106
+ # --------------------------------------------------------------------------- #
107
+ # Figures
108
+ # --------------------------------------------------------------------------- #
109
+
110
+ def fig_overview(df, a, out, plt, mdates):
111
+ from matplotlib.lines import Line2D
112
+ from matplotlib.patches import Patch
113
+ x = df["ts_local"]
114
+ fig, axes = plt.subplots(4, 1, figsize=(18, 13), sharex=True,
115
+ gridspec_kw={"height_ratios": [3, 2.2, 1.6, 1.6], "hspace": 0.32})
116
+ rtt_cap = 40
117
+ ax = axes[0]
118
+ handles = shade_episodes(ax, a)
119
+ ax.plot(x, df["rtt_avg_ms"].clip(upper=rtt_cap), color=BLUE, linewidth=0.5, alpha=0.45)
120
+ roll = df["rtt_avg_ms"].rolling(60, center=True, min_periods=20).median()
121
+ ax.plot(x, roll, color=NAVY, linewidth=1.8)
122
+ ax.set_ylim(0, rtt_cap)
123
+ ax.set_ylabel("ms")
124
+ ax.set_title(f"Round-trip time to {df['target'].iloc[0]} (ICMP, 10-echo mean per sample, clipped at {rtt_cap} ms)",
125
+ loc="left")
126
+ series = [Line2D([], [], color=BLUE, linewidth=1.2, alpha=0.7, label="per sample"),
127
+ Line2D([], [], color=NAVY, linewidth=2.2, label="30-minute rolling median")]
128
+ bands = [Patch(facecolor=c, alpha=min(1.0, al * 2.2), label=t) for c, al, t in handles]
129
+ bands += [Line2D([], [], color=RED, linewidth=2.2, label="outage (gateway unreachable)"),
130
+ Line2D([], [], color=INK2, linewidth=1.6, linestyle=(0, (5, 4)), label="change point in daily loss share")]
131
+ fig.legend(handles=series + bands, loc="lower center", bbox_to_anchor=(0.5, 0.925), ncol=6,
132
+ frameon=False, columnspacing=1.6, handletextpad=0.6)
133
+
134
+ ax = axes[1]
135
+ shade_episodes(ax, a)
136
+ ax.scatter(x, df["tcp_connect_min_ms"].clip(upper=rtt_cap), s=2.5, color=ORANGE, alpha=0.35, linewidth=0, rasterized=True)
137
+ ax.set_ylim(0, rtt_cap)
138
+ ax.set_ylabel("ms")
139
+ ax.set_title("Fastest of 5 TCP handshakes to port 443 of the same host (sub-millisecond resolution)", loc="left")
140
+
141
+ ax = axes[2]
142
+ shade_episodes(ax, a)
143
+ ax.plot(x, df["gateway_rtt_avg_ms"].clip(upper=20), color=AQUA, linewidth=0.7)
144
+ ax.set_ylim(0, 20)
145
+ ax.set_ylabel("ms")
146
+ ax.set_title("Round-trip time to the default gateway (first hop, clipped at 20 ms)", loc="left")
147
+
148
+ ax = axes[3]
149
+ shade_episodes(ax, a)
150
+ hourly = (df["packet_loss_pct"] > 0).groupby(df["ts_local"].dt.floor("h")).mean() * 100
151
+ ax.bar(hourly.index, hourly.values, width=pd.Timedelta(hours=1), color=RED, linewidth=0, alpha=0.9)
152
+ ax.set_ylim(0, 100)
153
+ ax.set_ylabel("% of samples")
154
+ ax.set_title("Samples with at least one lost echo, per hour", loc="left")
155
+ ax.set_xlabel("local time (America/New_York)")
156
+ date_axis(ax, mdates)
157
+ ax.set_xlim(x.min() - pd.Timedelta(hours=3), x.max() + pd.Timedelta(hours=3))
158
+ save(fig, out, "overview_timeline")
159
+ plt.close(fig)
160
+
161
+
162
+ def fig_diurnal(df, a, out, plt):
163
+ prof = pd.DataFrame(a["hour_profile"]).set_index("hour").reindex(range(24))
164
+ hours = np.arange(24)
165
+ fig, axes = plt.subplots(1, 3, figsize=(20, 6.4), gridspec_kw={"wspace": 0.28})
166
+ ax = axes[0]
167
+ ax.fill_between(hours, prof["rtt_p25"], prof["rtt_p75"], color=BLUE, alpha=0.16, linewidth=0, label="interquartile range")
168
+ ax.plot(hours, prof["rtt_median"], color=BLUE, marker="o", markersize=6, label="median")
169
+ ax.plot(hours, prof["rtt_p95"], color=NAVY, marker="o", markersize=6, label="95th percentile")
170
+ ax.set_ylim(0, max(32, float(prof["rtt_p95"].max()) * 1.15))
171
+ ax.set_ylabel("target RTT (ms)")
172
+ ax.set_title("Latency by local hour", loc="left")
173
+ ax.legend(loc="upper center", ncol=1)
174
+ ax = axes[1]
175
+ ax.plot(hours, prof["loss_share_weekday_pct"], color=BLUE, marker="o", markersize=6, label="weekdays")
176
+ ax.plot(hours, prof["loss_share_weekend_pct"], color=ORANGE, marker="o", markersize=6, label="weekends")
177
+ ax.set_ylim(0, max(30, float(prof[["loss_share_weekday_pct", "loss_share_weekend_pct"]].max().max()) * 1.2))
178
+ ax.set_ylabel("% of samples with a lost echo")
179
+ ax.set_title("Loss by local hour", loc="left")
180
+ ax.legend(loc="upper left")
181
+ ax = axes[2]
182
+ ax.plot(hours, prof["http_over_1s_pct"], color=VIOLET, marker="o", markersize=6, label="HTTP response > 1 s")
183
+ ax.plot(hours, prof["high_latency_pct"], color=BLUE, marker="o", markersize=6, label="high-latency label")
184
+ ax.set_ylim(0, max(25, float(prof[["http_over_1s_pct", "high_latency_pct"]].max().max()) * 1.25))
185
+ ax.set_ylabel("% of samples")
186
+ ax.set_title("Two tails with opposite clocks", loc="left")
187
+ ax.legend(loc="upper center")
188
+ for ax in axes:
189
+ ax.set_xticks(range(0, 24, 3))
190
+ ax.set_xticklabels([f"{h:02d}" for h in range(0, 24, 3)])
191
+ ax.set_xlim(-0.5, 23.5)
192
+ ax.set_xlabel("local hour")
193
+ save(fig, out, "diurnal_profile")
194
+ plt.close(fig)
195
+
196
+
197
+ def fig_heatmaps(df, a, out, plt):
198
+ from matplotlib.colors import LinearSegmentedColormap
199
+ cmap = LinearSegmentedColormap.from_list("blues", BLUES).with_extremes(bad="#eeede9")
200
+ panels = [
201
+ ("packet_loss_pct", lambda s: 100 * (s > 0).mean(), "Samples with a lost echo (%)"),
202
+ ("label_high_latency", lambda s: 100 * s.mean(), "Samples over the high-latency threshold (%)"),
203
+ ("http_ms", lambda s: 100 * (s.dropna() > 1000).mean(), "HTTP responses slower than 1 s (%)"),
204
+ ]
205
+ dates = sorted(df["date_local"].unique())
206
+ weekday = df.groupby("date_local")["weekday_local"].first()
207
+ fig, axes = plt.subplots(1, 3, figsize=(22, 0.42 * len(dates) + 2.4), gridspec_kw={"wspace": 0.12})
208
+ for ax, (col, fn, title) in zip(axes, panels):
209
+ pivot = df.pivot_table(index="date_local", columns="hour_local", values=col, aggfunc=fn)
210
+ pivot = pivot.reindex(index=dates, columns=range(24))
211
+ vmax = max(1.0, float(np.nanpercentile(pivot.values, 98)))
212
+ im = ax.imshow(np.ma.masked_invalid(pivot.values.astype(float)), aspect="auto", cmap=cmap,
213
+ vmin=0, vmax=vmax, interpolation="nearest")
214
+ ax.set_xticks(range(0, 24, 3))
215
+ ax.set_xticklabels([f"{h:02d}" for h in range(0, 24, 3)])
216
+ ax.set_xlabel("local hour")
217
+ ax.set_title(title, loc="left")
218
+ ax.grid(False)
219
+ for spine in ax.spines.values():
220
+ spine.set_visible(False)
221
+ cbar = fig.colorbar(im, ax=ax, orientation="horizontal", fraction=0.045, pad=0.14, aspect=28)
222
+ cbar.outline.set_visible(False)
223
+ cbar.ax.tick_params(labelsize=12)
224
+ axes[0].set_yticks(range(len(dates)))
225
+ axes[0].set_yticklabels([f"{WEEKDAYS[int(weekday[d])]} {pd.Timestamp(d):%b %d}" for d in dates])
226
+ for d, label in zip(dates, axes[0].get_yticklabels()):
227
+ if int(weekday[d]) >= 5:
228
+ label.set_color(ORANGE)
229
+ label.set_fontweight("semibold")
230
+ for ax in axes[1:]:
231
+ ax.set_yticks([])
232
+ save(fig, out, "calendar_heatmaps")
233
+ plt.close(fig)
234
+
235
+
236
+ def fig_anatomy(df, a, out, plt, mdates):
237
+ def window(kind):
238
+ """The longest episode of this kind, extended over same-kind episodes within two hours of it."""
239
+ eps = [e for e in a["latency_episodes"] if e["kind"] == kind]
240
+ if not eps:
241
+ return None
242
+ chain = [max(eps, key=lambda e: e["hours"])]
243
+ grown = True
244
+ while grown:
245
+ grown = False
246
+ lo = min(pd.Timestamp(e["start_local"][:19]) for e in chain) - pd.Timedelta(hours=2)
247
+ hi = max(pd.Timestamp(e["end_local"][:19]) for e in chain) + pd.Timedelta(hours=2)
248
+ for e in eps:
249
+ if e not in chain and lo <= pd.Timestamp(e["start_local"][:19]) <= hi:
250
+ chain.append(e)
251
+ grown = True
252
+ return sorted(chain, key=lambda e: e["start_local"])
253
+
254
+ chosen = [(window("path change"), "Path change"), (window("first hop"), "First-hop event")]
255
+ chosen = [(c, t) for c, t in chosen if c]
256
+ if not chosen:
257
+ return
258
+ fig, axes = plt.subplots(2, len(chosen), figsize=(10 * len(chosen), 9.5), sharex="col",
259
+ gridspec_kw={"height_ratios": [2.4, 1], "hspace": 0.22, "wspace": 0.16}, squeeze=False)
260
+ cap, top = 45, 60
261
+ for col, (chain, title) in enumerate(chosen):
262
+ start = pd.Timestamp(chain[0]["start_local"][:19])
263
+ end = pd.Timestamp(chain[-1]["end_local"][:19])
264
+ part = df[(df["ts_local"] >= start - pd.Timedelta(hours=2)) & (df["ts_local"] <= end + pd.Timedelta(hours=2))]
265
+ x = part["ts_local"]
266
+ tint = BLUE if chain[0]["kind"] == "path change" else AQUA
267
+ ax = axes[0, col]
268
+ for e in chain:
269
+ ax.axvspan(pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19]), color=tint, alpha=0.12, linewidth=0)
270
+ ax.plot(x, part["rtt_avg_ms"].clip(upper=cap), color=BLUE, linewidth=1.0, alpha=0.5, label="ICMP mean of 10")
271
+ ax.plot(x, part["rtt_min_ms"].clip(upper=cap), color=NAVY, linewidth=1.4, label="ICMP minimum of 10")
272
+ ax.plot(x, part["tcp_connect_min_ms"].clip(upper=cap), color=ORANGE, linewidth=1.2, alpha=0.9, label="TCP fastest of 5")
273
+ ax.set_ylim(0, top)
274
+ ax.set_ylabel(f"ms to target (clipped at {cap})")
275
+ hours = (end - start).total_seconds() / 3600.0
276
+ ax.set_title(f"{title}: {WEEKDAYS[chain[0]['weekday']]} {month_day(start)}, {hours:.1f} h", loc="left")
277
+ ax.legend(loc="upper left", ncol=3)
278
+ ax = axes[1, col]
279
+ for e in chain:
280
+ ax.axvspan(pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19]), color=tint, alpha=0.12, linewidth=0)
281
+ ax.plot(x, part["gateway_rtt_avg_ms"].clip(upper=30), color=AQUA, linewidth=1.2)
282
+ ax.set_ylim(0, 30)
283
+ ax.set_ylabel("ms to gateway")
284
+ ax.set_xlabel("local time")
285
+ ax.xaxis.set_major_locator(mdates.HourLocator(interval=2))
286
+ ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
287
+ save(fig, out, "degradation_anatomy")
288
+ plt.close(fig)
289
+
290
+
291
+ def fig_tcp_icmp(df, a, out, plt, mdates):
292
+ split = pd.Timestamp(a["tcp_icmp"]["split_local"])
293
+ fig, axes = plt.subplots(1, 2, figsize=(20, 6.4), gridspec_kw={"width_ratios": [2.3, 1], "wspace": 0.2})
294
+ ax = axes[0]
295
+ x = df["ts_local"]
296
+ cap = 35
297
+ from matplotlib.lines import Line2D
298
+ ax.scatter(x, df["tcp_connect_min_ms"].clip(upper=cap), s=2.5, color=ORANGE, alpha=0.35, linewidth=0, rasterized=True)
299
+ roll = df["rtt_min_ms"].rolling(120, center=True, min_periods=30).median()
300
+ ax.plot(x, roll, color=NAVY, linewidth=2.0)
301
+ handles = [Line2D([], [], marker="o", color=ORANGE, linestyle="none", markersize=8, label="TCP fastest of 5 handshakes, per sample"),
302
+ Line2D([], [], color=NAVY, linewidth=2.2, label="ICMP minimum of 10, 1-hour rolling median")]
303
+ ax.axvline(split, color=INK2, linewidth=1.6, linestyle=(0, (5, 4)))
304
+ ax.text(split, cap * 0.97, f" {month_day(split)} {split:%H:%M}", color=INK2, va="top", ha="left", fontsize=13)
305
+ ax.set_ylim(0, cap)
306
+ ax.set_ylabel("ms")
307
+ ax.set_xlabel("local time")
308
+ ax.set_title("Latency floor seen by TCP and by ICMP", loc="left")
309
+ ax.legend(handles=handles, loc="lower left")
310
+ date_axis(ax, mdates)
311
+ ax = axes[1]
312
+ before = df.loc[df["ts_local"] < split, "tcp_connect_min_ms"].dropna()
313
+ after = df.loc[df["ts_local"] >= split, "tcp_connect_min_ms"].dropna()
314
+ bins = np.arange(8, 32.5, 0.5)
315
+ ax.hist(before.clip(8, 32), bins=bins, density=True, color=MUTED, alpha=0.75, linewidth=0,
316
+ label=f"before ({len(before):,} samples)")
317
+ ax.hist(after.clip(8, 32), bins=bins, density=True, color=ORANGE, alpha=0.8, linewidth=0,
318
+ label=f"after ({len(after):,} samples)")
319
+ ax.set_xlabel("TCP fastest handshake (ms)")
320
+ ax.set_ylabel("density")
321
+ ax.set_title("Before and after the split", loc="left")
322
+ ax.legend(loc="upper right")
323
+ save(fig, out, "tcp_vs_icmp")
324
+ plt.close(fig)
325
+
326
+
327
+ def fig_loss(df, a, out, plt):
328
+ L = a["loss"]
329
+ fig = plt.figure(figsize=(20, 11))
330
+ gs = fig.add_gridspec(2, 3, height_ratios=[1, 1.1], hspace=0.45, wspace=0.3)
331
+ ax = fig.add_subplot(gs[0, 0])
332
+ counts = {int(k): v for k, v in L["packets_received_counts"].items()}
333
+ keys = sorted(counts, reverse=True)
334
+ ax.bar(range(len(keys)), [counts[k] for k in keys], color=BLUE, linewidth=0, width=0.72)
335
+ ax.set_xticks(range(len(keys)))
336
+ ax.set_xticklabels([str(k) for k in keys])
337
+ ax.set_yscale("log")
338
+ ax.set_ylim(1, max(counts.values()) * 4)
339
+ ax.set_xlabel("echo replies received out of 10")
340
+ ax.set_ylabel("samples (log scale)")
341
+ ax.set_title("Loss comes one echo at a time", loc="left")
342
+ for i, k in enumerate(keys):
343
+ ax.text(i, counts[k] * 1.25, f"{counts[k]:,}", ha="center", va="bottom", fontsize=12, color=INK2)
344
+
345
+ xs = np.arange(len(LOSS_CLASSES))
346
+ w = 0.36
347
+ c = L["conditional"]
348
+
349
+ def grouped(ax, left, right, unit, title):
350
+ for offset, (key, color, name) in zip((-w / 2, w / 2), (left, right)):
351
+ values = [c[k][key] or 0.0 for k, _ in LOSS_CLASSES]
352
+ ax.bar(xs + offset, values, w, color=color, linewidth=0, label=name)
353
+ for i, v in enumerate(values):
354
+ ax.text(i + offset, v + 0.02 * top, f"{v:.1f}", ha="center", fontsize=12, color=INK2)
355
+ ax.set_xticks(xs)
356
+ ax.set_xticklabels([t for _, t in LOSS_CLASSES])
357
+ ax.set_ylabel(unit)
358
+ ax.set_ylim(0, top)
359
+ ax.set_title(title, loc="left")
360
+ ax.legend(loc="upper left")
361
+
362
+ top = max(1.0, max((c[k]["http_over_1s_pct"] or 0.0) for k, _ in LOSS_CLASSES) * 1.35)
363
+ grouped(fig.add_subplot(gs[0, 1]), ("http_over_1s_pct", VIOLET, "HTTP response > 1 s"),
364
+ ("dns_recursive_over_200ms_pct", GREEN, "recursive DNS > 200 ms"), "% of samples",
365
+ "Application tails grow with ICMP loss")
366
+ top = max(1.0, max((c[k]["tcp_median"] or 0.0) for k, _ in LOSS_CLASSES) * 1.4)
367
+ grouped(fig.add_subplot(gs[0, 2]), ("jitter_median", MAGENTA, "jitter, median"),
368
+ ("tcp_median", ORANGE, "TCP handshake, median"), "ms", "Jitter rises, the TCP handshake does not")
369
+
370
+ ax = fig.add_subplot(gs[1, :])
371
+ h = df["http_ms"].dropna()
372
+ lo, hi = 20, 8000
373
+ bins = np.logspace(np.log10(lo), np.log10(hi), 150)
374
+ ax.hist(h.clip(lo, hi), bins=bins, color=VIOLET, linewidth=0)
375
+ ax.set_xscale("log")
376
+ ax.set_yscale("log")
377
+ ax.set_xlim(lo, hi)
378
+ ticks = [20, 50, 100, 200, 500, 1000, 2000, 5000]
379
+ ax.set_xticks(ticks)
380
+ ax.set_xticklabels([f"{t:,}" for t in ticks])
381
+ ax.set_xlabel("HTTP time to response headers (ms, log scale)")
382
+ ax.set_ylabel("samples (log scale)")
383
+ H = a["dns_http"]["http"]
384
+ ax.set_title(f"HTTP response time: a smooth body around {H['median']:.0f} ms, then discrete modes near "
385
+ "1.1 s, 1.3 s and 4.1 s where lost packets wait for retransmission timers", loc="left")
386
+ ax.axvspan(1000, 1400, color=VIOLET, alpha=0.1, linewidth=0)
387
+ ax.axvspan(3900, 4400, color=VIOLET, alpha=0.1, linewidth=0)
388
+ save(fig, out, "loss_anatomy")
389
+ plt.close(fig)
390
+
391
+
392
+ def fig_regimes(df, a, out, plt):
393
+ g = a["regimes"]
394
+ split = g["split_date"]
395
+ before, after = df[df["date_local"] < split], df[df["date_local"] >= split]
396
+ panels = [("rtt_avg_ms", "ICMP round-trip time, mean of 10 (ms)", (8, 60), [10, 15, 20, 30, 40, 60]),
397
+ ("jitter_ms", "ICMP jitter (ms)", (0.1, 30), [0.1, 0.3, 1, 3, 10, 30]),
398
+ ("tcp_connect_median_ms", "TCP handshake, median of 5 (ms)", (10, 80), [10, 15, 20, 30, 40, 60, 80]),
399
+ ("dns_resolve_ms", "DNS, resolver-cached name (ms)", (5, 300), [5, 10, 20, 50, 100, 200, 300]),
400
+ ("dns_recursive_ms", "DNS, recursive lookup (ms)", (20, 2000), [20, 50, 100, 200, 500, 1000, 2000]),
401
+ ("http_ms", "HTTP time to response headers (ms)", (30, 5000), [30, 100, 300, 1000, 3000])]
402
+ fig, axes = plt.subplots(2, 3, figsize=(20, 10), gridspec_kw={"hspace": 0.5, "wspace": 0.18})
403
+ for i, (ax, (col, title, lim, ticks)) in enumerate(zip(axes.ravel(), panels)):
404
+ for part, color, key in ((before, BLUE, "before"), (after, ORANGE, "after")):
405
+ v = np.sort(part[col].dropna().values)
406
+ if v.size == 0:
407
+ continue
408
+ v = np.clip(v, lim[0], lim[1])
409
+ ax.step(v, np.arange(1, v.size + 1) / v.size * 100, where="post", color=color, linewidth=2.2,
410
+ label=f"{key}: {period_label(g, key)}")
411
+ ax.set_xscale("log")
412
+ ax.set_xlim(*lim)
413
+ ax.set_xticks(ticks)
414
+ ax.set_xticklabels([f"{t:g}" for t in ticks])
415
+ ax.xaxis.set_minor_locator(plt.NullLocator())
416
+ ax.set_ylim(0, 100)
417
+ ax.set_yticks([0, 25, 50, 75, 100])
418
+ if i % 3 == 0:
419
+ ax.set_ylabel("% of samples at or below")
420
+ ax.set_title(title, loc="left")
421
+ axes[0, 0].legend(loc="lower right")
422
+ save(fig, out, "regimes")
423
+ plt.close(fig)
424
+
425
+
426
+ def fig_acf(df, a, out, plt):
427
+ A = a["autocorrelation"]
428
+ lags = A["lag_minutes"]
429
+ series = [("log_rtt_avg_ms", "ICMP RTT (log)", BLUE), ("jitter_ms", "jitter", MAGENTA),
430
+ ("loss_indicator", "lost echo (0/1)", RED), ("tcp_connect_min_ms", "TCP fastest handshake", ORANGE),
431
+ ("dns_recursive_ms", "recursive DNS", GREEN), ("http_ms", "HTTP", VIOLET)]
432
+ fig, ax = plt.subplots(figsize=(16, 7))
433
+ for key, name, color in series:
434
+ pts = [(l, v) for l, v in zip(lags, A["values"][key]) if v is not None]
435
+ if pts:
436
+ ax.plot([l for l, _ in pts], [v for _, v in pts], color=color, marker="o", markersize=6, label=name)
437
+ ax.set_xscale("log")
438
+ ticks = [0.5, 1, 2.5, 5, 10, 30, 60, 180, 360, 720, 1440]
439
+ ax.set_xticks(ticks)
440
+ ax.set_xticklabels(["30 s", "1 m", "2.5 m", "5 m", "10 m", "30 m", "1 h", "3 h", "6 h", "12 h", "24 h"])
441
+ ax.set_xlim(0.4, 1440 * 1.3)
442
+ ax.set_ylim(-0.05, 1.0)
443
+ ax.axhline(0, color=AXIS, linewidth=1.0)
444
+ ax.set_xlabel("lag")
445
+ ax.set_ylabel("autocorrelation")
446
+ ax.set_title("How long the network remembers: autocorrelation of each probe against lag", loc="left")
447
+ ax.legend(loc="upper right", ncol=2)
448
+ save(fig, out, "autocorrelation")
449
+ plt.close(fig)
450
+
451
+
452
+ def fig_speedtest(df, a, out, plt, mdates):
453
+ sp = df[df["download_mbps"].notna()].copy()
454
+ if sp.empty:
455
+ return
456
+ S = a["speedtest"]
457
+ failed = sp["speedtest_ping_ms"].isna() | (sp["speedtest_ping_ms"] >= 600_000)
458
+ fig = plt.figure(figsize=(20, 9.5))
459
+ gs = fig.add_gridspec(2, 2, width_ratios=[1.45, 1], hspace=0.42, wspace=0.12)
460
+ for row, (col, color, title) in enumerate((("download_mbps", BLUE, "Download"), ("upload_mbps", ORANGE, "Upload"))):
461
+ ax = fig.add_subplot(gs[row, 0])
462
+ ok, bad = sp[~failed], sp[failed]
463
+ ax.scatter(ok["ts_local"], ok[col], s=30, color=color, alpha=0.85, linewidth=0, label="server latency probe succeeded")
464
+ ax.scatter(bad["ts_local"], bad[col], s=42, facecolor="white", edgecolor=color, linewidth=1.4,
465
+ label="server latency probe failed")
466
+ ax.set_ylabel("Mbit/s")
467
+ ax.set_title(f"{title}: {len(sp)} hourly tests on {S['servers']} different servers" if row == 0 else title, loc="left")
468
+ ax.set_ylim(0, float(sp[col].max()) * 1.12)
469
+ if row == 0:
470
+ ax.legend(loc="upper left", ncol=2)
471
+ else:
472
+ ax.set_xlabel("local time")
473
+ date_axis(ax, mdates)
474
+ ax = fig.add_subplot(gs[:, 1])
475
+ top = S["top_servers"]
476
+ names = [t["server"] for t in top]
477
+ for i, t in enumerate(top):
478
+ part = sp[sp["speedtest_server"] == t["server"]]
479
+ y = np.full(len(part), i) + np.random.default_rng(i).uniform(-0.18, 0.18, len(part))
480
+ ax.scatter(part["download_mbps"], y, s=34, color=BLUE, alpha=0.6, linewidth=0)
481
+ ax.plot([t["download_median"], t["download_median"]], [i - 0.32, i + 0.32], color=NAVY, linewidth=3)
482
+ ax.set_yticks(range(len(top)))
483
+ ax.set_yticklabels([f"{n} ({t['n']})" for n, t in zip(names, top)])
484
+ ax.yaxis.tick_right()
485
+ ax.invert_yaxis()
486
+ ax.set_xlabel("download (Mbit/s); bar = median of that server")
487
+ ax.set_title("Download depends on which server was picked", loc="left")
488
+ save(fig, out, "speedtest")
489
+ plt.close(fig)
490
+
491
+
492
+ def fig_labels(df, a, out, plt):
493
+ g = a["regimes"]
494
+ names = [("label_outage", "outage"), ("label_packet_loss", "packet loss"), ("label_high_latency", "high latency"),
495
+ ("label_high_jitter", "high jitter"), ("label_gateway_degraded", "gateway degraded"), ("label_anomaly", "any (anomaly)")]
496
+ ys = np.arange(len(names))
497
+ h = 0.38
498
+ fig, ax = plt.subplots(figsize=(14, 6.6))
499
+ b = [g["before"]["labels_pct"][k] for k, _ in names]
500
+ c = [g["after"]["labels_pct"][k] for k, _ in names]
501
+ ax.barh(ys - h / 2, b, h, color=BLUE, linewidth=0, label=period_label(g, "before"))
502
+ ax.barh(ys + h / 2, c, h, color=ORANGE, linewidth=0, label=period_label(g, "after"))
503
+ for y, v in zip(ys - h / 2, b):
504
+ ax.text(v + 0.6, y, f"{v:.1f} %", va="center", fontsize=13, color=INK2)
505
+ for y, v in zip(ys + h / 2, c):
506
+ ax.text(v + 0.6, y, f"{v:.1f} %", va="center", fontsize=13, color=INK2)
507
+ ax.set_yticks(ys)
508
+ ax.set_yticklabels([n for _, n in names])
509
+ ax.invert_yaxis()
510
+ ax.set_xlim(0, max(b + c) * 1.18)
511
+ ax.set_xlabel("% of samples carrying the label")
512
+ ax.set_title("Reference labels before and after the change point", loc="left")
513
+ ax.legend(loc="upper right")
514
+ save(fig, out, "labels")
515
+ plt.close(fig)
516
+
517
+
518
+ # --------------------------------------------------------------------------- #
519
+ # CLI
520
+ # --------------------------------------------------------------------------- #
521
+
522
+ def render_all(df: pd.DataFrame, a: dict, out: Path) -> list[str]:
523
+ import matplotlib
524
+ matplotlib.use("Agg")
525
+ import matplotlib.dates as mdates
526
+ import matplotlib.pyplot as plt
527
+ style(plt)
528
+ out.mkdir(parents=True, exist_ok=True)
529
+ fig_overview(df, a, out, plt, mdates)
530
+ fig_diurnal(df, a, out, plt)
531
+ fig_heatmaps(df, a, out, plt)
532
+ fig_anatomy(df, a, out, plt, mdates)
533
+ fig_tcp_icmp(df, a, out, plt, mdates)
534
+ fig_loss(df, a, out, plt)
535
+ fig_regimes(df, a, out, plt)
536
+ fig_acf(df, a, out, plt)
537
+ fig_speedtest(df, a, out, plt, mdates)
538
+ fig_labels(df, a, out, plt)
539
+ return sorted(p.name for p in (out / "png").glob("*.png"))
540
+
541
+
542
+ def main(argv: list[str] | None = None) -> int:
543
+ p = argparse.ArgumentParser(description="Render the dataset figures as PNG and PDF.")
544
+ p.add_argument("--input", default=None,
545
+ help="consolidated parquet or CSV (default: dataset/localnet_dynamics.parquet)")
546
+ p.add_argument("--analysis", default=None,
547
+ help="analysis JSON from analyze.py (default: next to the input; recomputed if missing)")
548
+ p.add_argument("--out-dir", default=str(ROOT / "figures"))
549
+ args = p.parse_args(argv)
550
+
551
+ path = Path(args.input) if args.input else ROOT / "dataset" / "localnet_dynamics.parquet"
552
+ if not path.exists() and not args.input:
553
+ path = ROOT / "dataset" / "localnet_dynamics.csv"
554
+ if not path.exists():
555
+ raise SystemExit(f"{path} not found; run build_dataset.py first")
556
+ df = load(path)
557
+ analysis_path = Path(args.analysis) if args.analysis else path.parent / "analysis.json"
558
+ if analysis_path.exists():
559
+ a = json.loads(analysis_path.read_text(encoding="utf-8"))
560
+ else:
561
+ summary_path = path.parent / "summary.json"
562
+ summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.exists() else None
563
+ a = analyse(df, summary)
564
+ names = render_all(df, a, Path(args.out_dir))
565
+ print(f"{len(names)} figures written to {args.out_dir} (png/ and pdf/): " + ", ".join(names))
566
+ return 0
567
+
568
+
569
+ if __name__ == "__main__":
570
+ sys.exit(main())
tests/conftest.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"
5
+ if str(SCRIPTS) not in sys.path:
6
+ sys.path.insert(0, str(SCRIPTS))
tests/test_build.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end tests for build_dataset.py, annotate.py, analyze.py and plot_figures.py.
2
+
3
+ A small raw run is synthesised in a temporary directory with the collector's
4
+ own schema so that the build pipeline, label rules, event join and figure
5
+ rendering can be exercised without network access. Nothing here is written
6
+ into the repository's dataset directory.
7
+ """
8
+
9
+ import csv
10
+ import json
11
+ import math
12
+ import random
13
+ from datetime import datetime, timedelta, timezone
14
+ from pathlib import Path
15
+
16
+ import pytest
17
+
18
+ pd = pytest.importorskip("pandas")
19
+
20
+ import annotate # noqa: E402
21
+ import build_dataset as bd # noqa: E402
22
+ import collect_data as cd # noqa: E402
23
+
24
+ START = datetime(2026, 9, 6, 22, 0, 0, tzinfo=timezone.utc) # 18:00 local (UTC-4)
25
+ INTERVAL = 60
26
+ ROWS = 3 * 60 * 6 # 18 h of 1-minute samples
27
+ LOCAL_OFFSET = timedelta(hours=-4)
28
+
29
+
30
+ def write_synthetic_run(raw_dir: Path, run_id: str = "testhost_20260906_180000") -> Path:
31
+ rng = random.Random(7)
32
+ rows = []
33
+ for i in range(ROWS):
34
+ t = START + timedelta(seconds=i * INTERVAL)
35
+ if 400 <= i < 405: # simulated gap of five samples (machine asleep)
36
+ continue
37
+ s = cd.Sample(run_id=run_id, host_label="testhost", sample_index=i,
38
+ timestamp_utc=t.strftime("%Y-%m-%dT%H:%M:%SZ"),
39
+ timestamp_local=(t + LOCAL_OFFSET).strftime("%Y-%m-%dT%H:%M:%S-04:00"),
40
+ epoch_s=int(t.timestamp()), elapsed_s=float(i * INTERVAL),
41
+ link_type="wifi", gateway_ip="192.168.1.1", dns_server="192.168.1.1",
42
+ target="8.8.8.8")
43
+ base = 14.0 + 4.0 * math.sin((i / 60.0) / 24.0 * 2 * math.pi)
44
+ rtts = [max(1.0, rng.gauss(base, 1.2)) for _ in range(10)]
45
+ if i in (700, 701, 702): # simulated outage
46
+ rtts = []
47
+ elif i % 97 == 0: # occasional single lost packet
48
+ rtts = rtts[:9]
49
+ elif i == 900: # latency spike
50
+ rtts = [r + 120 for r in rtts]
51
+ st = cd.rtt_stats(rtts)
52
+ s.rtt_min_ms, s.rtt_avg_ms, s.rtt_median_ms = st["min"], st["avg"], st["median"]
53
+ s.rtt_max_ms, s.rtt_stddev_ms, s.jitter_ms = st["max"], st["stddev"], st["jitter"]
54
+ s.packets_sent, s.packets_received = 10, len(rtts)
55
+ s.packet_loss_pct = round(100.0 * (10 - len(rtts)) / 10, 1)
56
+ g = [max(0.3, rng.gauss(2.0, 0.5)) for _ in range(5)]
57
+ if i == 1000:
58
+ g = [r + 60 for r in g]
59
+ gst = cd.rtt_stats(g)
60
+ s.gateway_rtt_min_ms, s.gateway_rtt_avg_ms = gst["min"], gst["avg"]
61
+ s.gateway_rtt_max_ms, s.gateway_jitter_ms = gst["max"], gst["jitter"]
62
+ s.gateway_packet_loss_pct = 0.0
63
+ s.tcp_connect_min_ms = round(base - 0.5, 3)
64
+ s.tcp_connect_median_ms = round(base, 3)
65
+ s.dns_resolve_ms = round(rng.gauss(2.5, 0.4), 3)
66
+ s.dns_recursive_ms = round(rng.gauss(40, 8), 3)
67
+ s.http_ms, s.http_status = round(rng.gauss(60, 10), 3), 200
68
+ s.wifi_signal_pct = 80 + (i % 5)
69
+ s.wifi_rssi_dbm = cd.rssi_from_quality(s.wifi_signal_pct)
70
+ s.wifi_rx_mbps, s.wifi_tx_mbps = 866.7, 866.7
71
+ s.wifi_channel, s.wifi_band_ghz, s.wifi_phy = 36, 5.0, "802.11ax"
72
+ if i % 30 == 0:
73
+ s.download_mbps, s.upload_mbps = round(rng.gauss(450, 30), 2), round(rng.gauss(22, 2), 2)
74
+ s.speedtest_ping_ms = 1800000.0 if i == 60 else 9.5 # one failed latency probe
75
+ s.speedtest_server_id, s.speedtest_server = 1234, "Example ISP, Springfield"
76
+ s.sample_duration_s = 10.4
77
+ s.notes = "ping: no replies" if not rtts else ""
78
+ rows.append(cd.asdict(s))
79
+ raw_dir.mkdir(parents=True, exist_ok=True)
80
+ csv_path = raw_dir / f"localnet_{run_id}.csv"
81
+ with csv_path.open("w", newline="", encoding="utf-8") as f:
82
+ w = csv.DictWriter(f, fieldnames=cd.CSV_FIELDS)
83
+ w.writeheader()
84
+ w.writerows(rows)
85
+ meta = {"run_id": run_id, "collector_version": cd.COLLECTOR_VERSION, "status": "completed",
86
+ "interval_s": float(INTERVAL), "sample_count": len(rows),
87
+ "environment": {"os": "Windows-11-10.0.22631-SP0", "ping_resolution_ms": 1.0},
88
+ "network": {"link_type": "wifi"}}
89
+ csv_path.with_suffix(".json").write_text(json.dumps(meta), encoding="utf-8")
90
+ return csv_path
91
+
92
+
93
+ @pytest.fixture(scope="module")
94
+ def built(tmp_path_factory):
95
+ root = tmp_path_factory.mktemp("ds")
96
+ raw = root / "raw"
97
+ write_synthetic_run(raw)
98
+ # a manual annotation covering the simulated outage
99
+ annotate.main(["router rebooted", "--category", "maintenance",
100
+ "--start", "2026-09-07T09:39:30Z", "--end", "2026-09-07T09:43:00Z",
101
+ "--file", str(raw / "events.csv")])
102
+ card = root / "DATASET_CARD.md"
103
+ card.write_text("---\nsize_categories:\n - n<1K\n---\n# card\n\n"
104
+ f"{bd.CARD_BEGIN}\nold\n{bd.CARD_END}\n", encoding="utf-8")
105
+ bd.main(["--raw-dir", str(raw), "--out-dir", str(root), "--card", str(card)])
106
+ df = pd.read_csv(root / "localnet_dynamics.csv")
107
+ summary = json.loads((root / "summary.json").read_text(encoding="utf-8"))
108
+ return root, df, summary, card
109
+
110
+
111
+ def test_rows_and_columns(built):
112
+ root, df, summary, _ = built
113
+ assert len(df) == ROWS - 5
114
+ assert list(df.columns[:11]) == cd.CSV_FIELDS[:11]
115
+ assert df.columns[-1] == "notes"
116
+ for col in bd.RUN_COLUMNS + bd.TIME_COLUMNS + bd.LABEL_COLUMNS + bd.EVENT_COLUMNS:
117
+ assert col in df.columns
118
+ assert (root / "localnet_dynamics.parquet").exists()
119
+ assert summary["rows"] == len(df) and summary["runs"][0]["interval_s"] == 60.0
120
+ assert summary["runs"][0]["os"].startswith("Windows")
121
+ assert df["collector_os"].iloc[0] == "Windows" and df["rtt_resolution_ms"].iloc[0] == 1.0
122
+
123
+
124
+ def test_time_features_and_gaps(built):
125
+ _, df, summary, _ = built
126
+ first = df.iloc[0]
127
+ assert first["hour_local"] == 18 and first["date_local"] == "2026-09-06"
128
+ assert first["weekday_local"] == 6 and first["is_weekend"] == 1 # Sunday
129
+ gaps = df["gap_before_s"].dropna()
130
+ assert gaps.max() == 6 * INTERVAL and (gaps == INTERVAL).sum() == len(gaps) - 1
131
+ assert 99.0 < summary["coverage_pct"] < 100.0
132
+
133
+
134
+ def test_reference_labels(built):
135
+ _, df, summary, _ = built
136
+ outages = df[df["label_outage"] == 1]
137
+ assert list(outages["sample_index"]) == [700, 701, 702]
138
+ assert df.loc[df["sample_index"] == 900, "label_high_latency"].item() == 1
139
+ assert df.loc[df["sample_index"] == 1000, "label_gateway_degraded"].item() == 1
140
+ assert df.loc[df["sample_index"] == 97, "label_packet_loss"].item() == 1
141
+ assert df.loc[df["sample_index"] == 97, "label_outage"].item() == 0
142
+ assert df["label_high_latency"].sum() <= 5 # rule is not over-sensitive
143
+ assert (df["label_anomaly"] >= df["label_outage"]).all()
144
+ thr = summary["runs"][0]["thresholds"]["rtt_avg_ms"]
145
+ assert thr["threshold"] >= thr["median"] + 10.0
146
+ assert summary["labels"]["label_outage"]["rows"] == 3
147
+
148
+
149
+ def test_failed_speedtest_latency_is_missing(built):
150
+ _, df, summary, _ = built
151
+ tests = df[df["download_mbps"].notna()]
152
+ assert len(tests) == 36
153
+ assert tests["speedtest_ping_ms"].isna().sum() == 1
154
+ assert tests.loc[tests["sample_index"] == 60, "speedtest_ping_ms"].isna().all()
155
+ assert summary["metrics"]["speedtest_ping_ms"]["max"] == 9.5
156
+
157
+
158
+ def test_event_join(built):
159
+ _, df, summary, _ = built
160
+ tagged = df[df["event_category"].fillna("") != ""]
161
+ assert summary["events"] == 1
162
+ assert set(tagged["sample_index"]) == {700, 701, 702, 703}
163
+ assert (tagged["event_description"] == "router rebooted").all()
164
+
165
+
166
+ def test_card_updated(built):
167
+ _, _, summary, card = built
168
+ text = card.read_text(encoding="utf-8")
169
+ assert "old" not in text
170
+ assert f"| Rows | {summary['rows']:,} |" in text
171
+ assert "size_categories:\n - 1K<n<10K" in text
172
+ assert text.count(bd.CARD_BEGIN) == 1 and text.count(bd.CARD_END) == 1
173
+
174
+
175
+ def test_size_category():
176
+ assert bd.size_category(500) == "n<1K"
177
+ assert bd.size_category(86_400) == "10K<n<100K"
178
+ assert bd.size_category(2_000_000) == "1M<n<10M"
179
+
180
+
181
+ def test_analysis_json(built):
182
+ import analyze
183
+ root, df, summary, _ = built
184
+ analyze.main(["--input", str(root / "localnet_dynamics.csv"), "--no-report"])
185
+ a = json.loads((root / "analysis.json").read_text(encoding="utf-8"))
186
+ assert a["overview"]["rows"] == len(df)
187
+ assert len(a["hour_profile"]) == 18 and len(a["daily"]) == 2
188
+ assert len(a["outages"]) == 1 and a["outages"][0]["samples"] == 3
189
+ assert a["regimes"]["before"]["n"] + a["regimes"]["after"]["n"] == len(df)
190
+ assert a["speedtest"]["tests"] == 36 and a["speedtest"]["failed_latency_probe"] == 1
191
+ assert a["labels"]["counts"]["label_outage"] == 3
192
+ assert set(a["autocorrelation"]["values"]) >= {"log_rtt_avg_ms", "loss_indicator", "http_ms"}
193
+
194
+
195
+ def test_figures(built, tmp_path):
196
+ pytest.importorskip("matplotlib")
197
+ import plot_figures
198
+ root, _, _, _ = built
199
+ out = tmp_path / "figures"
200
+ plot_figures.main(["--input", str(root / "localnet_dynamics.csv"), "--out-dir", str(out)])
201
+ for name in ("overview_timeline", "diurnal_profile", "calendar_heatmaps", "tcp_vs_icmp",
202
+ "loss_anatomy", "regimes", "autocorrelation", "speedtest", "labels"):
203
+ assert (out / "png" / f"{name}.png").stat().st_size > 10_000, name
204
+ assert (out / "pdf" / f"{name}.pdf").stat().st_size > 1_000, name
205
+
206
+
207
+ def test_annotate_parses_local_and_utc_times():
208
+ assert annotate.parse_time("2026-09-12T16:00:00Z").isoformat() == "2026-09-12T16:00:00+00:00"
209
+ assert annotate.parse_time("2026-09-12 16:00+02:00").isoformat() == "2026-09-12T14:00:00+00:00"
210
+ local = annotate.parse_time("2026-09-12 16:00")
211
+ assert local.tzinfo == timezone.utc
tests/test_collector.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the parsing and measurement helpers in collect_data.py.
2
+
3
+ The fixtures below reproduce the output formats of the system utilities on
4
+ the platforms and locales the collector supports. They exercise the parsers
5
+ without needing network access.
6
+ """
7
+
8
+ import json
9
+ import struct
10
+
11
+ import pytest
12
+
13
+ import collect_data as cd
14
+
15
+
16
+ # --------------------------------------------------------------------------- #
17
+ # ping output
18
+ # --------------------------------------------------------------------------- #
19
+
20
+ WINDOWS_EN = """
21
+ Pinging 8.8.8.8 with 32 bytes of data:
22
+ Reply from 8.8.8.8: bytes=32 time=14ms TTL=117
23
+ Reply from 8.8.8.8: bytes=32 time<1ms TTL=117
24
+ Request timed out.
25
+ Reply from 8.8.8.8: bytes=32 time=20ms TTL=117
26
+
27
+ Ping statistics for 8.8.8.8:
28
+ Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),
29
+ Approximate round trip times in milli-seconds:
30
+ Minimum = 0ms, Maximum = 20ms, Average = 11ms
31
+ """
32
+
33
+ WINDOWS_ZH = """
34
+ 正在 Ping 8.8.8.8 具有 32 字节的数据:
35
+ 来自 8.8.8.8 的回复: 字节=32 时间=14ms TTL=117
36
+ 来自 8.8.8.8 的回复: 字节=32 时间=15ms TTL=117
37
+ 请求超时。
38
+ 来自 8.8.8.8 的回复: 字节=32 时间<1ms TTL=117
39
+
40
+ 8.8.8.8 的 Ping 统计信息:
41
+ 数据包: 已发送 = 4,已接收 = 3,丢失 = 1 (25% 丢失),
42
+ 往返行程的估计时间(以毫秒为单位):
43
+ 最短 = 0ms,最长 = 15ms,平均 = 9ms
44
+ """
45
+
46
+ WINDOWS_DE = """
47
+ Ping wird ausgeführt für 8.8.8.8 mit 32 Bytes Daten:
48
+ Antwort von 8.8.8.8: Bytes=32 Zeit=14ms TTL=117
49
+ Antwort von 8.8.8.8: Bytes=32 Zeit=15ms TTL=117
50
+
51
+ Ping-Statistik für 8.8.8.8:
52
+ Pakete: Gesendet = 2, Empfangen = 2, Verloren = 0
53
+ (0% Verlust),
54
+ Ca. Zeitangaben in Millisek.:
55
+ Minimum = 14ms, Maximum = 15ms, Mittelwert = 14ms
56
+ """
57
+
58
+ WINDOWS_FR = """
59
+ Envoi d'une requête 'Ping' 8.8.8.8 avec 32 octets de données :
60
+ Réponse de 8.8.8.8 : octets=32 temps=14 ms TTL=117
61
+ Réponse de 8.8.8.8 : octets=32 temps=16 ms TTL=117
62
+
63
+ Statistiques Ping pour 8.8.8.8:
64
+ Paquets : envoyés = 2, reçus = 2, perdus = 0 (perte 0%),
65
+ Durée approximative des boucles en millisecondes :
66
+ Minimum = 14ms, Maximum = 16ms, Moyenne = 15ms
67
+ """
68
+
69
+ WINDOWS_RU = """
70
+ Обмен пакетами с 8.8.8.8 по с 32 байтами данных:
71
+ Ответ от 8.8.8.8: число байт=32 время=14мс TTL=117
72
+ Ответ от 8.8.8.8: число байт=32 время=17мс TTL=117
73
+
74
+ Статистика Ping для 8.8.8.8:
75
+ Пакетов: отправлено = 2, получено = 2, потеряно = 0
76
+ (0% потерь)
77
+ Приблизительное время приема-передачи в мс:
78
+ Минимальное = 14мсек, Максимальное = 17 мсек, Среднее = 15 мсек
79
+ """
80
+
81
+ WINDOWS_IPV6 = """
82
+ Pinging 2001:4860:4860::8888 with 32 bytes of data:
83
+ Reply from 2001:4860:4860::8888: time=15ms
84
+ Reply from 2001:4860:4860::8888: time=14ms
85
+
86
+ Ping statistics for 2001:4860:4860::8888:
87
+ Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
88
+ Approximate round trip times in milli-seconds:
89
+ Minimum = 14ms, Maximum = 15ms, Average = 14ms
90
+ """
91
+
92
+ WINDOWS_UNREACHABLE = """
93
+ Pinging 10.9.9.9 with 32 bytes of data:
94
+ Reply from 192.168.1.23: Destination host unreachable.
95
+ Reply from 192.168.1.23: Destination host unreachable.
96
+ PING: transmit failed. General failure.
97
+
98
+ Ping statistics for 10.9.9.9:
99
+ Packets: Sent = 3, Received = 2, Lost = 1 (33% loss),
100
+ """
101
+
102
+ LINUX = """
103
+ PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
104
+ 64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=14.2 ms
105
+ 64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=13.9 ms
106
+ 64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=14.1 ms (DUP!)
107
+ From 192.168.1.1 icmp_seq=3 Destination Host Unreachable
108
+ 64 bytes from 8.8.8.8: icmp_seq=4 ttl=117 time=15.0 ms
109
+
110
+ --- 8.8.8.8 ping statistics ---
111
+ 4 packets transmitted, 3 received, +1 duplicates, 25% packet loss, time 3004ms
112
+ rtt min/avg/max/mdev = 13.900/14.367/15.000/0.464 ms
113
+ """
114
+
115
+ MACOS = """
116
+ PING 8.8.8.8 (8.8.8.8): 56 data bytes
117
+ 64 bytes from 8.8.8.8: icmp_seq=0 ttl=117 time=14.234 ms
118
+ 64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=13.877 ms
119
+ Request timeout for icmp_seq 2
120
+ 64 bytes from 8.8.8.8: icmp_seq=3 ttl=117 time=15.001 ms
121
+
122
+ --- 8.8.8.8 ping statistics ---
123
+ 4 packets transmitted, 3 packets received, 25.0% packet loss
124
+ round-trip min/avg/max/stddev = 13.877/14.371/15.001/0.478 ms
125
+ """
126
+
127
+ BUSYBOX = """
128
+ PING 8.8.8.8 (8.8.8.8): 56 data bytes
129
+ 64 bytes from 8.8.8.8: seq=0 ttl=117 time=14.210 ms
130
+ 64 bytes from 8.8.8.8: seq=1 ttl=117 time=13.905 ms
131
+
132
+ --- 8.8.8.8 ping statistics ---
133
+ 2 packets transmitted, 2 packets received, 0% packet loss
134
+ round-trip min/avg/max = 13.905/14.057/14.210 ms
135
+ """
136
+
137
+
138
+ @pytest.mark.parametrize("text, sent, expected", [
139
+ (WINDOWS_EN, 4, [14.0, 0.0, 20.0]),
140
+ (WINDOWS_ZH, 4, [14.0, 15.0, 0.0]),
141
+ (WINDOWS_DE, 2, [14.0, 15.0]),
142
+ (WINDOWS_FR, 2, [14.0, 16.0]),
143
+ (WINDOWS_RU, 2, [14.0, 17.0]),
144
+ (WINDOWS_IPV6, 2, [15.0, 14.0]),
145
+ (WINDOWS_UNREACHABLE, 3, []),
146
+ (LINUX, 4, [14.2, 13.9, 15.0]),
147
+ (MACOS, 4, [14.234, 13.877, 15.001]),
148
+ (BUSYBOX, 2, [14.21, 13.905]),
149
+ ])
150
+ def test_parse_ping_output(text, sent, expected):
151
+ result = cd.parse_ping_output(text, sent=sent)
152
+ assert result.rtts == expected
153
+ assert result.received == len(expected)
154
+ assert result.sent == sent
155
+ assert result.loss_pct == round(100.0 * (sent - len(expected)) / sent, 1)
156
+
157
+
158
+ def test_loss_is_clamped_and_none_when_nothing_sent():
159
+ assert cd.PingResult(sent=0, received=0).loss_pct is None
160
+ assert cd.PingResult(sent=2, received=5).loss_pct == 0.0
161
+
162
+
163
+ def test_rtt_stats():
164
+ st = cd.rtt_stats([10.0, 12.0, 11.0, 15.0])
165
+ assert st["min"] == 10.0 and st["max"] == 15.0
166
+ assert st["avg"] == 12.0 and st["median"] == 11.5
167
+ assert st["jitter"] == round((2 + 1 + 4) / 3, 3)
168
+ assert st["stddev"] == pytest.approx(1.871, abs=1e-3)
169
+ assert cd.rtt_stats([]) == {k: None for k in ("min", "avg", "median", "max", "stddev", "jitter")}
170
+ single = cd.rtt_stats([7.0])
171
+ assert single["jitter"] is None and single["stddev"] == 0.0
172
+
173
+
174
+ def test_ping_command_flags():
175
+ assert cd.ping_command("8.8.8.8", 10, 2.0, "windows") == \
176
+ ["ping", "-n", "10", "-w", "2000", "-4", "8.8.8.8"]
177
+ assert cd.ping_command("2001:db8::1", 3, 2.0, "windows")[-2] == "-6"
178
+ assert cd.ping_command("8.8.8.8", 10, 2.0, "iputils") == \
179
+ ["ping", "-n", "-c", "10", "-W", "2", "8.8.8.8"]
180
+ assert cd.ping_command("8.8.8.8", 4, 0.4, "iputils")[5] == "1"
181
+ assert cd.ping_command("8.8.8.8", 10, 2.0, "busybox") == \
182
+ ["ping", "-c", "10", "-W", "2", "8.8.8.8"]
183
+ assert cd.ping_command("8.8.8.8", 10, 2.5, "bsd") == \
184
+ ["ping", "-n", "-c", "10", "-W", "2500", "8.8.8.8"]
185
+
186
+
187
+ # --------------------------------------------------------------------------- #
188
+ # routes, resolvers, interfaces
189
+ # --------------------------------------------------------------------------- #
190
+
191
+ ROUTE_PRINT = """
192
+ ===========================================================================
193
+ Interface List
194
+ 12...00 11 22 33 44 55 ......Intel(R) Wi-Fi 6 AX201 160MHz
195
+ ===========================================================================
196
+
197
+ IPv4 Route Table
198
+ ===========================================================================
199
+ Active Routes:
200
+ Network Destination Netmask Gateway Interface Metric
201
+ 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.23 35
202
+ 0.0.0.0 0.0.0.0 10.10.0.1 10.10.0.5 50
203
+ ===========================================================================
204
+ Persistent Routes:
205
+ Network Address Netmask Gateway Address Metric
206
+ 0.0.0.0 0.0.0.0 192.168.1.1 Default
207
+ ===========================================================================
208
+ """
209
+
210
+
211
+ def test_parse_route_print_picks_lowest_metric():
212
+ assert cd.parse_route_print(ROUTE_PRINT) == ("192.168.1.1", "192.168.1.23")
213
+ assert cd.parse_route_print("no routes here") is None
214
+
215
+
216
+ def test_parse_ip_route_get():
217
+ text = "8.8.8.8 via 192.168.1.1 dev wlp3s0 src 192.168.1.50 uid 1000 \\ cache \n"
218
+ assert cd.parse_ip_route_get(text) == {"via": "192.168.1.1", "dev": "wlp3s0", "src": "192.168.1.50"}
219
+ assert cd.parse_ip_route_get("default via 10.0.0.1 dev eth0 proto dhcp metric 100") == \
220
+ {"via": "10.0.0.1", "dev": "eth0"}
221
+
222
+
223
+ def test_parse_resolv_conf():
224
+ text = "# generated\nsearch lan\nnameserver 127.0.0.53 # stub\nnameserver 192.168.1.1\noptions edns0\n"
225
+ assert cd.parse_resolv_conf(text) == ["127.0.0.53", "192.168.1.1"]
226
+
227
+
228
+ def test_parse_route_get_default_macos():
229
+ text = """ route to: default
230
+ destination: default
231
+ mask: default
232
+ gateway: 192.168.1.1
233
+ interface: en0
234
+ flags: <UP,GATEWAY,DONE,STATIC,PRCLONING,GLOBAL>
235
+ """
236
+ assert cd.parse_route_get_default(text) == {"gateway": "192.168.1.1", "interface": "en0"}
237
+
238
+
239
+ def test_parse_hardware_ports():
240
+ text = """Hardware Port: Wi-Fi
241
+ Device: en0
242
+ Ethernet Address: 00:11:22:33:44:55
243
+
244
+ Hardware Port: Thunderbolt Ethernet
245
+ Device: en5
246
+ Ethernet Address: 66:77:88:99:aa:bb
247
+ """
248
+ assert cd.parse_hardware_ports(text) == {"en0": "Wi-Fi", "en5": "Thunderbolt Ethernet"}
249
+
250
+
251
+ def test_link_type_from_media():
252
+ assert cd._link_type_from_media("Native 802.11") == "wifi"
253
+ assert cd._link_type_from_media("802.3") == "ethernet"
254
+ assert cd._link_type_from_media("Unspecified") == "unknown"
255
+ assert cd._link_type_from_media("") == "unknown"
256
+ assert cd._link_type_from_media("BlueTooth") == "other"
257
+
258
+
259
+ # --------------------------------------------------------------------------- #
260
+ # DNS packets
261
+ # --------------------------------------------------------------------------- #
262
+
263
+ def test_dns_query_roundtrip():
264
+ packet = cd.build_dns_query("example.com", qid=0x1234)
265
+ qid, flags, qd, an, ns, ar = struct.unpack(">HHHHHH", packet[:12])
266
+ assert (qid, flags, qd, an, ns, ar) == (0x1234, 0x0100, 1, 0, 0, 0)
267
+ assert packet[12:] == b"\x07example\x03com\x00" + struct.pack(">HH", 1, 1)
268
+
269
+ response = struct.pack(">HHHHHH", 0x1234, 0x8183, 1, 0, 0, 0) + packet[12:]
270
+ assert cd.parse_dns_response(response, 0x1234) == 3 # NXDOMAIN
271
+ other = struct.pack(">HHHHHH", 0x9999, 0x8180, 1, 0, 0, 0)
272
+ assert cd.parse_dns_response(other, 0x1234) is None # wrong id
273
+ assert cd.parse_dns_response(packet, 0x1234) is None # a query, not a response
274
+ assert cd.parse_dns_response(b"\x00", 0x1234) is None
275
+
276
+
277
+ def test_random_label_is_hex():
278
+ label = cd.random_label()
279
+ assert len(label) == 12 and int(label, 16) >= 0
280
+
281
+
282
+ # --------------------------------------------------------------------------- #
283
+ # Wi-Fi parsers
284
+ # --------------------------------------------------------------------------- #
285
+
286
+ NETSH_EN = """
287
+ There is 1 interface on the system:
288
+
289
+ Name : Wi-Fi
290
+ Description : Intel(R) Wi-Fi 6 AX201 160MHz
291
+ GUID : 4d1a2b3c-0000-1111-2222-333344445555
292
+ Physical address : 00:11:22:33:44:55
293
+ Interface type : Primary
294
+ State : connected
295
+ SSID : Home:Net
296
+ BSSID : aa:bb:cc:dd:ee:ff
297
+ Network type : Infrastructure
298
+ Radio type : 802.11ax
299
+ Authentication : WPA2-Personal
300
+ Cipher : CCMP
301
+ Connection mode : Auto Connect
302
+ Band : 5 GHz
303
+ Channel : 36
304
+ Receive rate (Mbps) : 1200.9
305
+ Transmit rate (Mbps) : 1200.9
306
+ Signal : 84%
307
+ Profile : Home:Net
308
+
309
+ Hosted network status : Not available
310
+ """
311
+
312
+ NETSH_ZH = """
313
+ 系统上有 1 个接口:
314
+
315
+ 名称 : WLAN
316
+ 描述 : Intel(R) Wi-Fi 6 AX201 160MHz
317
+ GUID : 4d1a2b3c-0000-1111-2222-333344445555
318
+ 物理地址 : 00:11:22:33:44:55
319
+ 接口类型 : 主要
320
+ 状态 : 已连接
321
+ SSID : 家里的WiFi
322
+ BSSID : aa:bb:cc:dd:ee:ff
323
+ 网络类型 : 结构
324
+ 无线电类型 : 802.11ac
325
+ 身份验证 : WPA2 - 个人
326
+ 密码 : CCMP
327
+ 连接模式 : 自动连接
328
+ 信道 : 149
329
+ 接收速率(Mbps) : 866.7
330
+ 传输速率(Mbps) : 866.7
331
+ 信号 : 91%
332
+ 配置文件 : 家里的WiFi
333
+
334
+ 承载网络状态 : 不可用
335
+ """
336
+
337
+ NETSH_DISCONNECTED = """
338
+ There is 1 interface on the system:
339
+
340
+ Name : Wi-Fi
341
+ Description : Intel(R) Wi-Fi 6 AX201 160MHz
342
+ GUID : 4d1a2b3c-0000-1111-2222-333344445555
343
+ Physical address : 00:11:22:33:44:55
344
+ Interface type : Primary
345
+ State : disconnected
346
+ Radio status : Hardware On
347
+ Software On
348
+
349
+ Hosted network status : Not available
350
+ """
351
+
352
+
353
+ def test_parse_netsh_english():
354
+ w = cd.parse_netsh_wlan(NETSH_EN)
355
+ assert w.connected and w.ssid == "Home:Net"
356
+ assert w.signal_pct == 84 and w.rssi_dbm == -58.0
357
+ assert w.rx_mbps == 1200.9 and w.tx_mbps == 1200.9
358
+ assert w.channel == 36 and w.band_ghz == 5.0 and w.phy == "802.11ax"
359
+
360
+
361
+ def test_parse_netsh_chinese_without_band_line():
362
+ w = cd.parse_netsh_wlan(NETSH_ZH)
363
+ assert w.connected and w.ssid == "家里的WiFi"
364
+ assert w.signal_pct == 91 and w.rssi_dbm == -54.5
365
+ assert w.rx_mbps == 866.7 and w.tx_mbps == 866.7
366
+ assert w.channel == 149 and w.band_ghz == 5.0 and w.phy == "802.11ac"
367
+
368
+
369
+ def test_parse_netsh_disconnected():
370
+ w = cd.parse_netsh_wlan(NETSH_DISCONNECTED)
371
+ assert not w.connected and w.signal_pct is None
372
+
373
+
374
+ IW_LINK = """Connected to aa:bb:cc:dd:ee:ff (on wlp3s0)
375
+ \tSSID: HomeNet
376
+ \tfreq: 5180
377
+ \tRX: 123456 bytes (789 packets)
378
+ \tTX: 23456 bytes (234 packets)
379
+ \tsignal: -55 dBm
380
+ \trx bitrate: 866.7 MBit/s VHT-MCS 9 80MHz short GI VHT-NSS 2
381
+ \ttx bitrate: 780.0 MBit/s VHT-MCS 8 80MHz short GI VHT-NSS 2
382
+
383
+ \tbss flags:\tshort-slot-time
384
+ \tdtim period:\t1
385
+ \tbeacon int:\t100
386
+ """
387
+
388
+
389
+ def test_parse_iw_link():
390
+ w = cd.parse_iw_link(IW_LINK)
391
+ assert w.connected and w.ssid == "HomeNet"
392
+ assert w.channel == 36 and w.band_ghz == 5.0
393
+ assert w.rssi_dbm == -55.0 and w.signal_pct == 90
394
+ assert w.rx_mbps == 866.7 and w.tx_mbps == 780.0 and w.phy == "802.11ac"
395
+ assert not cd.parse_iw_link("Not connected.\n").connected
396
+ ht = cd.parse_iw_link("Connected to x (on w)\n\tSSID: n\n\tfreq: 2437\n\ttx bitrate: 72.2 MBit/s MCS 7 short GI\n")
397
+ assert ht.phy == "802.11n" and ht.channel == 6 and ht.band_ghz == 2.4
398
+
399
+
400
+ def test_parse_proc_net_wireless():
401
+ text = ("Inter-| sta-| Quality | Discarded packets | Missed | WE\n"
402
+ " face | tus | link level noise | nwid crypt frag retry misc | beacon | 22\n"
403
+ " wlan0: 0000 60. -50. -256 0 0 0 0 0 0\n")
404
+ w = cd.parse_proc_net_wireless(text, "wlan0")
405
+ assert w.connected and w.rssi_dbm == -50.0 and w.signal_pct == 100
406
+ assert not cd.parse_proc_net_wireless(text, "wlan1").connected
407
+
408
+
409
+ def test_parse_system_profiler():
410
+ data = {"SPAirPortDataType": [{"spairport_airport_interfaces": [{
411
+ "_name": "en0",
412
+ "spairport_current_network_information": {
413
+ "_name": "HomeNet",
414
+ "spairport_network_channel": "44 (5GHz, 80MHz)",
415
+ "spairport_network_phymode": "802.11ax",
416
+ "spairport_network_rate": 1200,
417
+ "spairport_signal_noise": "-52 dBm / -92 dBm",
418
+ }}]}]}
419
+ w = cd.parse_system_profiler_airport(data)
420
+ assert w.connected and w.ssid == "HomeNet" and w.channel == 44 and w.band_ghz == 5.0
421
+ assert w.phy == "802.11ax" and w.rx_mbps == 1200 and w.rssi_dbm == -52.0
422
+ assert not cd.parse_system_profiler_airport({}).connected
423
+
424
+
425
+ def test_channel_and_rssi_helpers():
426
+ assert cd.channel_from_freq_mhz(2412) == (1, 2.4)
427
+ assert cd.channel_from_freq_mhz(2484) == (14, 2.4)
428
+ assert cd.channel_from_freq_mhz(5745) == (149, 5.0)
429
+ assert cd.channel_from_freq_mhz(5955) == (1, 6.0)
430
+ assert cd.channel_from_freq_mhz(1000) == (None, None)
431
+ assert cd.rssi_from_quality(100) == -50.0 and cd.rssi_from_quality(0) == -100.0
432
+ assert cd.quality_from_rssi(-75) == 50 and cd.quality_from_rssi(-120) == 0
433
+ assert cd.band_from_channel(11) == 2.4 and cd.band_from_channel(100) == 5.0
434
+
435
+
436
+ # --------------------------------------------------------------------------- #
437
+ # throughput tool output
438
+ # --------------------------------------------------------------------------- #
439
+
440
+ def test_parse_ookla_json():
441
+ data = {"type": "result",
442
+ "ping": {"jitter": 0.6, "latency": 9.5},
443
+ "download": {"bandwidth": 58231421, "latency": {"iqm": 21.3}},
444
+ "upload": {"bandwidth": 2500000, "latency": {"iqm": 45.0}},
445
+ "server": {"id": 1234, "name": "Example ISP", "location": "Springfield"}}
446
+ r = cd.parse_ookla_json(data)
447
+ assert r["download_mbps"] == pytest.approx(465.85, abs=0.01)
448
+ assert r["upload_mbps"] == 20.0
449
+ assert r["speedtest_ping_ms"] == 9.5
450
+ assert r["download_loaded_latency_ms"] == 21.3 and r["upload_loaded_latency_ms"] == 45.0
451
+ assert r["speedtest_server_id"] == 1234 and r["speedtest_server"] == "Example ISP, Springfield"
452
+
453
+
454
+ class _FakeResults:
455
+ ping = 1800000.0
456
+ server = {"id": 42, "sponsor": "Example ISP", "name": "Springfield"}
457
+
458
+
459
+ class _FakeSpeedtest:
460
+ def __init__(self, secure=True):
461
+ self.results = _FakeResults()
462
+
463
+ def get_servers(self, ids):
464
+ pass
465
+
466
+ def get_best_server(self):
467
+ pass
468
+
469
+ def download(self):
470
+ return 120e6
471
+
472
+ def upload(self, pre_allocate=False):
473
+ return 20e6
474
+
475
+
476
+ def test_speedtest_cli_failed_latency_probe(monkeypatch):
477
+ import sys
478
+ import types
479
+ module = types.ModuleType("speedtest")
480
+ module.Speedtest = _FakeSpeedtest
481
+ monkeypatch.setitem(sys.modules, "speedtest", module)
482
+ monkeypatch.setattr(cd, "_ookla_cli_path", lambda: None)
483
+ out = cd.run_speedtest()
484
+ assert out["download_mbps"] == 120.0 and out["upload_mbps"] == 20.0
485
+ assert "speedtest_ping_ms" not in out
486
+ assert out["error"] == "speedtest-cli: server latency probe failed"
487
+ assert out["speedtest_server"] == "Example ISP, Springfield"
488
+ _FakeResults.ping = 23.4
489
+ out = cd.run_speedtest()
490
+ assert out["speedtest_ping_ms"] == 23.4 and "error" not in out
491
+
492
+
493
+ def test_iperf_json_parsing(monkeypatch):
494
+ payload = {"end": {"sum_sent": {"bits_per_second": 9.4e8, "retransmits": 12},
495
+ "sum_received": {"bits_per_second": 9.38e8}}}
496
+ monkeypatch.setattr(cd.shutil, "which", lambda name: "/usr/bin/iperf3")
497
+ monkeypatch.setattr(cd, "run_cmd", lambda *a, **k: (0, json.dumps(payload)))
498
+ assert cd.run_iperf3("10.0.0.2", 5201, 10, False) == {"lan_throughput_mbps": 938.0, "lan_retransmits": 12}
499
+ monkeypatch.setattr(cd, "run_cmd", lambda *a, **k: (1, json.dumps({"error": "unable to connect"})))
500
+ assert "unable to connect" in cd.run_iperf3("10.0.0.2", 5201, 10, False)["error"]
501
+
502
+
503
+ # --------------------------------------------------------------------------- #
504
+ # configuration helpers
505
+ # --------------------------------------------------------------------------- #
506
+
507
+ def test_parse_duration():
508
+ assert cd.parse_duration("90") == 90
509
+ assert cd.parse_duration("30s") == 30
510
+ assert cd.parse_duration("1.5h") == 5400
511
+ assert cd.parse_duration("7d") == 7 * 86400
512
+ with pytest.raises(Exception):
513
+ cd.parse_duration("1w")
514
+
515
+
516
+ def test_human_duration():
517
+ assert cd.human_duration(0) == "0s"
518
+ assert cd.human_duration(90) == "1m 30s"
519
+ assert cd.human_duration(7 * 86400 + 3600) == "7d 1h"
520
+
521
+
522
+ def test_sanitize_label():
523
+ assert cd.sanitize_label(" laptop wifi/5G ") == "laptop-wifi-5G"
524
+ assert cd.sanitize_label("") == ""
525
+
526
+
527
+ def test_csv_fields_match_dataclass():
528
+ assert cd.CSV_FIELDS[0] == "run_id" and cd.CSV_FIELDS[-1] == "notes"
529
+ assert len(cd.CSV_FIELDS) == len(set(cd.CSV_FIELDS))
530
+ for key in cd.SUMMARY_KEYS:
531
+ assert key in cd.CSV_FIELDS