Datasets:
LocalNet-Dynamics 1.0.0
Browse filesFiles changed (40)
- .gitattributes+5
- CITATION.cffAdded+30
- LICENSEAdded+21
- README.mdAdded+627
- dataset/analysis.jsonAdded+1504
- dataset/localnet_dynamics.csvAdded+3
- dataset/localnet_dynamics.parquetAdded+3
- dataset/raw/localnet_desktop-eth_20260920_123407.csvAdded+3
- dataset/raw/localnet_desktop-eth_20260920_123407.jsonAdded+220
- dataset/summary.jsonAdded+231
- figures/pdf/autocorrelation.pdfAdded
- figures/pdf/calendar_heatmaps.pdfAdded
- figures/pdf/degradation_anatomy.pdfAdded
- figures/pdf/diurnal_profile.pdfAdded
- figures/pdf/labels.pdfAdded
- figures/pdf/loss_anatomy.pdfAdded
- figures/pdf/overview_timeline.pdfAdded+3
- figures/pdf/regimes.pdfAdded+3
- figures/pdf/speedtest.pdfAdded
- figures/pdf/tcp_vs_icmp.pdfAdded+3
- figures/png/autocorrelation.pngAdded
- figures/png/calendar_heatmaps.pngAdded
- figures/png/degradation_anatomy.pngAdded
- figures/png/diurnal_profile.pngAdded
- figures/png/labels.pngAdded
- figures/png/loss_anatomy.pngAdded
- figures/png/overview_timeline.pngAdded
- figures/png/regimes.pngAdded
- figures/png/speedtest.pngAdded
- figures/png/tcp_vs_icmp.pngAdded
- requirements.txtAdded+9
- scripts/analyze.pyAdded+557
- scripts/annotate.pyAdded+108
- scripts/build_dataset.pyAdded+429
- scripts/collect_data.pyAdded+1583
- scripts/package_huggingface.pyAdded+126
- scripts/plot_figures.pyAdded+570
- tests/conftest.pyAdded+6
- tests/test_build.pyAdded+211
- tests/test_collector.pyAdded+531
57 unmodified lines585960616263646557 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdataset/localnet_dynamics.csv filter=lfs diff=lfs merge=lfs -textdataset/raw/localnet_desktop-eth_20260920_123407.csv filter=lfs diff=lfs merge=lfs -textfigures/pdf/overview_timeline.pdf filter=lfs diff=lfs merge=lfs -textfigures/pdf/regimes.pdf filter=lfs diff=lfs merge=lfs -textfigures/pdf/tcp_vs_icmp.pdf filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930cff-version: 1.2.0
message: "If you use this dataset, please cite it as below. The toolkit that produced it has its own citation in the source repository."
type: dataset
title: "LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset"
authors:
- family-names: "Ezharjan"
given-names: "Alexander"
version: 1.0.0
date-released: "2026-10-09"
license: MIT
url: "https://huggingface.co/datasets/ezharjan/LocalNetDynamics"
repository-code: "https://github.com/Ezharjan/LocalNetDynamicsDataset"
abstract: >-
A longitudinal telemetry dataset of a residential local area network,
sampled every 30 seconds around the clock from a wired desktop for 19 days.
Each sample records ICMP latency, jitter and loss to a reference host and to
the gateway, TCP connect time, cached and recursive DNS response time, HTTP
time-to-first-response and hourly WAN throughput tests, with time-of-day
features and rule-based reference labels for forecasting, anomaly detection
and quality-of-service research.
keywords:
- network telemetry
- latency
- jitter
- packet loss
- DNS
- throughput
- quality of service
- anomaly detection
- time series123456789101112131415161718192021MIT License
Copyright (c) 2026 Alexander Ezharjan
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627---
pretty_name: LocalNet-Dynamics
license: mit
language:
- en
tags:
- tabular
- timeseries
- networking
- telemetry
- latency
- jitter
- packet-loss
- dns
- wifi
- throughput
- qos
- anomaly-detection
task_categories:
- time-series-forecasting
- tabular-classification
- tabular-regression
annotations_creators:
- machine-generated
source_datasets:
- original
size_categories:
- 10K<n<100K
configs:
- config_name: default
data_files:
- split: train
path: dataset/localnet_dynamics.parquet
---
# LocalNet-Dynamics
A longitudinal, high-resolution telemetry dataset of a residential local area
network, sampled every 30 seconds around the clock from a wired desktop for
19 days (2026-09-20 to 2026-10-09). Each of the 54,617 rows is one sampling
epoch and combines ICMP latency, loss and jitter to a reference host and to
the gateway, TCP connect time, cached and recursive DNS response time, HTTP
time-to-first-response and hourly WAN throughput tests with time-of-day
features and rule-based reference labels.
- Author and point of contact: Alexander Ezharjan
- Dataset: https://huggingface.co/datasets/ezharjan/LocalNetDynamics
- Source code (collector, build pipeline, analysis): https://github.com/Ezharjan/LocalNetDynamicsDataset
- License: MIT (code and data)
- Version: 1.0.0
## Intended uses
- Time-series forecasting of latency, jitter and loss. The capture shows
strong persistence (lag-1 autocorrelation of the log round-trip time 0.81,
still 0.42 after three hours) and almost no 24-hour periodicity (0.09 at a
one-day lag), so it rewards models that track regime changes rather than
seasonal ones.
- Unsupervised and semi-supervised anomaly detection, evaluated against the
reference labels and the episode tables in `dataset/analysis.json`.
- QoS classification (for example, whether a sample meets the requirements of
real-time voice, cloud gaming or video conferencing).
- Root-cause studies: the gateway probe, the TCP probe and the
cached-versus-recursive DNS timings make it possible to separate first-hop
degradation from path changes and from resolver degradation. The capture
contains worked examples of each.
- Studies of the relationship between ICMP loss and application-visible
latency (HTTP retransmission modes, DNS tails).
## Collection site
| Item | Value |
|---|---|
| Vantage point | one desktop PC, host label `desktop-eth` |
| Link between client and router | wired Ethernet (the collector could not read the media type, see the limitations) |
| Client operating system | Windows 11 (build 26200), Python 3.12.12 |
| Gateway and resolver | the home router, a private address on the `192.168.1.0/24` LAN |
| Time zone | US Eastern, UTC-4 for the whole run |
| Reference host | `8.8.8.8` (ICMP and TCP port 443) |
| Access technology, advertised plan, router model | not recorded |
| Household usage during the run | normal use, not annotated |
## Files
| File | Content |
|---|---|
| `dataset/localnet_dynamics.parquet` | consolidated dataset, one row per sample, typed columns (the file served by the dataset viewer) |
| `dataset/localnet_dynamics.csv` | the same table as CSV |
| `dataset/summary.json` | row counts, coverage, per-metric statistics, per-run label thresholds |
| `dataset/analysis.json` | every number quoted in this card: profiles, regimes, episodes, conditional statistics, autocorrelation, speed-test quality |
| `dataset/raw/localnet_desktop-eth_20260920_123407.csv` | raw measurements of the collection run, exactly as written by the collector |
| `dataset/raw/localnet_desktop-eth_20260920_123407.json` | configuration, environment, detected network and running summary of that run |
| `figures/png/`, `figures/pdf/` | the ten figures below, as 200 dpi PNG and as vector PDF |
| `scripts/` | collector, builder, annotation tool, analysis, plotting and packaging scripts |
| `tests/` | pytest suite |
The consolidated files are produced from the raw files by
`scripts/build_dataset.py`; the raw files are never edited. No manual event
annotations were recorded during this run, so there is no `events.csv`.
## Findings
The numbers in this section are computed by `scripts/analyze.py` and stored in
`dataset/analysis.json`.
### Overview

54,617 samples from 2026-09-20 12:34 to 2026-10-09 15:49 local time, 99.1 % of
the samples expected at the 30-second interval. 345 gaps are exactly 60 s,
the tick skipped after an hourly speed test; 78 gaps are longer, up to 122 s,
53 of them after a speed test that overran two ticks and the rest after
samples whose probes waited for their timeouts. The median round-trip time
to 8.8.8.8 is 11.1 ms (95th percentile 22.3 ms), the median first-hop
round-trip time 0.2 ms, the median TCP handshake 14.5 ms.
### Two regimes
A single least-squares change point in the daily share of samples with ICMP
loss falls on 2026-09-30 and divides the capture into two ten-day halves:
| | Sep 20 to Sep 29 | Sep 30 to Oct 9 |
|---|---|---|
| samples | 27,020 | 27,597 |
| samples with at least one lost echo | 23.2 % | 5.3 % |
| mean packet loss | 2.98 % | 0.57 % |
| round-trip time, median / p95 / p99 | 11.9 / 24.3 / 28.4 ms | 10.8 / 14.2 / 25.5 ms |
| jitter, median / p95 | 2.22 / 9.22 ms | 0.78 / 4.56 ms |
| HTTP response, median / p95 | 87.7 / 1,094 ms | 77.6 / 157 ms |
| HTTP responses slower than 1 s | 5.87 % | 1.09 % |
| recursive DNS, median | 62.5 ms | 56.2 ms |
| samples with any label | 38.9 % | 9.2 % |


### Loss: daytime, weekdays, upstream of the gateway


14.1 % of all samples lost at least one of their ten echoes; 6,309 lost
exactly one, 1,092 two, 230 three, 41 four. On weekdays the hourly share of
samples with loss rises from 6 to 8 % between midnight and 05:00 to 25.2 % at
08:00 and stays above 20 % until 16:00; on weekends it stays between 6 % and
14 % all day. Weekdays as a whole have 15.2 % of samples with loss, weekends
10.5 %. Outside the four outages, the gateway lost a packet in exactly one
sample, so the loss sits beyond the first hop.

Loss is only weakly bursty: a sample that follows a lossy sample is lossy with
probability 0.30 against a base rate of 0.14, and the autocorrelation of the
loss indicator is 0.18 at lag 1. The other probes show what a lost echo means:
| | no loss | 1 of 10 lost | 2 or more lost |
|---|---|---|---|
| samples | 46,907 | 6,309 | 1,383 |
| round-trip time, median | 11.0 ms | 11.8 ms | 12.6 ms |
| jitter, median | 1.00 ms | 2.12 ms | 3.29 ms |
| TCP handshake, median | 14.5 ms | 14.3 ms | 14.4 ms |
| HTTP responses slower than 1 s | 2.54 % | 7.47 % | 16.34 % |
| recursive DNS slower than 200 ms | 1.75 % | 5.22 % | 9.60 % |
The HTTP response time has a smooth body with a median of 81.9 ms and a 95th
percentile of 271 ms, then discrete modes: 2.48 % of responses fall between
1.0 and 1.4 s and 0.55 % between 3.9 and 4.4 s. Their timing matches the
retransmission timers of the operating system's DNS client and TCP stack (one
second, then multiples of it), and they occur three to six times more often in
samples that also lost an echo, so they are lost packets waiting out a timer
rather than slow servers: the mechanism by which an echo lost in a ten-second
burst becomes a one-second stall for an application.
### Latency episodes: path changes and a first-hop event

Runs of the high-latency label, merged across gaps of up to ten samples, give
nine episodes of 30 minutes or more; they contain 88.4 % of all high-latency
labels. Each is classified from the probe that moved: *first hop* if the
median gateway round-trip time exceeds the run's gateway threshold (5.2 ms),
*path change* if the median minimum ICMP time or the median fastest TCP
handshake rises at least 5 ms above its run median (10.0 and 12.3 ms), and
*queueing* otherwise.
| start (local) | end (local) | hours | ICMP min | ICMP mean | TCP fastest | gateway | kind |
|---|---|---|---|---|---|---|---|
| Mon Sep 21 22:34 | Tue Sep 22 01:05 | 2.52 | 20.0 | 26.4 | 25.7 | 0.0 | path change |
| Tue Sep 22 01:27 | 02:41 | 1.23 | 10.0 | 20.4 | 20.1 | 0.0 | path change |
| Tue Sep 22 02:47 | 03:44 | 0.95 | 11.0 | 21.1 | 19.5 | 0.0 | path change |
| Thu Sep 24 23:51 | Fri Sep 25 01:16 | 1.42 | 11.0 | 22.3 | 20.1 | 0.0 | path change |
| Sat Sep 26 14:07 | 14:54 | 0.78 | 14.0 | 23.5 | 18.1 | 11.4 | first hop |
| Sat Sep 26 15:01 | 15:32 | 0.52 | 14.0 | 22.0 | 18.1 | 11.2 | first hop |
| Sat Sep 26 16:36 | 18:17 | 1.68 | 14.0 | 23.7 | 20.7 | 10.6 | first hop |
| Sun Sep 27 00:00 | 06:16 | 6.28 | 17.0 | 25.6 | 23.8 | 0.0 | path change |
| Tue Sep 29 21:21 | Wed Sep 30 07:34 | 10.22 | 20.0 | 24.8 | 24.5 | 0.0 | path change |
Values are medians over the episode, in milliseconds; an end time without a
date is on the start date. The six path changes fall on four nights and all
lie between 21:21 and 07:34. In every one of them the fastest TCP handshake
sits 7 to 13 ms above its 12.3 ms baseline, the gateway is untouched, and the
DNS probe, whose queries the gateway forwards to the upstream resolver, stays
within 4 ms of its 36 ms median, so the extra delay lies on the route towards
8.8.8.8, beyond the first hop and beyond the point where the path to the
resolver branches off. The three first-hop episodes are one event on the
afternoon of Saturday September 26: the gateway answered in 10 to 11 ms
instead of 0.2 ms, every other probe inherited the delay, and that day holds
507 of the 560 gateway-degraded labels.
### Outages
| start (local) | duration | samples | gateway reachable |
|---|---|---|---|
| Mon Sep 21 13:03 | 2.0 min | 4 | no |
| Thu Sep 24 07:10 | 2.5 min | 5 | no |
| Sat Sep 26 13:11 | 2.5 min | 5 | no |
| Tue Oct 6 02:51 | 2.0 min | 4 | no |
Every outage took the gateway down together with the target, with name
resolution failing as well (`getaddrinfo failed` in the `notes` column), so
all four were first-hop events. The ISP path never failed on its own during
the capture. Outages account for 18 samples, 0.03 % of the dataset.
### The TCP/ICMP split

Over the whole capture the fastest TCP handshake exceeds the minimum ICMP time
by 2.27 ms (median). From 22:00 on October 6 the share of samples in which it
exceeds it by more than 5 ms jumps from 7.2 % to 63.7 %, and the fastest
handshake becomes bimodal (first quartile 12.9 ms, median 18.6 ms, third
quartile 22.2 ms) while the ICMP minimum stays at 10 ms. The ICMP and TCP
probes address the same host, so the difference is in how the two kinds of
flow are routed; a monitor that relies on ping alone would not see the change.
### DNS
The "cached" probe asks the gateway resolver for `example.com`, which it has
answered before, yet its median is 36.0 ms (5th percentile 17 ms; only 3.4 %
of answers arrive within 15 ms). The gateway therefore forwards every query
upstream rather than serving it from a local cache, and the column measures
the upstream resolver's responsiveness. The recursive probe (a random name
under `example.com`) has a median of 59.2 ms, 20.2 ms above the cached probe
in the same sample; 2.35 % of recursive lookups take longer than 200 ms and
the 99th percentile is 1,266 ms. 24 samples recorded a DNS timeout, 14 of
them during the four outages (the other four outage samples failed with a
socket error instead).
### Memory

| lag | 30 s | 5 min | 30 min | 3 h | 12 h | 24 h |
|---|---|---|---|---|---|---|
| log round-trip time | 0.81 | 0.76 | 0.68 | 0.42 | 0.18 | 0.09 |
| jitter | 0.44 | 0.42 | 0.36 | 0.25 | 0.23 | 0.17 |
| lost-echo indicator | 0.18 | 0.17 | 0.16 | 0.14 | 0.04 | 0.10 |
| fastest TCP handshake | 0.28 | 0.15 | 0.14 | 0.09 | 0.04 | 0.02 |
| recursive DNS | 0.04 | 0.02 | 0.02 | 0.02 | 0.00 | 0.01 |
| HTTP | 0.06 | 0.05 | 0.03 | 0.04 | 0.02 | 0.01 |
Latency is persistent for hours and has no daily cycle at this site; DNS and
HTTP timings are memoryless at every lag.
### WAN throughput

460 hourly speed tests ran through the `speedtest-cli` Python fallback with no
pinned server and used 162 different servers. 79 tests could not measure the
server's latency (the fallback encodes that failure as a value of 600,000 ms
or more; the builder sets it to missing), 7 reported a download of 0 Mbit/s
and 4 an upload of 0 Mbit/s. Download: median 34.7 Mbit/s, 90th percentile
183 Mbit/s, maximum 480.7 Mbit/s; among the ten most used servers the
per-server median ranges from 20.9 to 371.8 Mbit/s. Upload: median
28.6 Mbit/s, 90th percentile 40.3 Mbit/s, maximum 54.2 Mbit/s. The median
download is 61.5 Mbit/s for the 95 tests started between 00:00 and 04:59 and
22.0 Mbit/s for the 156 started between 09:00 and 16:59. The download column is a lower bound on
the access link and depends heavily on the server; the upload column is more
consistent. Loaded latency was not measured because the official Ookla CLI was
not installed.
## Measurement protocol
One sample is taken at every tick of a fixed schedule (`start + k * interval`).
Within a sample the following probes run concurrently:
- ICMP: `ping_count` (10) echo requests to the target and `gateway_ping_count`
(5) to the default gateway, one second apart, each waiting at most
`ping_timeout` (2 s) for its reply. Per-reply round-trip times are parsed
from the output of the operating system's `ping`.
- TCP: `tcp_count` (5) TCP handshakes to `target:443`, 0.2 s apart, timed with
a high-resolution clock from `connect()` start to completion.
- DNS: two UDP queries (type A, recursion desired) sent directly to the
configured resolver, bypassing the operating-system cache. The first asks for
`dns_host` (`example.com`), which the resolver serves from its cache after
the first sample and therefore measures the resolver's responsiveness. The
second asks for a random 12-hexadecimal-character subdomain of `dns_host`,
which can never be cached and therefore measures a full recursive
resolution. A response with rcode NOERROR or NXDOMAIN is a valid measurement.
- HTTP: one GET request for `http_url`
(`http://www.msftconnecttest.com/connecttest.txt`) with the system proxy
bypassed, timed until the response headers have been received.
- Wi-Fi: link metrics read from the operating system
(`netsh wlan show interfaces`, `iw dev <if> link`, `system_profiler
SPAirPortDataType`).
After the concurrent probes, and only on their own cadence (every hour in the
published run), the heavy tests run: an Ookla speed test and/or an `iperf3`
test. Because they run after the latency probes of the same sample, they do
not influence that sample's latency columns; a sample that includes a speed
test usually overruns the interval, and the collector then skips to the next
tick.
The default gateway, the interface type and the resolver are detected at start
and re-detected every 15 minutes (or within a minute after the gateway probe
loses every packet). System sleep is inhibited for the duration of the run.
Run configuration of the published capture: interval 30 s, 10 echoes to
`8.8.8.8` and 5 to the gateway with a 2 s timeout, 5 TCP handshakes to port
443, DNS probes against the gateway resolver with a 3 s timeout, HTTP probe
with a 5 s timeout, Wi-Fi metrics enabled, SSID not recorded, speed test every
hour with no pinned server, no iperf3 server, collector version 2.0.0.
## Schema
Empty cells mean "not measured or failed"; the `notes` column records the
reason (for example `ping: no replies`, `dns recursive: timeout`,
`speedtest (ookla) failed: ...`). Times are in milliseconds unless the column
name says otherwise.
### Identity and time
| Column | Type | Description |
|---|---|---|
| `run_id` | string | collection run identifier, `<host_label_>YYYYMMDD_HHMMSS` in local time of the run start |
| `host_label` | string | free-text label of the vantage point (`--host-label`), empty if not given |
| `sample_index` | int | 0-based row number within the run |
| `timestamp_utc` | string | sample start, ISO 8601 UTC, e.g. `2026-09-05T14:00:00Z` |
| `timestamp_local` | string | sample start in the collector's local time with UTC offset, e.g. `2026-09-05T10:00:00-04:00` |
| `epoch_s` | int | sample start as Unix time (seconds) |
| `elapsed_s` | float | seconds since the start of the run |
| `link_type` | string | `wifi`, `ethernet`, `other` or `unknown`: the interface that carries the default route |
| `gateway_ip` | string | default gateway (private address) |
| `dns_server` | string | resolver used for the DNS probes |
| `target` | string | host used for the ICMP and TCP probes |
### Run context (added by the builder)
| Column | Type | Description |
|---|---|---|
| `collector_version` | string | version of `collect_data.py` that wrote the run |
| `collector_os` | string | `Windows`, `Linux` or `macOS` |
| `interval_s` | float | configured sampling interval of the run |
| `rtt_resolution_ms` | float | resolution of the ICMP columns: 1.0 on Windows, 0.001 elsewhere |
### Time features (added by the builder, from `timestamp_local`)
| Column | Type | Description |
|---|---|---|
| `date_local` | string | local calendar date `YYYY-MM-DD` |
| `hour_local` | int | local hour 0-23 |
| `weekday_local` | int | 0 = Monday ... 6 = Sunday |
| `is_weekend` | int | 1 on Saturday and Sunday |
| `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 |
### Target latency (ICMP)
| Column | Type | Description |
|---|---|---|
| `rtt_min_ms` | float | minimum round-trip time of the received replies |
| `rtt_avg_ms` | float | arithmetic mean |
| `rtt_median_ms` | float | median |
| `rtt_max_ms` | float | maximum |
| `rtt_stddev_ms` | float | population standard deviation of the received replies (the `mdev` of Linux `ping`) |
| `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 |
| `packets_sent` | int | echo requests sent (`ping_count`) |
| `packets_received` | int | replies received |
| `packet_loss_pct` | float | `100 * (sent - received) / sent` |
### Gateway latency (ICMP to the default gateway)
| Column | Type | Description |
|---|---|---|
| `gateway_rtt_min_ms` | float | minimum round-trip time |
| `gateway_rtt_avg_ms` | float | mean |
| `gateway_rtt_max_ms` | float | maximum |
| `gateway_jitter_ms` | float | mean absolute consecutive difference |
| `gateway_packet_loss_pct` | float | loss in percent |
### TCP, DNS and HTTP
| Column | Type | Description |
|---|---|---|
| `tcp_connect_min_ms` | float | fastest of the TCP handshakes to `target:443` |
| `tcp_connect_median_ms` | float | median handshake time |
| `dns_resolve_ms` | float | response time of the resolver for `dns_host` (cache-served after the first sample) |
| `dns_recursive_ms` | float | response time for a random subdomain of `dns_host` (full recursive lookup) |
| `http_ms` | float | time to the response headers of `http_url`, including the operating-system name lookup, the TCP handshake and the request |
| `http_status` | int | HTTP status code of that response |
### Wi-Fi link (empty on wired links)
| Column | Type | Description |
|---|---|---|
| `wifi_ssid` | string | network name; only recorded with `--record-ssid` |
| `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 |
| `wifi_rssi_dbm` | float | received signal strength: as reported on Linux and macOS; on Windows derived from the quality with `rssi = quality / 2 - 100` |
| `wifi_rx_mbps` | float | negotiated receive PHY rate (Mbit/s) |
| `wifi_tx_mbps` | float | negotiated transmit PHY rate (Mbit/s); equals the receive rate on macOS, which reports one rate |
| `wifi_channel` | int | channel number |
| `wifi_band_ghz` | float | 2.4, 5 or 6 |
| `wifi_phy` | string | standard in use, e.g. `802.11ax` |
### WAN throughput (rows in which a speed test ran)
| Column | Type | Description |
|---|---|---|
| `download_mbps` | float | download throughput (Mbit/s) |
| `upload_mbps` | float | upload throughput (Mbit/s) |
| `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 |
| `download_loaded_latency_ms` | float | interquartile-mean latency measured during the download (Ookla CLI only) |
| `upload_loaded_latency_ms` | float | interquartile-mean latency measured during the upload (Ookla CLI only) |
| `speedtest_server_id` | int | Ookla server id |
| `speedtest_server` | string | server name and location |
### LAN throughput (rows in which an iperf3 test ran)
| Column | Type | Description |
|---|---|---|
| `lan_throughput_mbps` | float | TCP throughput to the LAN iperf3 server (Mbit/s) |
| `lan_retransmits` | int | TCP retransmissions during the test, when reported |
### Reference labels (added by the builder)
| Column | Type | Rule |
|---|---|---|
| `label_outage` | int | `packets_received == 0` while `packets_sent > 0` |
| `label_packet_loss` | int | `0 < packet_loss_pct < 100` |
| `label_high_latency` | int | `rtt_avg_ms > T_rtt` |
| `label_high_jitter` | int | `jitter_ms > T_jitter` |
| `label_gateway_degraded` | int | `gateway_rtt_avg_ms > T_gateway` or `gateway_packet_loss_pct > 0` |
| `label_anomaly` | int | any of the above |
The thresholds are computed per run from that run's own distribution with a
robust rule, so they adapt to the baseline of the site without being pulled by
the outliers they are meant to find:
```text
T = median + max(k * 1.4826 * MAD, absolute floor, relative floor * median)
```
with `k = 5`, the median absolute deviation `MAD`, and the floors
10 ms / 50 % for `rtt_avg_ms`, 5 ms / 100 % for `jitter_ms` and
5 ms / 100 % for `gateway_rtt_avg_ms`. A threshold is not computed (and the
label stays 0) for runs with fewer than 20 valid values. For the published run
the thresholds are 21.1 ms (`rtt_avg_ms`), 6.0 ms (`jitter_ms`) and 5.2 ms
(`gateway_rtt_avg_ms`); the values used for each run are stored in
`dataset/summary.json`. These labels are derived from the measurements
themselves; they are reference points for evaluating detectors, not
independent ground truth.
### Manual annotations and notes
| Column | Type | Description |
|---|---|---|
| `event_category` | string | categories of the manual events covering the sample time, joined with ` \| `; one of `load`, `outage`, `maintenance`, `environment`, `isp`, `device`, `other` |
| `event_description` | string | the corresponding free-text descriptions |
| `sample_duration_s` | float | wall-clock time the sample's probes took |
| `notes` | string | probe errors and status messages, `; `-separated |
## Validation performed by the builder
- Rows with a malformed `timestamp_utc` are dropped and duplicate
`(run_id, timestamp_utc)` pairs are reduced to the first occurrence (none in
the published run).
- Loss percentages outside 0-100 are set to missing (none in the published
run).
- `speedtest_ping_ms` values of 600,000 ms or more are set to missing. The
`speedtest-cli` fallback scores each failed latency attempt as 3,600 s and
averages three attempts over six, so one failed attempt already yields
600,000 ms and three yield 1,800,000 ms. The raw file keeps the original
values; 79 of the 460 speed-test rows are affected. Collector version 2.0.1
no longer records such values.
## Statistics
<!-- BEGIN GENERATED STATISTICS -->
Generated by `scripts/build_dataset.py` on 2026-10-10T05:42:01Z from 1 collection run(s).
| Item | Value |
|---|---|
| Rows | 54,617 |
| Columns | 67 |
| First sample (UTC) | 2026-09-20T16:34:22Z |
| Last sample (UTC) | 2026-10-09T19:49:43Z |
| Span | 19.14 days |
| Sampling coverage | 99.1 % of the samples expected at the configured interval |
| Manual event annotations | 0 |
| Run | Vantage | Link | OS | Interval | Rows | Span | Coverage |
|---|---|---|---|---|---|---|---|
| desktop-eth_20260920_123407 | desktop-eth | unknown (54617) | Windows | 30 s | 54,617 | 459.26 h | 99.1 % |
| Metric | n | Median | Mean | p95 | Max |
|---|---|---|---|---|---|
| rtt_avg_ms | 54,599 | 11.1 | 12.581 | 22.3 | 288.6 |
| rtt_min_ms | 54,599 | 10.0 | 10.432 | 14.0 | 263.0 |
| rtt_max_ms | 54,599 | 13.0 | 17.869 | 32.0 | 373.0 |
| jitter_ms | 54,599 | 1.0 | 2.306 | 7.667 | 59.778 |
| packet_loss_pct | 54,617 | 0.0 | 1.763 | 10.0 | 100.0 |
| gateway_rtt_avg_ms | 54,599 | 0.2 | 0.321 | 0.8 | 89.4 |
| gateway_packet_loss_pct | 54,617 | 0.0 | 0.033 | 0.0 | 100.0 |
| tcp_connect_median_ms | 54,598 | 14.484 | 19.311 | 32.127 | 1524.463 |
| dns_resolve_ms | 54,595 | 36.026 | 43.594 | 74.878 | 3252.214 |
| dns_recursive_ms | 54,590 | 59.242 | 87.275 | 106.31 | 25645.041 |
| http_ms | 54,565 | 81.911 | 154.745 | 271.36 | 13111.02 |
| wifi_signal_pct | 4 | 85.0 | 85.75 | 88.4 | 89.0 |
| wifi_rssi_dbm | 4 | -57.5 | -57.125 | -55.8 | -55.5 |
| wifi_rx_mbps | 4 | 866.7 | 866.7 | 866.7 | 866.7 |
| download_mbps | 460 | 34.725 | 68.463 | 318.275 | 480.72 |
| upload_mbps | 460 | 28.625 | 26.121 | 41.142 | 54.17 |
| speedtest_ping_ms | 381 | 52.058 | 93.665 | 196.381 | 1167.189 |
| Reference label | Rows | Share |
|---|---|---|
| label_outage | 18 | 0.033 % |
| label_packet_loss | 7,692 | 14.084 % |
| label_high_latency | 3,067 | 5.615 % |
| label_high_jitter | 5,074 | 9.29 % |
| label_gateway_degraded | 560 | 1.025 % |
| label_anomaly | 13,036 | 23.868 % |
<!-- END GENERATED STATISTICS -->
## Known limitations and biases
- Single vantage point, single run. Absolute values reflect one site's access
technology, router, cabling and ISP routing. Relative variation, the
structure of episodes and the probe-to-probe relationships transfer better
than absolute baselines.
- `link_type` is `unknown` for every row. The PowerShell route query returned
nothing on this machine, the collector fell back to `route print`, and that
fallback does not report the media type. The vantage point is a wired
desktop (host label `desktop-eth`, median first-hop round-trip time 0.2 ms).
Four rows carry Wi-Fi link metrics (channel 44 or 157, 5 GHz, 802.11ac,
866.7 Mbit/s): a wireless adapter on the same machine was connected at those
moments. Their first-hop round-trip times (0.0 to 1.2 ms) and target
latencies match the wired baseline, so the default route stayed on the
wired link.
- ICMP resolution on Windows is 1 ms and sub-millisecond replies are stored as
0; jitter and standard deviation computed from such values contain
quantisation noise, and the gateway columns are mostly 0 for this wired
site. Use `tcp_connect_*` for sub-millisecond latency, or collect on
Linux/macOS. `rtt_resolution_ms` states the resolution of each run.
- ICMP is handled differently from user traffic by some routers and hosts
(rate limiting, de-prioritisation). The TCP connect and HTTP columns measure
the transport and application paths that applications actually use, and the
October 6 TCP/ICMP split shows that the two can be routed differently.
- The 10-echo burst characterises latency over roughly ten seconds of each
interval; events shorter than that between samples are not observed.
- The DNS "cached" probe is cached at the upstream resolver, not at the
gateway: at this site the gateway forwards every query, so the column
measures the upstream resolver plus the forwarding hop.
- The DNS "recursive" probe generates NXDOMAIN answers for random names; a
resolver that applies aggressive negative caching or that intercepts
NXDOMAIN (ISP search redirection) still answers, but its timing reflects that
behaviour.
- The HTTP probe includes the operating system's name lookup for the URL's
host, which is normally cached; its discrete modes near 1.1, 1.3 and 4.1 s
are retransmission timers waiting out lost packets, not propagation or
queueing delay.
- Speed tests were run with the `speedtest-cli` fallback, which uses the
Python interpreter's own HTTP transfers, and without a pinned server. The
download column is a lower bound that depends strongly on the chosen
server; 79 tests have no latency, 7 report 0 Mbit/s download and 4 report
0 Mbit/s upload. Loaded latency is absent. Speed tests also load the
household link for about half a minute, which is visible to other devices,
and they leave a 60-second gap in the 30-second grid.
- The two halves of the capture differ markedly (see the findings). Models
trained on one half should be evaluated on the other.
- No manual event annotations were recorded, so the `event_*` columns are
empty and the causes of the episodes are inferred from the probes only.
- Gaps: system sleep, reboots and collector restarts appear as gaps
(`gap_before_s`) or as separate runs; ticks skipped after an overrun also
appear as gaps. The published run has none longer than 122 s.
- Clock: timestamps come from the system clock; `elapsed_s` uses a monotonic
clock and is unaffected by clock adjustments.
## Privacy
The dataset does not contain public IP addresses, hostnames of household
devices, MAC addresses, Wi-Fi network names or per-device traffic. Gateway and
resolver addresses are private LAN addresses. The run metadata records the
operating system build, the Python version, the time zone and the private LAN
address of the collector. Speed-test rows name the test server, which was not
pinned and therefore only indicates the broad region of the site.
## Citation
If you use the data:
```bibtex
@dataset{ezharjan_localnetdynamics_data_2026,
author = {Ezharjan, Alexander},
title = {LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset},
year = {2026},
version = {1.0.0},
publisher = {Hugging Face},
url = {https://huggingface.co/datasets/ezharjan/LocalNetDynamics}
}
```
If you use the collector, the build pipeline or the analysis code:
```bibtex
@software{ezharjan_localnetdynamics_code_2026,
author = {Ezharjan, Alexander},
title = {LocalNet-Dynamics: collector, build pipeline and analysis toolkit for longitudinal home-network telemetry},
year = {2026},
version = {1.0.0},
url = {https://github.com/Ezharjan/LocalNetDynamicsDataset}
}
```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504{
"generated_utc": "2026-10-10T05:42:03Z",
"overview": {
"rows": 54617,
"runs": 1,
"first_utc": "2026-09-20T16:34:22Z",
"last_utc": "2026-10-09T19:49:43Z",
"first_local": "2026-09-20T12:34:22-04:00",
"last_local": "2026-10-09T15:49:43-04:00",
"span_days": 19.14,
"full_days": 18,
"coverage_pct": 99.1,
"max_gap_s": 122.0,
"gaps_of_2_intervals": 345,
"gaps_over_2_intervals": 78,
"gaps_over_2_intervals_after_speedtest": 53,
"rows_with_notes": 59,
"wifi_rows": 4,
"link_types": {
"unknown": 54617
},
"metrics": {
"rtt_avg_ms": {
"n": 54599,
"median": 11.1,
"mean": 12.581,
"p95": 22.3,
"p99": 27.0,
"max": 288.6
},
"rtt_min_ms": {
"n": 54599,
"median": 10.0,
"mean": 10.432,
"p95": 14.0,
"p99": 22.0,
"max": 263.0
},
"rtt_max_ms": {
"n": 54599,
"median": 13.0,
"mean": 17.869,
"p95": 32.0,
"p99": 43.0,
"max": 373.0
},
"jitter_ms": {
"n": 54599,
"median": 1.0,
"mean": 2.306,
"p95": 7.667,
"p99": 11.333,
"max": 59.778
},
"packet_loss_pct": {
"n": 54617,
"median": 0.0,
"mean": 1.763,
"p95": 10.0,
"p99": 20.0,
"max": 100.0
},
"gateway_rtt_avg_ms": {
"n": 54599,
"median": 0.2,
"mean": 0.321,
"p95": 0.8,
"p99": 5.0,
"max": 89.4
},
"tcp_connect_min_ms": {
"n": 54598,
"median": 12.296,
"mean": 14.133,
"p95": 23.886,
"p99": 28.762,
"max": 1032.09
},
"tcp_connect_median_ms": {
"n": 54598,
"median": 14.484,
"mean": 19.311,
"p95": 32.127,
"p99": 38.784,
"max": 1524.463
},
"dns_resolve_ms": {
"n": 54595,
"median": 36.026,
"mean": 43.594,
"p95": 74.878,
"p99": 121.832,
"max": 3252.214
},
"dns_recursive_ms": {
"n": 54590,
"median": 59.242,
"mean": 87.275,
"p95": 106.31,
"p99": 1266.18,
"max": 25645.041
},
"http_ms": {
"n": 54565,
"median": 81.911,
"mean": 154.745,
"p95": 271.36,
"p99": 1375.212,
"max": 13111.02
},
"download_mbps": {
"n": 460,
"median": 34.725,
"mean": 68.463,
"p95": 318.275,
"p99": 417.581,
"max": 480.72
},
"upload_mbps": {
"n": 460,
"median": 28.625,
"mean": 26.121,
"p95": 41.142,
"p99": 44.101,
"max": 54.17
}
}
},
"hour_profile": [
{
"hour": 0,
"n": 2263,
"rtt_median": 11.4,
"rtt_p25": 10.7,
"rtt_p75": 15.5,
"rtt_p95": 27.44,
"jitter_median": 1.222,
"loss_share_pct": 6.41,
"loss_share_weekday_pct": 6.55,
"loss_share_weekend_pct": 5.88,
"http_p95": 160.456,
"http_over_1s_pct": 1.72,
"high_latency_pct": 19.93,
"gateway_p95": 0.6
},
{
"hour": 1,
"n": 2266,
"rtt_median": 11.4,
"rtt_p25": 10.8,
"rtt_p75": 15.9,
"rtt_p95": 25.383,
"jitter_median": 1.292,
"loss_share_pct": 7.28,
"loss_share_weekday_pct": 6.65,
"loss_share_weekend_pct": 9.64,
"http_p95": 146.393,
"http_over_1s_pct": 1.19,
"high_latency_pct": 13.72,
"gateway_p95": 0.8
},
{
"hour": 2,
"n": 2266,
"rtt_median": 11.4,
"rtt_p25": 10.778,
"rtt_p75": 15.9,
"rtt_p95": 25.59,
"jitter_median": 1.222,
"loss_share_pct": 8.25,
"loss_share_weekday_pct": 7.83,
"loss_share_weekend_pct": 9.83,
"http_p95": 149.275,
"http_over_1s_pct": 1.42,
"high_latency_pct": 13.55,
"gateway_p95": 0.8
},
{
"hour": 3,
"n": 2263,
"rtt_median": 11.2,
"rtt_p25": 10.683,
"rtt_p75": 13.845,
"rtt_p95": 25.44,
"jitter_median": 1.0,
"loss_share_pct": 7.69,
"loss_share_weekday_pct": 7.5,
"loss_share_weekend_pct": 8.39,
"http_p95": 135.124,
"http_over_1s_pct": 1.63,
"high_latency_pct": 12.77,
"gateway_p95": 0.8
},
{
"hour": 4,
"n": 2264,
"rtt_median": 11.0,
"rtt_p25": 10.6,
"rtt_p75": 12.133,
"rtt_p95": 24.548,
"jitter_median": 0.827,
"loss_share_pct": 6.71,
"loss_share_weekday_pct": 5.76,
"loss_share_weekend_pct": 10.32,
"http_p95": 130.753,
"http_over_1s_pct": 1.19,
"high_latency_pct": 10.51,
"gateway_p95": 0.8
},
{
"hour": 5,
"n": 2263,
"rtt_median": 11.0,
"rtt_p25": 10.6,
"rtt_p75": 11.9,
"rtt_p95": 24.6,
"jitter_median": 0.875,
"loss_share_pct": 9.81,
"loss_share_weekday_pct": 9.35,
"loss_share_weekend_pct": 11.55,
"http_p95": 135.304,
"http_over_1s_pct": 1.81,
"high_latency_pct": 10.38,
"gateway_p95": 0.8
},
{
"hour": 6,
"n": 2265,
"rtt_median": 11.0,
"rtt_p25": 10.6,
"rtt_p75": 12.7,
"rtt_p95": 24.0,
"jitter_median": 0.889,
"loss_share_pct": 13.6,
"loss_share_weekday_pct": 15.1,
"loss_share_weekend_pct": 7.97,
"http_p95": 263.324,
"http_over_1s_pct": 3.53,
"high_latency_pct": 7.42,
"gateway_p95": 0.8
},
{
"hour": 7,
"n": 2265,
"rtt_median": 11.1,
"rtt_p25": 10.6,
"rtt_p75": 12.4,
"rtt_p95": 20.305,
"jitter_median": 0.889,
"loss_share_pct": 17.26,
"loss_share_weekday_pct": 20.02,
"loss_share_weekend_pct": 6.92,
"http_p95": 151.028,
"http_over_1s_pct": 3.23,
"high_latency_pct": 4.06,
"gateway_p95": 0.8
},
{
"hour": 8,
"n": 2262,
"rtt_median": 11.1,
"rtt_p25": 10.5,
"rtt_p75": 12.333,
"rtt_p95": 16.5,
"jitter_median": 0.889,
"loss_share_pct": 21.75,
"loss_share_weekday_pct": 25.21,
"loss_share_weekend_pct": 8.81,
"http_p95": 1088.286,
"http_over_1s_pct": 5.57,
"high_latency_pct": 0.84,
"gateway_p95": 0.8
},
{
"hour": 9,
"n": 2262,
"rtt_median": 11.0,
"rtt_p25": 10.5,
"rtt_p75": 12.333,
"rtt_p95": 17.0,
"jitter_median": 1.0,
"loss_share_pct": 19.98,
"loss_share_weekday_pct": 23.12,
"loss_share_weekend_pct": 8.19,
"http_p95": 1070.512,
"http_over_1s_pct": 5.57,
"high_latency_pct": 0.53,
"gateway_p95": 0.8
},
{
"hour": 10,
"n": 2256,
"rtt_median": 11.0,
"rtt_p25": 10.6,
"rtt_p75": 12.333,
"rtt_p95": 16.0,
"jitter_median": 1.111,
"loss_share_pct": 18.26,
"loss_share_weekday_pct": 20.73,
"loss_share_weekend_pct": 9.03,
"http_p95": 324.732,
"http_over_1s_pct": 4.3,
"high_latency_pct": 0.84,
"gateway_p95": 0.8
},
{
"hour": 11,
"n": 2259,
"rtt_median": 11.1,
"rtt_p25": 10.6,
"rtt_p75": 12.4,
"rtt_p95": 15.222,
"jitter_median": 1.222,
"loss_share_pct": 19.17,
"loss_share_weekday_pct": 21.39,
"loss_share_weekend_pct": 10.78,
"http_p95": 326.073,
"http_over_1s_pct": 4.48,
"high_latency_pct": 0.35,
"gateway_p95": 0.6
},
{
"hour": 12,
"n": 2307,
"rtt_median": 11.0,
"rtt_p25": 10.5,
"rtt_p75": 12.4,
"rtt_p95": 16.0,
"jitter_median": 1.0,
"loss_share_pct": 20.42,
"loss_share_weekday_pct": 22.6,
"loss_share_weekend_pct": 12.98,
"http_p95": 1071.792,
"http_over_1s_pct": 5.33,
"high_latency_pct": 0.26,
"gateway_p95": 0.6
},
{
"hour": 13,
"n": 2375,
"rtt_median": 10.9,
"rtt_p25": 10.5,
"rtt_p75": 12.333,
"rtt_p95": 16.0,
"jitter_median": 1.0,
"loss_share_pct": 20.21,
"loss_share_weekday_pct": 22.91,
"loss_share_weekend_pct": 12.03,
"http_p95": 1055.948,
"http_over_1s_pct": 5.08,
"high_latency_pct": 0.97,
"gateway_p95": 0.8
},
{
"hour": 14,
"n": 2377,
"rtt_median": 11.0,
"rtt_p25": 10.5,
"rtt_p75": 12.6,
"rtt_p95": 19.4,
"jitter_median": 1.111,
"loss_share_pct": 20.87,
"loss_share_weekday_pct": 23.64,
"loss_share_weekend_pct": 12.5,
"http_p95": 1079.365,
"http_over_1s_pct": 5.56,
"high_latency_pct": 3.83,
"gateway_p95": 1.0
},
{
"hour": 15,
"n": 2356,
"rtt_median": 11.1,
"rtt_p25": 10.6,
"rtt_p75": 12.8,
"rtt_p95": 18.822,
"jitter_median": 1.111,
"loss_share_pct": 21.31,
"loss_share_weekday_pct": 23.91,
"loss_share_weekend_pct": 13.54,
"http_p95": 1076.688,
"http_over_1s_pct": 5.69,
"high_latency_pct": 2.97,
"gateway_p95": 1.0
},
{
"hour": 16,
"n": 2258,
"rtt_median": 11.1,
"rtt_p25": 10.6,
"rtt_p75": 12.5,
"rtt_p95": 17.7,
"jitter_median": 1.118,
"loss_share_pct": 19.53,
"loss_share_weekday_pct": 22.76,
"loss_share_weekend_pct": 10.46,
"http_p95": 1081.493,
"http_over_1s_pct": 5.68,
"high_latency_pct": 2.61,
"gateway_p95": 0.8
},
{
"hour": 17,
"n": 2252,
"rtt_median": 11.1,
"rtt_p25": 10.6,
"rtt_p75": 12.556,
"rtt_p95": 19.745,
"jitter_median": 1.111,
"loss_share_pct": 16.87,
"loss_share_weekday_pct": 18.82,
"loss_share_weekend_pct": 11.38,
"http_p95": 263.657,
"http_over_1s_pct": 3.78,
"high_latency_pct": 3.95,
"gateway_p95": 6.0
},
{
"hour": 18,
"n": 2258,
"rtt_median": 11.0,
"rtt_p25": 10.5,
"rtt_p75": 12.2,
"rtt_p95": 15.8,
"jitter_median": 1.111,
"loss_share_pct": 13.82,
"loss_share_weekday_pct": 14.11,
"loss_share_weekend_pct": 13.01,
"http_p95": 312.767,
"http_over_1s_pct": 3.63,
"high_latency_pct": 1.2,
"gateway_p95": 0.6
},
{
"hour": 19,
"n": 2255,
"rtt_median": 11.0,
"rtt_p25": 10.556,
"rtt_p75": 12.0,
"rtt_p95": 14.5,
"jitter_median": 1.0,
"loss_share_pct": 11.18,
"loss_share_weekday_pct": 11.73,
"loss_share_weekend_pct": 9.63,
"http_p95": 269.201,
"http_over_1s_pct": 3.24,
"high_latency_pct": 0.49,
"gateway_p95": 0.6
},
{
"hour": 20,
"n": 2257,
"rtt_median": 10.9,
"rtt_p25": 10.6,
"rtt_p75": 11.7,
"rtt_p95": 14.1,
"jitter_median": 1.0,
"loss_share_pct": 10.15,
"loss_share_weekday_pct": 9.49,
"loss_share_weekend_pct": 11.99,
"http_p95": 388.689,
"http_over_1s_pct": 2.75,
"high_latency_pct": 0.31,
"gateway_p95": 0.6
},
{
"hour": 21,
"n": 2257,
"rtt_median": 11.1,
"rtt_p25": 10.7,
"rtt_p75": 12.5,
"rtt_p95": 17.455,
"jitter_median": 1.222,
"loss_share_pct": 9.53,
"loss_share_weekday_pct": 8.29,
"loss_share_weekend_pct": 12.98,
"http_p95": 323.17,
"http_over_1s_pct": 2.53,
"high_latency_pct": 3.9,
"gateway_p95": 0.6
},
{
"hour": 22,
"n": 2251,
"rtt_median": 11.3,
"rtt_p25": 10.7,
"rtt_p75": 12.9,
"rtt_p95": 24.9,
"jitter_median": 1.222,
"loss_share_pct": 8.31,
"loss_share_weekday_pct": 7.67,
"loss_share_weekend_pct": 10.08,
"http_p95": 268.161,
"http_over_1s_pct": 2.13,
"high_latency_pct": 8.35,
"gateway_p95": 0.6
},
{
"hour": 23,
"n": 2260,
"rtt_median": 11.2,
"rtt_p25": 10.6,
"rtt_p75": 12.889,
"rtt_p95": 25.89,
"jitter_median": 1.111,
"loss_share_pct": 9.38,
"loss_share_weekday_pct": 8.58,
"loss_share_weekend_pct": 11.62,
"http_p95": 146.393,
"http_over_1s_pct": 1.55,
"high_latency_pct": 11.46,
"gateway_p95": 0.6
}
],
"weekday_weekend": {
"weekday": {
"n": 41865,
"rtt_median": 11.1,
"rtt_p95": 20.3,
"loss_share_pct": 15.21,
"jitter_median": 1.0,
"http_median": 81.525
},
"weekend": {
"n": 12752,
"rtt_median": 11.2,
"rtt_p95": 24.8,
"loss_share_pct": 10.54,
"jitter_median": 1.111,
"http_median": 83.276
}
},
"daily": [
{
"date": "2026-09-20",
"weekday": 6,
"n": 1331,
"rtt_median": 10.7,
"rtt_p95": 13.2,
"rtt_min_median": 10.0,
"tcp_min_median": 11.933,
"loss_share_pct": 10.22,
"mean_loss_pct": 1.097,
"jitter_median": 0.889,
"http_p95": 370.934,
"anomaly_pct": 13.15,
"gateway_degraded": 9
},
{
"date": "2026-09-21",
"weekday": 0,
"n": 2852,
"rtt_median": 11.2,
"rtt_p95": 25.0,
"rtt_min_median": 10.0,
"tcp_min_median": 12.113,
"loss_share_pct": 21.18,
"mean_loss_pct": 3.166,
"jitter_median": 1.222,
"http_p95": 1093.809,
"anomaly_pct": 29.49,
"gateway_degraded": 5
},
{
"date": "2026-09-22",
"weekday": 1,
"n": 2860,
"rtt_median": 11.646,
"rtt_p95": 24.1,
"rtt_min_median": 10.0,
"tcp_min_median": 12.237,
"loss_share_pct": 19.9,
"mean_loss_pct": 2.367,
"jitter_median": 1.778,
"http_p95": 1065.949,
"anomaly_pct": 35.24,
"gateway_degraded": 7
},
{
"date": "2026-09-23",
"weekday": 2,
"n": 2853,
"rtt_median": 12.0,
"rtt_p95": 16.9,
"rtt_min_median": 10.0,
"tcp_min_median": 12.142,
"loss_share_pct": 33.93,
"mean_loss_pct": 4.707,
"jitter_median": 1.125,
"http_p95": 1295.07,
"anomaly_pct": 38.77,
"gateway_degraded": 3
},
{
"date": "2026-09-24",
"weekday": 3,
"n": 2859,
"rtt_median": 11.2,
"rtt_p95": 16.556,
"rtt_min_median": 10.0,
"tcp_min_median": 12.118,
"loss_share_pct": 30.57,
"mean_loss_pct": 4.113,
"jitter_median": 1.222,
"http_p95": 1285.424,
"anomaly_pct": 37.01,
"gateway_degraded": 5
},
{
"date": "2026-09-25",
"weekday": 4,
"n": 2848,
"rtt_median": 11.2,
"rtt_p95": 21.273,
"rtt_min_median": 10.0,
"tcp_min_median": 12.338,
"loss_share_pct": 16.33,
"mean_loss_pct": 1.857,
"jitter_median": 1.111,
"http_p95": 192.037,
"anomaly_pct": 25.28,
"gateway_degraded": 3
},
{
"date": "2026-09-26",
"weekday": 5,
"n": 2849,
"rtt_median": 11.3,
"rtt_p95": 24.889,
"rtt_min_median": 10.0,
"tcp_min_median": 12.303,
"loss_share_pct": 13.83,
"mean_loss_pct": 1.692,
"jitter_median": 1.222,
"http_p95": 195.367,
"anomaly_pct": 30.92,
"gateway_degraded": 507
},
{
"date": "2026-09-27",
"weekday": 6,
"n": 2858,
"rtt_median": 15.261,
"rtt_p95": 27.815,
"rtt_min_median": 10.0,
"tcp_min_median": 12.745,
"loss_share_pct": 16.34,
"mean_loss_pct": 1.802,
"jitter_median": 5.333,
"http_p95": 272.551,
"anomaly_pct": 60.81,
"gateway_degraded": 0
},
{
"date": "2026-09-28",
"weekday": 0,
"n": 2854,
"rtt_median": 13.0,
"rtt_p95": 18.9,
"rtt_min_median": 10.0,
"tcp_min_median": 12.326,
"loss_share_pct": 32.69,
"mean_loss_pct": 4.201,
"jitter_median": 4.333,
"http_p95": 1284.014,
"anomaly_pct": 52.21,
"gateway_degraded": 0
},
{
"date": "2026-09-29",
"weekday": 1,
"n": 2856,
"rtt_median": 12.889,
"rtt_p95": 25.4,
"rtt_min_median": 10.0,
"tcp_min_median": 12.369,
"loss_share_pct": 29.69,
"mean_loss_pct": 3.771,
"jitter_median": 3.667,
"http_p95": 1294.432,
"anomaly_pct": 52.28,
"gateway_degraded": 0
},
{
"date": "2026-09-30",
"weekday": 2,
"n": 2858,
"rtt_median": 11.4,
"rtt_p95": 26.3,
"rtt_min_median": 10.0,
"tcp_min_median": 12.446,
"loss_share_pct": 9.34,
"mean_loss_pct": 1.018,
"jitter_median": 1.667,
"http_p95": 201.76,
"anomaly_pct": 38.17,
"gateway_degraded": 0
},
{
"date": "2026-10-01",
"weekday": 3,
"n": 2856,
"rtt_median": 10.9,
"rtt_p95": 13.3,
"rtt_min_median": 10.0,
"tcp_min_median": 12.157,
"loss_share_pct": 5.78,
"mean_loss_pct": 0.637,
"jitter_median": 0.889,
"http_p95": 124.368,
"anomaly_pct": 7.84,
"gateway_degraded": 0
},
{
"date": "2026-10-02",
"weekday": 4,
"n": 2854,
"rtt_median": 10.9,
"rtt_p95": 13.0,
"rtt_min_median": 10.0,
"tcp_min_median": 12.221,
"loss_share_pct": 6.76,
"mean_loss_pct": 0.708,
"jitter_median": 0.889,
"http_p95": 108.096,
"anomaly_pct": 8.13,
"gateway_degraded": 0
},
{
"date": "2026-10-03",
"weekday": 5,
"n": 2859,
"rtt_median": 10.6,
"rtt_p95": 12.6,
"rtt_min_median": 10.0,
"tcp_min_median": 12.054,
"loss_share_pct": 6.61,
"mean_loss_pct": 0.693,
"jitter_median": 0.667,
"http_p95": 111.648,
"anomaly_pct": 7.52,
"gateway_degraded": 7
},
{
"date": "2026-10-04",
"weekday": 6,
"n": 2855,
"rtt_median": 11.0,
"rtt_p95": 13.0,
"rtt_min_median": 10.0,
"tcp_min_median": 12.237,
"loss_share_pct": 5.53,
"mean_loss_pct": 0.581,
"jitter_median": 0.778,
"http_p95": 114.124,
"anomaly_pct": 6.06,
"gateway_degraded": 1
},
{
"date": "2026-10-05",
"weekday": 0,
"n": 2859,
"rtt_median": 10.9,
"rtt_p95": 12.8,
"rtt_min_median": 10.0,
"tcp_min_median": 12.197,
"loss_share_pct": 5.46,
"mean_loss_pct": 0.581,
"jitter_median": 0.778,
"http_p95": 217.098,
"anomaly_pct": 6.47,
"gateway_degraded": 3
},
{
"date": "2026-10-06",
"weekday": 1,
"n": 2853,
"rtt_median": 10.9,
"rtt_p95": 12.6,
"rtt_min_median": 10.0,
"tcp_min_median": 12.226,
"loss_share_pct": 2.98,
"mean_loss_pct": 0.452,
"jitter_median": 0.778,
"http_p95": 206.245,
"anomaly_pct": 4.14,
"gateway_degraded": 7
},
{
"date": "2026-10-07",
"weekday": 2,
"n": 2854,
"rtt_median": 10.4,
"rtt_p95": 11.6,
"rtt_min_median": 10.0,
"tcp_min_median": 19.295,
"loss_share_pct": 1.61,
"mean_loss_pct": 0.172,
"jitter_median": 0.667,
"http_p95": 185.259,
"anomaly_pct": 1.89,
"gateway_degraded": 0
},
{
"date": "2026-10-08",
"weekday": 3,
"n": 2862,
"rtt_median": 10.5,
"rtt_p95": 12.8,
"rtt_min_median": 10.0,
"tcp_min_median": 17.971,
"loss_share_pct": 3.95,
"mean_loss_pct": 0.412,
"jitter_median": 0.778,
"http_p95": 196.441,
"anomaly_pct": 4.65,
"gateway_degraded": 0
},
{
"date": "2026-10-09",
"weekday": 4,
"n": 1887,
"rtt_median": 10.5,
"rtt_p95": 12.444,
"rtt_min_median": 10.0,
"tcp_min_median": 18.398,
"loss_share_pct": 4.24,
"mean_loss_pct": 0.44,
"jitter_median": 0.667,
"http_p95": 113.939,
"anomaly_pct": 5.35,
"gateway_degraded": 3
}
],
"regimes": {
"method": "single least-squares change point in the daily share of samples with ICMP loss",
"split_date": "2026-09-30",
"daily_loss_share_before_pct": 22.47,
"daily_loss_share_after_pct": 5.23,
"before": {
"first_date": "2026-09-20",
"last_date": "2026-09-29",
"n": 27020,
"days": 10,
"rtt_median": 11.9,
"rtt_p95": 24.3,
"rtt_p99": 28.4,
"jitter_median": 2.222,
"jitter_p95": 9.222,
"loss_share_pct": 23.16,
"mean_loss_pct": 2.978,
"tcp_median": 14.101,
"dns_cached_median": 37.234,
"dns_recursive_median": 62.511,
"http_median": 87.667,
"http_p95": 1093.754,
"http_over_1s_pct": 5.87,
"labels_pct": {
"label_outage": 0.05,
"label_packet_loss": 23.11,
"label_high_latency": 7.96,
"label_high_jitter": 17.25,
"label_gateway_degraded": 1.99,
"label_anomaly": 38.9
}
},
"after": {
"first_date": "2026-09-30",
"last_date": "2026-10-09",
"n": 27597,
"days": 10,
"rtt_median": 10.8,
"rtt_p95": 14.2,
"rtt_p99": 25.5,
"jitter_median": 0.778,
"jitter_p95": 4.556,
"loss_share_pct": 5.26,
"mean_loss_pct": 0.574,
"tcp_median": 15.307,
"dns_cached_median": 35.018,
"dns_recursive_median": 56.243,
"http_median": 77.572,
"http_p95": 157.017,
"http_over_1s_pct": 1.09,
"labels_pct": {
"label_outage": 0.01,
"label_packet_loss": 5.25,
"label_high_latency": 3.32,
"label_high_jitter": 1.5,
"label_gateway_degraded": 0.08,
"label_anomaly": 9.15
}
}
},
"outages": [
{
"start_local": "2026-09-21T13:03:22-04:00",
"end_local": "2026-09-21T13:04:54-04:00",
"weekday": 0,
"samples": 4,
"minutes": 2.0,
"gateway_unreachable": true,
"gateway_loss_sample_before": 20.0
},
{
"start_local": "2026-09-24T07:10:56-04:00",
"end_local": "2026-09-24T07:12:56-04:00",
"weekday": 3,
"samples": 5,
"minutes": 2.5,
"gateway_unreachable": true,
"gateway_loss_sample_before": 0.0
},
{
"start_local": "2026-09-26T13:11:29-04:00",
"end_local": "2026-09-26T13:13:29-04:00",
"weekday": 5,
"samples": 5,
"minutes": 2.5,
"gateway_unreachable": true,
"gateway_loss_sample_before": 0.0
},
{
"start_local": "2026-10-06T02:51:09-04:00",
"end_local": "2026-10-06T02:52:40-04:00",
"weekday": 1,
"samples": 4,
"minutes": 2.0,
"gateway_unreachable": true,
"gateway_loss_sample_before": 0.0
}
],
"latency_episodes": [
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-21T22:34:24-04:00",
"end_local": "2026-09-22T01:05:24-04:00",
"weekday": 0,
"hours": 2.52,
"samples": 300,
"labelled_samples": 296,
"rtt_min_median": 20.0,
"rtt_avg_median": 26.422,
"tcp_min_median": 25.68,
"gateway_median": 0.0,
"jitter_median": 5.723,
"dns_cached_median": 36.483,
"http_median": 124.519,
"loss_share_pct": 14.0,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-22T01:27:24-04:00",
"end_local": "2026-09-22T02:41:24-04:00",
"weekday": 1,
"hours": 1.23,
"samples": 147,
"labelled_samples": 62,
"rtt_min_median": 10.0,
"rtt_avg_median": 20.4,
"tcp_min_median": 20.07,
"gateway_median": 0.0,
"jitter_median": 5.111,
"dns_cached_median": 36.795,
"http_median": 100.914,
"loss_share_pct": 6.12,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-22T02:47:24-04:00",
"end_local": "2026-09-22T03:44:24-04:00",
"weekday": 1,
"hours": 0.95,
"samples": 114,
"labelled_samples": 57,
"rtt_min_median": 11.0,
"rtt_avg_median": 21.15,
"tcp_min_median": 19.5,
"gateway_median": 0.0,
"jitter_median": 5.333,
"dns_cached_median": 36.397,
"http_median": 104.078,
"loss_share_pct": 3.51,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-24T23:51:27-04:00",
"end_local": "2026-09-25T01:16:27-04:00",
"weekday": 3,
"hours": 1.42,
"samples": 170,
"labelled_samples": 111,
"rtt_min_median": 11.0,
"rtt_avg_median": 22.3,
"tcp_min_median": 20.05,
"gateway_median": 0.0,
"jitter_median": 6.444,
"dns_cached_median": 37.297,
"http_median": 106.861,
"loss_share_pct": 7.06,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-26T14:07:29-04:00",
"end_local": "2026-09-26T14:54:29-04:00",
"weekday": 5,
"hours": 0.78,
"samples": 94,
"labelled_samples": 75,
"rtt_min_median": 14.0,
"rtt_avg_median": 23.5,
"tcp_min_median": 18.09,
"gateway_median": 11.4,
"jitter_median": 8.291,
"dns_cached_median": 48.922,
"http_median": 113.554,
"loss_share_pct": 14.89,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "first hop"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-26T15:01:59-04:00",
"end_local": "2026-09-26T15:32:59-04:00",
"weekday": 5,
"hours": 0.52,
"samples": 63,
"labelled_samples": 44,
"rtt_min_median": 14.0,
"rtt_avg_median": 22.0,
"tcp_min_median": 18.13,
"gateway_median": 11.2,
"jitter_median": 7.444,
"dns_cached_median": 38.085,
"http_median": 108.327,
"loss_share_pct": 14.29,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "first hop"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-26T16:36:59-04:00",
"end_local": "2026-09-26T18:17:29-04:00",
"weekday": 5,
"hours": 1.68,
"samples": 199,
"labelled_samples": 140,
"rtt_min_median": 14.0,
"rtt_avg_median": 23.7,
"tcp_min_median": 20.66,
"gateway_median": 10.6,
"jitter_median": 8.0,
"dns_cached_median": 46.31,
"http_median": 125.929,
"loss_share_pct": 21.61,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "first hop"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-27T00:00:29-04:00",
"end_local": "2026-09-27T06:16:59-04:00",
"weekday": 6,
"hours": 6.28,
"samples": 751,
"labelled_samples": 728,
"rtt_min_median": 17.0,
"rtt_avg_median": 25.6,
"tcp_min_median": 23.81,
"gateway_median": 0.0,
"jitter_median": 6.0,
"dns_cached_median": 40.061,
"http_median": 116.654,
"loss_share_pct": 18.64,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
},
{
"run_id": "desktop-eth_20260920_123407",
"start_local": "2026-09-29T21:21:32-04:00",
"end_local": "2026-09-30T07:34:34-04:00",
"weekday": 1,
"hours": 10.22,
"samples": 1220,
"labelled_samples": 1197,
"rtt_min_median": 20.0,
"rtt_avg_median": 24.8,
"tcp_min_median": 24.52,
"gateway_median": 0.0,
"jitter_median": 3.5,
"dns_cached_median": 39.95,
"http_median": 117.706,
"loss_share_pct": 12.79,
"run_rtt_min_median": 10.0,
"run_tcp_min_median": 12.3,
"kind": "path change"
}
],
"loss": {
"samples_with_loss_pct": 14.12,
"mean_loss_pct": 1.763,
"packets_received_counts": {
"4": 4,
"5": 16,
"6": 41,
"7": 230,
"8": 1092,
"9": 6309,
"10": 46907
},
"gateway_loss_samples_pct": 0.03,
"gateway_loss_outside_outages_samples": 1,
"persistence": {
"p_loss": 0.1412,
"p_loss_given_previous_loss": 0.2977,
"ratio": 2.11
},
"conditional": {
"no_loss": {
"n": 46907,
"rtt_median": 11.0,
"jitter_median": 1.0,
"tcp_median": 14.521,
"tcp_p95": 31.995,
"tcp_missing_pct": 0.0,
"http_median": 81.362,
"http_p95": 234.902,
"http_over_1s_pct": 2.54,
"dns_recursive_over_200ms_pct": 1.75,
"gateway_loss_pct": 0.0
},
"one_lost": {
"n": 6309,
"rtt_median": 11.778,
"jitter_median": 2.125,
"tcp_median": 14.265,
"tcp_p95": 32.66,
"tcp_missing_pct": 0.0,
"http_median": 85.113,
"http_p95": 1278.521,
"http_over_1s_pct": 7.47,
"dns_recursive_over_200ms_pct": 5.22,
"gateway_loss_pct": 0.0
},
"two_plus_lost": {
"n": 1383,
"rtt_median": 12.625,
"jitter_median": 3.286,
"tcp_median": 14.392,
"tcp_p95": 34.071,
"tcp_missing_pct": 0.07,
"http_median": 89.658,
"http_p95": 1485.044,
"http_over_1s_pct": 16.34,
"dns_recursive_over_200ms_pct": 9.6,
"gateway_loss_pct": 0.07
}
}
},
"tcp_icmp": {
"tcp_min_minus_icmp_min_median_ms": 2.27,
"tcp_median_minus_icmp_avg_median_ms": 2.925,
"split_local": "2026-10-06T22:00",
"long_path_share_before_pct": 7.22,
"long_path_share_after_pct": 63.73,
"after_split": {
"tcp_min_p25": 12.925,
"tcp_min_median": 18.556,
"tcp_min_p75": 22.233,
"icmp_min_median": 10.0,
"icmp_avg_median": 10.5,
"share_tcp_min_over_17ms_pct": 55.64
},
"before_split": {
"tcp_min_median": 12.218,
"icmp_min_median": 10.0
}
},
"dns_http": {
"dns_cached": {
"median": 36.026,
"p05": 17.031,
"p95": 74.878,
"share_under_15ms_pct": 3.38,
"share_under_5ms_pct": 0.01
},
"dns_recursive": {
"median": 59.242,
"p95": 106.31,
"p99": 1266.18,
"share_over_200ms_pct": 2.35
},
"dns_recursive_minus_cached_median_ms": 20.16,
"dns_timeouts": 24,
"dns_timeouts_during_outages": 14,
"http": {
"median": 81.911,
"p90": 155.012,
"p95": 271.36,
"p99": 1375.212,
"share_1000_1400ms_pct": 2.48,
"share_3900_4400ms_pct": 0.55,
"share_over_1s_pct": 3.45,
"share_over_5s_pct": 0.08,
"timeouts": 32,
"status_counts": {
"200": 54565
}
}
},
"autocorrelation": {
"lag_minutes": [
0.5,
1,
2.5,
5,
10,
30,
60,
180,
360,
720,
1440
],
"lag_samples": [
1,
2,
5,
10,
20,
60,
120,
360,
720,
1440,
2880
],
"values": {
"rtt_avg_ms": [
0.737,
0.658,
0.582,
0.52,
0.49,
0.473,
0.386,
0.259,
0.118,
0.097,
0.025
],
"log_rtt_avg_ms": [
0.808,
0.806,
0.768,
0.762,
0.731,
0.68,
0.597,
0.422,
0.223,
0.182,
0.092
],
"jitter_ms": [
0.438,
0.457,
0.397,
0.415,
0.391,
0.356,
0.291,
0.252,
0.205,
0.232,
0.174
],
"loss_indicator": [
0.182,
0.175,
0.181,
0.169,
0.167,
0.156,
0.145,
0.135,
0.089,
0.04,
0.097
],
"tcp_connect_min_ms": [
0.281,
0.217,
0.203,
0.151,
0.149,
0.143,
0.123,
0.092,
0.055,
0.038,
0.016
],
"dns_recursive_ms": [
0.035,
0.035,
0.026,
0.02,
0.025,
0.023,
0.023,
0.016,
0.004,
0.0,
0.008
],
"http_ms": [
0.061,
0.059,
0.047,
0.045,
0.046,
0.034,
0.039,
0.042,
0.028,
0.017,
0.013
]
}
},
"speedtest": {
"tests": 460,
"servers": 162,
"failed_latency_probe": 79,
"zero_download": 7,
"zero_upload": 4,
"download": {
"n": 460,
"median": 34.725,
"mean": 68.463,
"p95": 318.275,
"p99": 417.581,
"max": 480.72
},
"upload": {
"n": 460,
"median": 28.625,
"mean": 26.121,
"p95": 41.142,
"p99": 44.101,
"max": 54.17
},
"download_quantiles": {
"0.1": 9.082,
"0.25": 15.84,
"0.5": 34.725,
"0.75": 65.045,
"0.9": 183.019
},
"upload_quantiles": {
"0.1": 9.366,
"0.25": 15.015,
"0.5": 28.625,
"0.75": 37.992,
"0.9": 40.281
},
"ping_valid": {
"n": 381,
"median": 52.058,
"mean": 93.665,
"p95": 196.381,
"p99": 396.917,
"max": 1167.189
},
"download_median_night_0_4": 61.52,
"download_median_day_9_16": 22.005,
"sample_duration_median_s": 34.91,
"top_servers": [
{
"server": "Spectrum, New York, NY",
"n": 16,
"download_median": 133.0,
"download_max": 319.5,
"upload_median": 38.4,
"ping_median": 20.9
},
{
"server": "Surfshark Ltd, New York, NY",
"n": 15,
"download_median": 56.7,
"download_max": 480.7,
"upload_median": 39.1,
"ping_median": 28.0
},
{
"server": "WebNX Inc, New York, NY",
"n": 15,
"download_median": 44.5,
"download_max": 252.4,
"upload_median": 39.7,
"ping_median": 29.2
},
{
"server": "Summit Broadband, Orlando, FL",
"n": 13,
"download_median": 34.3,
"download_max": 61.9,
"upload_median": 37.7,
"ping_median": 43.6
},
{
"server": "GOZFLY LLC, Herndon, VA",
"n": 9,
"download_median": 22.6,
"download_max": 80.6,
"upload_median": 33.8,
"ping_median": 20.6
},
{
"server": "EZEE Fiber, Chicago, IL",
"n": 9,
"download_median": 41.6,
"download_max": 62.6,
"upload_median": 35.8,
"ping_median": 44.0
},
{
"server": "Spectrum, Oxford, MA",
"n": 9,
"download_median": 371.8,
"download_max": 456.5,
"upload_median": 40.7,
"ping_median": 28.6
},
{
"server": "University of Florida, Gainesville, FL",
"n": 8,
"download_median": 20.9,
"download_max": 53.9,
"upload_median": 35.3,
"ping_median": 39.6
},
{
"server": "Summit Broadband, Bonita Springs, FL",
"n": 7,
"download_median": 85.8,
"download_max": 105.3,
"upload_median": 37.0,
"ping_median": 49.6
},
{
"server": "Redel Internet, Balne\u00e1rio Cambori\u00fa",
"n": 6,
"download_median": 36.2,
"download_max": 37.4,
"upload_median": 19.8,
"ping_median": 142.8
}
]
},
"labels": {
"counts": {
"label_outage": 18,
"label_packet_loss": 7692,
"label_high_latency": 3067,
"label_high_jitter": 5074,
"label_gateway_degraded": 560,
"label_anomaly": 13036
},
"share_pct": {
"label_outage": 0.03,
"label_packet_loss": 14.08,
"label_high_latency": 5.62,
"label_high_jitter": 9.29,
"label_gateway_degraded": 1.03,
"label_anomaly": 23.87
},
"exactly_one_label": 10205,
"two_or_more_labels": 2831,
"high_latency_in_episodes_pct": 88.4,
"episode_kinds": {
"path change": 6,
"first hop": 3,
"queueing": 0
}
}
}123version https://git-lfs.github.com/spec/v1oid sha256:6fe30f9a91afeb018196711470e29b61ee367a8cb638b3fdf05bc4eec0afd400size 18452443123version https://git-lfs.github.com/spec/v1oid sha256:b9dee301cd18939c36b91765ad8d0198e1c98caea620c3fae15b8377df8b4ee1size 3500919123version https://git-lfs.github.com/spec/v1oid sha256:d37484c1c71b75ab52df3574d028e16234fc4978900d0ebd54a70c76808d0cc0size 15198518123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220{
"run_id": "desktop-eth_20260920_123407",
"host_label": "desktop-eth",
"collector_version": "2.0.0",
"status": "running",
"started_utc": "2026-09-20T16:34:18Z",
"updated_utc": "2026-10-09T19:45:22Z",
"planned_duration_s": 2592000.0,
"elapsed_s": 1653039.2,
"interval_s": 30.0,
"sample_count": 54608,
"first_sample_utc": "2026-09-20T16:34:22Z",
"last_sample_utc": "2026-10-09T19:45:13Z",
"csv_file": "localnet_desktop-eth_20260920_123407.csv",
"config": {
"target": "8.8.8.8",
"ping_count": 10,
"gateway_ping_count": 5,
"ping_timeout_s": 2.0,
"tcp_port": 443,
"tcp_count": 5,
"dns_host": "example.com",
"dns_server": "192.168.1.1",
"dns_timeout_s": 3.0,
"http_url": "http://www.msftconnecttest.com/connecttest.txt",
"http_timeout_s": 5.0,
"wifi": true,
"record_ssid": false,
"speedtest": true,
"speedtest_every_s": 3600.0,
"speedtest_server_id": null,
"iperf_server": null,
"iperf_port": 5201,
"iperf_every_s": null,
"iperf_duration_s": 10,
"iperf_reverse": false
},
"environment": {
"os": "Windows-11-10.0.26200-SP0",
"python": "3.12.12",
"machine": "AMD64",
"timezone": "Eastern Daylight Time",
"utc_offset_s": -14400,
"ping_resolution_ms": 1.0
},
"network": {
"gateway_ip": "192.168.1.1",
"interface": null,
"local_ip": "192.168.1.217",
"link_type": "unknown",
"link_types_seen": {
"unknown": 54608
},
"detection_source": "route print"
},
"summary": {
"rtt_avg_ms": {
"count": 54590,
"mean": 12.581,
"median": 11.1,
"min": 9.3,
"max": 288.6,
"p95": 22.3,
"stddev": 5.217
},
"rtt_min_ms": {
"count": 54590,
"mean": 10.432,
"median": 10.0,
"min": 5.0,
"max": 263.0,
"p95": 14.0,
"stddev": 3.125
},
"rtt_max_ms": {
"count": 54590,
"mean": 17.87,
"median": 13.0,
"min": 10.0,
"max": 373.0,
"p95": 32.0,
"stddev": 10.344
},
"jitter_ms": {
"count": 54590,
"mean": 2.306,
"median": 1.0,
"min": 0.0,
"max": 59.778,
"p95": 7.667,
"stddev": 2.692
},
"packet_loss_pct": {
"count": 54608,
"mean": 1.764,
"median": 0.0,
"min": 0.0,
"max": 100.0,
"p95": 10.0,
"stddev": 5.072
},
"gateway_rtt_avg_ms": {
"count": 54590,
"mean": 0.321,
"median": 0.2,
"min": 0.0,
"max": 89.4,
"p95": 0.8,
"stddev": 1.319
},
"gateway_packet_loss_pct": {
"count": 54608,
"mean": 0.033,
"median": 0.0,
"min": 0.0,
"max": 100.0,
"p95": 0.0,
"stddev": 1.817
},
"tcp_connect_median_ms": {
"count": 54589,
"mean": 19.311,
"median": 14.483,
"min": 11.262,
"max": 1524.463,
"p95": 32.127,
"stddev": 18.435
},
"dns_resolve_ms": {
"count": 54586,
"mean": 43.595,
"median": 36.025,
"min": 3.743,
"max": 3252.214,
"p95": 74.864,
"stddev": 70.374
},
"dns_recursive_ms": {
"count": 54581,
"mean": 87.278,
"median": 59.238,
"min": 16.657,
"max": 25645.041,
"p95": 106.313,
"stddev": 230.545
},
"http_ms": {
"count": 54556,
"mean": 154.754,
"median": 81.91,
"min": 23.451,
"max": 13111.02,
"p95": 271.398,
"stddev": 403.142
},
"wifi_signal_pct": {
"count": 4,
"mean": 85.75,
"median": 85.0,
"min": 84.0,
"max": 89.0,
"p95": 89.0,
"stddev": 1.92
},
"wifi_rssi_dbm": {
"count": 4,
"mean": -57.125,
"median": -57.5,
"min": -58.0,
"max": -55.5,
"p95": -55.5,
"stddev": 0.96
},
"wifi_rx_mbps": {
"count": 4,
"mean": 866.7,
"median": 866.7,
"min": 866.7,
"max": 866.7,
"p95": 866.7,
"stddev": 0.0
},
"download_mbps": {
"count": 460,
"mean": 68.463,
"median": 34.725,
"min": 0.0,
"max": 480.72,
"p95": 319.51,
"stddev": 93.847
},
"upload_mbps": {
"count": 460,
"mean": 26.121,
"median": 28.625,
"min": 0.0,
"max": 54.17,
"p95": 41.17,
"stddev": 12.608
},
"speedtest_ping_ms": {
"count": 460,
"mean": 306603.157,
"median": 78.725,
"min": 16.672,
"max": 1800000.0,
"p95": 1800000.0,
"stddev": 674249.533
},
"sample_duration_s": {
"count": 54608,
"mean": 9.789,
"median": 9.21,
"min": 9.06,
"max": 114.85,
"p95": 11.23,
"stddev": 2.964
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231{
"generated_utc": "2026-10-10T05:42:01Z",
"builder_version": "2.0.1",
"rows": 54617,
"columns": 67,
"runs": [
{
"run_id": "desktop-eth_20260920_123407",
"host_label": "desktop-eth",
"rows": 54617,
"first_utc": "2026-09-20T16:34:22Z",
"last_utc": "2026-10-09T19:49:43Z",
"span_hours": 459.26,
"interval_s": 30.0,
"coverage_pct": 99.1,
"link_types": {
"unknown": 54617
},
"collector_version": "2.0.0",
"os": "Windows-11-10.0.26200-SP0",
"status": "running",
"thresholds": {
"rtt_avg_ms": {
"n": 54599,
"median": 11.1,
"mad": 0.678,
"threshold": 21.1
},
"jitter_ms": {
"n": 54599,
"median": 1.0,
"mad": 0.556,
"threshold": 6.0
},
"gateway_rtt_avg_ms": {
"n": 54599,
"median": 0.2,
"mad": 0.2,
"threshold": 5.2
}
}
}
],
"first_utc": "2026-09-20T16:34:22Z",
"last_utc": "2026-10-09T19:49:43Z",
"span_days": 19.14,
"coverage_pct": 99.1,
"label_rule": {
"mad_k": 5.0,
"description": "threshold = median + max(k * 1.4826 * MAD, absolute floor, relative floor * median), computed per run",
"floors": {
"rtt_avg_ms": {
"absolute_ms": 10.0,
"relative": 0.5
},
"jitter_ms": {
"absolute_ms": 5.0,
"relative": 1.0
},
"gateway_rtt_avg_ms": {
"absolute_ms": 5.0,
"relative": 1.0
}
}
},
"labels": {
"label_outage": {
"rows": 18,
"share_pct": 0.033
},
"label_packet_loss": {
"rows": 7692,
"share_pct": 14.084
},
"label_high_latency": {
"rows": 3067,
"share_pct": 5.615
},
"label_high_jitter": {
"rows": 5074,
"share_pct": 9.29
},
"label_gateway_degraded": {
"rows": 560,
"share_pct": 1.025
},
"label_anomaly": {
"rows": 13036,
"share_pct": 23.868
}
},
"events": 0,
"metrics": {
"rtt_avg_ms": {
"count": 54599,
"mean": 12.581,
"median": 11.1,
"p95": 22.3,
"min": 9.3,
"max": 288.6
},
"rtt_min_ms": {
"count": 54599,
"mean": 10.432,
"median": 10.0,
"p95": 14.0,
"min": 5.0,
"max": 263.0
},
"rtt_max_ms": {
"count": 54599,
"mean": 17.869,
"median": 13.0,
"p95": 32.0,
"min": 10.0,
"max": 373.0
},
"jitter_ms": {
"count": 54599,
"mean": 2.306,
"median": 1.0,
"p95": 7.667,
"min": 0.0,
"max": 59.778
},
"packet_loss_pct": {
"count": 54617,
"mean": 1.763,
"median": 0.0,
"p95": 10.0,
"min": 0.0,
"max": 100.0
},
"gateway_rtt_avg_ms": {
"count": 54599,
"mean": 0.321,
"median": 0.2,
"p95": 0.8,
"min": 0.0,
"max": 89.4
},
"gateway_packet_loss_pct": {
"count": 54617,
"mean": 0.033,
"median": 0.0,
"p95": 0.0,
"min": 0.0,
"max": 100.0
},
"tcp_connect_median_ms": {
"count": 54598,
"mean": 19.311,
"median": 14.484,
"p95": 32.127,
"min": 11.262,
"max": 1524.463
},
"dns_resolve_ms": {
"count": 54595,
"mean": 43.594,
"median": 36.026,
"p95": 74.878,
"min": 3.743,
"max": 3252.214
},
"dns_recursive_ms": {
"count": 54590,
"mean": 87.275,
"median": 59.242,
"p95": 106.31,
"min": 16.657,
"max": 25645.041
},
"http_ms": {
"count": 54565,
"mean": 154.745,
"median": 81.911,
"p95": 271.36,
"min": 23.451,
"max": 13111.02
},
"wifi_signal_pct": {
"count": 4,
"mean": 85.75,
"median": 85.0,
"p95": 88.4,
"min": 84.0,
"max": 89.0
},
"wifi_rssi_dbm": {
"count": 4,
"mean": -57.125,
"median": -57.5,
"p95": -55.8,
"min": -58.0,
"max": -55.5
},
"wifi_rx_mbps": {
"count": 4,
"mean": 866.7,
"median": 866.7,
"p95": 866.7,
"min": 866.7,
"max": 866.7
},
"download_mbps": {
"count": 460,
"mean": 68.463,
"median": 34.725,
"p95": 318.275,
"min": 0.0,
"max": 480.72
},
"upload_mbps": {
"count": 460,
"mean": 26.121,
"median": 28.625,
"p95": 41.142,
"min": 0.0,
"max": 54.17
},
"speedtest_ping_ms": {
"count": 381,
"mean": 93.665,
"median": 52.058,
"p95": 196.381,
"min": 16.672,
"max": 1167.189
}
}
}123version https://git-lfs.github.com/spec/v1oid sha256:98d60d1ef32d2a2bc99d4161c04cbbcace3443132b6800836102bb054a448904size 417997123version https://git-lfs.github.com/spec/v1oid sha256:6432a5b991cb038ddaf02e79914252b6fc0168934079266b7dd066d483c0fb62size 162338123version https://git-lfs.github.com/spec/v1oid sha256:4c1ad55efbb3baa639349a262270464ed3530cba9ed3ca3b68c68d735af85c4esize 125522123456789# The collector (scripts/collect_data.py) needs only the Python standard library.# These packages are used by the build, analysis, plotting, packaging and test# scripts, and by the speed-test fallback when the Ookla CLI is not installed.pandas>=1.5numpy>=1.21pyarrow>=12.0matplotlib>=3.6pytest>=7.0speedtest-cli>=2.1.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557#!/usr/bin/env python3"""Analyse the consolidated LocalNet-Dynamics dataset.
Reads dataset/localnet_dynamics.parquet (or .csv), prints a text report andwrites dataset/analysis.json with every number the documentation quotes:overall statistics, hour-of-day and day-by-day profiles, the two regimesseparated by a change point in the daily loss share, outage and high-latencyepisodes with their diagnosis (path change, first hop, queueing), theconditional effect of ICMP loss on the other probes, the ICMP/TCP path split,DNS and HTTP facts, autocorrelation, speed-test quality and label statistics.
python analyze.py python analyze.py --input dataset/localnet_dynamics.csv --no-report
The figures are rendered by plot_figures.py from the same functions."""
from __future__ import annotations
import argparseimport jsonimport sysfrom datetime import datetime, timezonefrom pathlib import Path
import numpy as npimport pandas as pd
ROOT = Path(__file__).resolve().parent.parent
METRICS = ["rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct", "gateway_rtt_avg_ms", "tcp_connect_min_ms", "tcp_connect_median_ms", "dns_resolve_ms", "dns_recursive_ms", "http_ms", "download_mbps", "upload_mbps"]LABELS = ["label_outage", "label_packet_loss", "label_high_latency", "label_high_jitter", "label_gateway_degraded", "label_anomaly"]ACF_LAGS_MIN = [0.5, 1, 2.5, 5, 10, 30, 60, 180, 360, 720, 1440]
# Latency episodes: runs of label_high_latency, merged across gaps of at most# MERGE_GAP samples and kept when they span at least MIN_EPISODE_MIN minutes.MERGE_GAP = 10MIN_EPISODE_MIN = 30# An episode whose first-hop RTT exceeds the run's gateway threshold is a# first-hop event; one whose ICMP or TCP latency floor rises by at least# FLOOR_SHIFT_MS over the run median is a path change; anything else is queueing.FLOOR_SHIFT_MS = 5.0TCP_SPLIT_MS = 5.0 # TCP floor above ICMP floor by more than thisSPEEDTEST_PING_FAILED_MS = 600_000 # speedtest-cli counts a failed latency probe as 3600 s
# --------------------------------------------------------------------------- ## Loading and helpers# --------------------------------------------------------------------------- #
def load(path: Path) -> pd.DataFrame: df = pd.read_parquet(path) if path.suffix == ".parquet" else pd.read_csv(path, low_memory=False) df["ts"] = pd.to_datetime(df["timestamp_utc"], utc=True) df["ts_local"] = pd.to_datetime(df["timestamp_local"].astype(str).str[:19], format="%Y-%m-%dT%H:%M:%S", errors="coerce") for col in LABELS: if col in df.columns: df[col] = df[col].fillna(0).astype(int) for col in METRICS + ["gateway_packet_loss_pct", "packets_received", "speedtest_ping_ms"]: if col in df.columns: df[col] = pd.to_numeric(df[col], errors="coerce").astype(float) return df.sort_values("ts").reset_index(drop=True)
def q(series: pd.Series, p: float) -> float | None: v = series.dropna() return round(float(v.quantile(p)), 3) if len(v) else None
def describe(series: pd.Series) -> dict | None: v = series.dropna().astype(float) if v.empty: return None return {"n": int(v.size), "median": round(float(v.median()), 3), "mean": round(float(v.mean()), 3), "p95": round(float(v.quantile(0.95)), 3), "p99": round(float(v.quantile(0.99)), 3), "max": round(float(v.max()), 3)}
def share(mask: pd.Series) -> float: return round(100.0 * float(mask.mean()), 2) if len(mask) else 0.0
def change_point(series: pd.Series) -> tuple: """Split index that minimises the within-segment sum of squares (one break).""" x = series.dropna().values.astype(float) n = len(x) if n < 4: k = max(1, n // 2) return series.dropna().index[k], float(x[:k].mean()), float(x[k:].mean()) cs, cs2 = np.cumsum(x), np.cumsum(x * x) best = None for k in range(2, n - 1): a = cs2[k - 1] - cs[k - 1] ** 2 / k b = (cs2[-1] - cs2[k - 1]) - (cs[-1] - cs[k - 1]) ** 2 / (n - k) if best is None or a + b < best[0]: best = (a + b, k) k = best[1] return series.dropna().index[k], float(x[:k].mean()), float(x[k:].mean())
def runs_of(mask: np.ndarray, merge_gap: int) -> list[tuple[int, int]]: idx = np.flatnonzero(mask) if idx.size == 0: return [] runs, start, prev = [], idx[0], idx[0] for i in idx[1:]: if i - prev > merge_gap: runs.append((start, prev)) start = i prev = i runs.append((start, prev)) return runs
def acf(series: pd.Series, lag: int) -> float | None: s = series.astype(float) if lag >= len(s) - 2: return None value = s.autocorr(lag) return round(float(value), 3) if np.isfinite(value) else None
# --------------------------------------------------------------------------- ## Sections# --------------------------------------------------------------------------- #
def overview(df: pd.DataFrame, summary: dict | None) -> dict: span = (df["ts"].max() - df["ts"].min()).total_seconds() / 86400.0 out = { "rows": int(len(df)), "runs": int(df["run_id"].nunique()), "first_utc": df["ts"].min().strftime("%Y-%m-%dT%H:%M:%SZ"), "last_utc": df["ts"].max().strftime("%Y-%m-%dT%H:%M:%SZ"), "first_local": str(df["timestamp_local"].iloc[0]), "last_local": str(df["timestamp_local"].iloc[-1]), "span_days": round(span, 2), "full_days": int((df.groupby("date_local").size() >= 2700).sum()), "coverage_pct": summary.get("coverage_pct") if summary else None, "max_gap_s": float(df["gap_before_s"].max()), "gaps_of_2_intervals": int((df["gap_before_s"] == 2 * df["interval_s"].median()).sum()), "gaps_over_2_intervals": int((df["gap_before_s"] > 2 * df["interval_s"].median()).sum()), "gaps_over_2_intervals_after_speedtest": int((df["download_mbps"].shift(1).notna() & (df["gap_before_s"] > 2 * df["interval_s"].median())).sum()), "rows_with_notes": int(df["notes"].fillna("").astype(str).str.len().gt(0).sum()), "wifi_rows": int(df["wifi_signal_pct"].notna().sum()) if "wifi_signal_pct" in df else 0, "link_types": {str(k): int(v) for k, v in df["link_type"].value_counts().items()}, "metrics": {c: describe(df[c]) for c in METRICS if c in df.columns and describe(df[c])}, } return out
def hour_profile(df: pd.DataFrame) -> list[dict]: rows = [] for hour, part in df.groupby("hour_local"): rows.append({ "hour": int(hour), "n": int(len(part)), "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p25": q(part["rtt_avg_ms"], 0.25), "rtt_p75": q(part["rtt_avg_ms"], 0.75), "rtt_p95": q(part["rtt_avg_ms"], 0.95), "jitter_median": q(part["jitter_ms"], 0.5), "loss_share_pct": share(part["packet_loss_pct"] > 0), "loss_share_weekday_pct": share(part.loc[part["is_weekend"] == 0, "packet_loss_pct"] > 0), "loss_share_weekend_pct": share(part.loc[part["is_weekend"] == 1, "packet_loss_pct"] > 0), "http_p95": q(part["http_ms"], 0.95), "http_over_1s_pct": share(part["http_ms"].dropna() > 1000), "high_latency_pct": share(part["label_high_latency"] == 1), "gateway_p95": q(part["gateway_rtt_avg_ms"], 0.95), }) return rows
def weekday_weekend(df: pd.DataFrame) -> dict: out = {} for name, part in (("weekday", df[df["is_weekend"] == 0]), ("weekend", df[df["is_weekend"] == 1])): out[name] = {"n": int(len(part)), "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p95": q(part["rtt_avg_ms"], 0.95), "loss_share_pct": share(part["packet_loss_pct"] > 0), "jitter_median": q(part["jitter_ms"], 0.5), "http_median": q(part["http_ms"], 0.5)} return out
def daily(df: pd.DataFrame) -> list[dict]: rows = [] for date, part in df.groupby("date_local"): rows.append({ "date": str(date), "weekday": int(part["weekday_local"].iloc[0]), "n": int(len(part)), "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p95": q(part["rtt_avg_ms"], 0.95), "rtt_min_median": q(part["rtt_min_ms"], 0.5), "tcp_min_median": q(part["tcp_connect_min_ms"], 0.5), "loss_share_pct": share(part["packet_loss_pct"] > 0), "mean_loss_pct": round(float(part["packet_loss_pct"].mean()), 3), "jitter_median": q(part["jitter_ms"], 0.5), "http_p95": q(part["http_ms"], 0.95), "anomaly_pct": share(part["label_anomaly"] == 1), "gateway_degraded": int(part["label_gateway_degraded"].sum()), }) return rows
def period_stats(part: pd.DataFrame) -> dict: return { "n": int(len(part)), "days": int(part["date_local"].nunique()), "rtt_median": q(part["rtt_avg_ms"], 0.5), "rtt_p95": q(part["rtt_avg_ms"], 0.95), "rtt_p99": q(part["rtt_avg_ms"], 0.99), "jitter_median": q(part["jitter_ms"], 0.5), "jitter_p95": q(part["jitter_ms"], 0.95), "loss_share_pct": share(part["packet_loss_pct"] > 0), "mean_loss_pct": round(float(part["packet_loss_pct"].mean()), 3), "tcp_median": q(part["tcp_connect_median_ms"], 0.5), "dns_cached_median": q(part["dns_resolve_ms"], 0.5), "dns_recursive_median": q(part["dns_recursive_ms"], 0.5), "http_median": q(part["http_ms"], 0.5), "http_p95": q(part["http_ms"], 0.95), "http_over_1s_pct": share(part["http_ms"].dropna() > 1000), "labels_pct": {c: share(part[c] == 1) for c in LABELS}, }
def regimes(df: pd.DataFrame) -> dict: daily_loss = df.groupby("date_local")["packet_loss_pct"].apply(lambda s: float((s > 0).mean())) if len(daily_loss) < 2: split, before, after = daily_loss.index[0], float(daily_loss.iloc[0]), float(daily_loss.iloc[0]) first = second = df else: split, before, after = change_point(daily_loss) first = df[df["date_local"] < split] second = df[df["date_local"] >= split] return { "method": "single least-squares change point in the daily share of samples with ICMP loss", "split_date": str(split), "daily_loss_share_before_pct": round(100 * before, 2), "daily_loss_share_after_pct": round(100 * after, 2), "before": {"first_date": str(first["date_local"].min()), "last_date": str(first["date_local"].max()), **period_stats(first)}, "after": {"first_date": str(second["date_local"].min()), "last_date": str(second["date_local"].max()), **period_stats(second)}, }
def outages(df: pd.DataFrame) -> list[dict]: out = [] for a, b in runs_of(df["label_outage"].values == 1, merge_gap=2): part = df.iloc[a:b + 1] interval = float(df["interval_s"].median()) out.append({ "start_local": str(part["timestamp_local"].iloc[0]), "end_local": str(part["timestamp_local"].iloc[-1]), "weekday": int(part["weekday_local"].iloc[0]), "samples": int(len(part)), "minutes": round((float(part["epoch_s"].iloc[-1] - part["epoch_s"].iloc[0]) + interval) / 60.0, 1), "gateway_unreachable": bool((part["gateway_packet_loss_pct"] == 100).all()), "gateway_loss_sample_before": float(df["gateway_packet_loss_pct"].iloc[a - 1]) if a > 0 else None, }) return out
def latency_episodes(df: pd.DataFrame, thresholds: dict) -> list[dict]: """High-latency episodes with a diagnosis from the probe that moved.""" out = [] for run_id, part in df.groupby("run_id", sort=False): part = part.reset_index(drop=True) rtt_floor = float(part["rtt_min_ms"].median()) tcp_floor = float(part["tcp_connect_min_ms"].median()) gw_thr = (thresholds.get(run_id, {}).get("gateway_rtt_avg_ms") or {}).get("threshold") for a, b in runs_of(part["label_high_latency"].values == 1, MERGE_GAP): ep = part.iloc[a:b + 1] minutes = (float(ep["epoch_s"].iloc[-1] - ep["epoch_s"].iloc[0])) / 60.0 if minutes < MIN_EPISODE_MIN: continue rtt_min_med = float(ep["rtt_min_ms"].median()) tcp_min_med = float(ep["tcp_connect_min_ms"].median()) gw_med = float(ep["gateway_rtt_avg_ms"].median()) if gw_thr is not None and gw_med > gw_thr: kind = "first hop" elif max(rtt_min_med - rtt_floor, tcp_min_med - tcp_floor) >= FLOOR_SHIFT_MS: kind = "path change" else: kind = "queueing" out.append({ "run_id": run_id, "start_local": str(ep["timestamp_local"].iloc[0]), "end_local": str(ep["timestamp_local"].iloc[-1]), "weekday": int(ep["weekday_local"].iloc[0]), "hours": round(minutes / 60.0, 2), "samples": int(len(ep)), "labelled_samples": int(ep["label_high_latency"].sum()), "rtt_min_median": round(rtt_min_med, 2), "rtt_avg_median": q(ep["rtt_avg_ms"], 0.5), "tcp_min_median": round(tcp_min_med, 2), "gateway_median": round(gw_med, 2), "jitter_median": q(ep["jitter_ms"], 0.5), "dns_cached_median": q(ep["dns_resolve_ms"], 0.5), "http_median": q(ep["http_ms"], 0.5), "loss_share_pct": share(ep["packet_loss_pct"] > 0), "run_rtt_min_median": round(rtt_floor, 2), "run_tcp_min_median": round(tcp_floor, 2), "kind": kind, }) return out
def loss_analysis(df: pd.DataFrame) -> dict: ok = df[df["label_outage"] == 0] received = ok["packets_received"].dropna().astype(int) classes = { "no_loss": ok[ok["packet_loss_pct"] == 0], "one_lost": ok[ok["packets_received"] == ok["packets_sent"] - 1], "two_plus_lost": ok[(ok["packets_received"] <= ok["packets_sent"] - 2) & (ok["packets_received"] > 0)], } conditional = {} for name, part in classes.items(): conditional[name] = { "n": int(len(part)), "rtt_median": q(part["rtt_avg_ms"], 0.5), "jitter_median": q(part["jitter_ms"], 0.5), "tcp_median": q(part["tcp_connect_median_ms"], 0.5), "tcp_p95": q(part["tcp_connect_median_ms"], 0.95), "tcp_missing_pct": share(part["tcp_connect_median_ms"].isna()), "http_median": q(part["http_ms"], 0.5), "http_p95": q(part["http_ms"], 0.95), "http_over_1s_pct": share(part["http_ms"].dropna() > 1000), "dns_recursive_over_200ms_pct": share(part["dns_recursive_ms"].dropna() > 200), "gateway_loss_pct": share(part["gateway_packet_loss_pct"] > 0), } indicator = (df["packet_loss_pct"] > 0).astype(int) p_loss = float(indicator.mean()) p_cond = float(indicator[1:][indicator[:-1].values == 1].mean()) return { "samples_with_loss_pct": share(df["packet_loss_pct"] > 0), "mean_loss_pct": round(float(df["packet_loss_pct"].mean()), 3), "packets_received_counts": {int(k): int(v) for k, v in received.value_counts().sort_index().items()}, "gateway_loss_samples_pct": share(df["gateway_packet_loss_pct"] > 0), "gateway_loss_outside_outages_samples": int((ok["gateway_packet_loss_pct"] > 0).sum()), "persistence": {"p_loss": round(p_loss, 4), "p_loss_given_previous_loss": round(p_cond, 4), "ratio": round(p_cond / p_loss, 2) if p_loss else None}, "conditional": conditional, }
def tcp_icmp(df: pd.DataFrame) -> dict: gap = df["tcp_connect_min_ms"] - df["rtt_min_ms"] hourly = (gap > TCP_SPLIT_MS).astype(float).groupby(df["ts_local"].dt.floor("h")).mean() split, before, after = change_point(hourly) sec = df[df["ts_local"] >= split] v = sec["tcp_connect_min_ms"].dropna() return { "tcp_min_minus_icmp_min_median_ms": round(float(gap.median()), 3), "tcp_median_minus_icmp_avg_median_ms": round(float((df["tcp_connect_median_ms"] - df["rtt_avg_ms"]).median()), 3), "split_local": split.strftime("%Y-%m-%dT%H:%M"), "long_path_share_before_pct": round(100 * before, 2), "long_path_share_after_pct": round(100 * after, 2), "after_split": { "tcp_min_p25": q(v, 0.25), "tcp_min_median": q(v, 0.5), "tcp_min_p75": q(v, 0.75), "icmp_min_median": q(sec["rtt_min_ms"], 0.5), "icmp_avg_median": q(sec["rtt_avg_ms"], 0.5), "share_tcp_min_over_17ms_pct": share(v > 17), }, "before_split": { "tcp_min_median": q(df.loc[df["ts_local"] < split, "tcp_connect_min_ms"], 0.5), "icmp_min_median": q(df.loc[df["ts_local"] < split, "rtt_min_ms"], 0.5), }, }
def dns_http(df: pd.DataFrame) -> dict: c, r, h = df["dns_resolve_ms"].dropna(), df["dns_recursive_ms"].dropna(), df["http_ms"].dropna() return { "dns_cached": {"median": q(c, 0.5), "p05": q(c, 0.05), "p95": q(c, 0.95), "share_under_15ms_pct": share(c < 15), "share_under_5ms_pct": share(c < 5)}, "dns_recursive": {"median": q(r, 0.5), "p95": q(r, 0.95), "p99": q(r, 0.99), "share_over_200ms_pct": share(r > 200)}, "dns_recursive_minus_cached_median_ms": round(float((df["dns_recursive_ms"] - df["dns_resolve_ms"]).median()), 2), "dns_timeouts": int(df["notes"].fillna("").astype(str).str.contains("dns: timeout|dns recursive: timeout").sum()), "dns_timeouts_during_outages": int((df["notes"].fillna("").astype(str).str.contains("dns: timeout|dns recursive: timeout") & (df["label_outage"] == 1)).sum()), "http": {"median": q(h, 0.5), "p90": q(h, 0.9), "p95": q(h, 0.95), "p99": q(h, 0.99), "share_1000_1400ms_pct": share((h >= 1000) & (h < 1400)), "share_3900_4400ms_pct": share((h >= 3900) & (h < 4400)), "share_over_1s_pct": share(h > 1000), "share_over_5s_pct": share(h > 5000), "timeouts": int(df["notes"].fillna("").astype(str).str.contains("http: timed out").sum()), "status_counts": {str(int(k)): int(v) for k, v in df["http_status"].dropna().value_counts().items()}}, }
def autocorrelation(df: pd.DataFrame) -> dict: interval = float(df["interval_s"].median()) lags = [max(1, int(round(m * 60 / interval))) for m in ACF_LAGS_MIN] series = { "rtt_avg_ms": df["rtt_avg_ms"], "log_rtt_avg_ms": np.log(df["rtt_avg_ms"]), "jitter_ms": df["jitter_ms"], "loss_indicator": (df["packet_loss_pct"] > 0).astype(float), "tcp_connect_min_ms": df["tcp_connect_min_ms"], "dns_recursive_ms": df["dns_recursive_ms"], "http_ms": df["http_ms"], } return {"lag_minutes": ACF_LAGS_MIN, "lag_samples": lags, "values": {name: [acf(s, l) for l in lags] for name, s in series.items()}}
def speedtest(df: pd.DataFrame) -> dict: sp = df[df["download_mbps"].notna()].copy() if sp.empty: return {"tests": 0} failed_ping = sp["speedtest_ping_ms"].isna() | (sp["speedtest_ping_ms"] >= SPEEDTEST_PING_FAILED_MS) top = (sp.groupby("speedtest_server") .agg(n=("download_mbps", "size"), download_median=("download_mbps", "median"), download_max=("download_mbps", "max"), upload_median=("upload_mbps", "median"), ping_median=("speedtest_ping_ms", "median")) .sort_values("n", ascending=False).head(10)) return { "tests": int(len(sp)), "servers": int(sp["speedtest_server"].nunique()), "failed_latency_probe": int(failed_ping.sum()), "zero_download": int((sp["download_mbps"] == 0).sum()), "zero_upload": int((sp["upload_mbps"] == 0).sum()), "download": describe(sp["download_mbps"]), "upload": describe(sp["upload_mbps"]), "download_quantiles": {str(p): q(sp["download_mbps"], p) for p in (0.1, 0.25, 0.5, 0.75, 0.9)}, "upload_quantiles": {str(p): q(sp["upload_mbps"], p) for p in (0.1, 0.25, 0.5, 0.75, 0.9)}, "ping_valid": describe(sp.loc[~failed_ping, "speedtest_ping_ms"]), "download_median_night_0_4": q(sp.loc[sp["hour_local"].between(0, 4), "download_mbps"], 0.5), "download_median_day_9_16": q(sp.loc[sp["hour_local"].between(9, 16), "download_mbps"], 0.5), "sample_duration_median_s": q(sp["sample_duration_s"], 0.5), "top_servers": [{"server": str(k), **{c: (int(v) if c == "n" else round(float(v), 1)) for c, v in row.items()}} for k, row in top.iterrows()], }
def labels(df: pd.DataFrame) -> dict: M = df[LABELS[:-1]] return { "counts": {c: int(df[c].sum()) for c in LABELS}, "share_pct": {c: share(df[c] == 1) for c in LABELS}, "exactly_one_label": int((M.sum(axis=1) == 1).sum()), "two_or_more_labels": int((M.sum(axis=1) >= 2).sum()), "high_latency_in_episodes_pct": None, }
# --------------------------------------------------------------------------- ## Report# --------------------------------------------------------------------------- #
def analyse(df: pd.DataFrame, summary: dict | None) -> dict: thresholds = {r["run_id"]: r.get("thresholds", {}) for r in (summary or {}).get("runs", [])} eps = latency_episodes(df, thresholds) result = { "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "overview": overview(df, summary), "hour_profile": hour_profile(df), "weekday_weekend": weekday_weekend(df), "daily": daily(df), "regimes": regimes(df), "outages": outages(df), "latency_episodes": eps, "loss": loss_analysis(df), "tcp_icmp": tcp_icmp(df), "dns_http": dns_http(df), "autocorrelation": autocorrelation(df), "speedtest": speedtest(df), "labels": labels(df), } total = int(df["label_high_latency"].sum()) inside = sum(e["labelled_samples"] for e in eps) result["labels"]["high_latency_in_episodes_pct"] = round(100.0 * inside / total, 1) if total else None result["labels"]["episode_kinds"] = {k: sum(1 for e in eps if e["kind"] == k) for k in ("path change", "first hop", "queueing")} return result
def print_report(r: dict) -> None: o = r["overview"] print(f"rows {o['rows']:,} runs {o['runs']} span {o['span_days']} days " f"{o['first_utc']} -> {o['last_utc']} coverage {o['coverage_pct']} %") print() print(f"{'metric':<24}{'n':>8}{'median':>10}{'mean':>10}{'p95':>10}{'p99':>10}{'max':>12}") for col, d in o["metrics"].items(): print(f"{col:<24}{d['n']:>8}{d['median']:>10.2f}{d['mean']:>10.2f}{d['p95']:>10.2f}" f"{d['p99']:>10.2f}{d['max']:>12.2f}") g = r["regimes"] print() print(f"regimes (split {g['split_date']}):") for name in ("before", "after"): p = g[name] print(f" {name:<7}{p['first_date']} .. {p['last_date']} n={p['n']:,} rtt med {p['rtt_median']} " f"p95 {p['rtt_p95']} loss {p['loss_share_pct']} % jitter med {p['jitter_median']} " f"http>1s {p['http_over_1s_pct']} % anomaly {p['labels_pct']['label_anomaly']} %") print() print(f"outages: {len(r['outages'])}") for e in r["outages"]: print(f" {e['start_local'][:16]} {e['minutes']} min {e['samples']} samples " f"gateway unreachable: {e['gateway_unreachable']}") print() print(f"high-latency episodes >= {MIN_EPISODE_MIN} min: {len(r['latency_episodes'])}") for e in r["latency_episodes"]: print(f" {e['start_local'][:16]} -> {e['end_local'][11:16]} {e['hours']:>5.2f} h " f"rtt min {e['rtt_min_median']:>5.1f} avg {e['rtt_avg_median']:>5.1f} tcp min {e['tcp_min_median']:>5.1f} " f"gw {e['gateway_median']:>5.1f} {e['kind']}") t = r["tcp_icmp"] print() print(f"tcp/icmp: floor offset {t['tcp_min_minus_icmp_min_median_ms']} ms; long-path share " f"{t['long_path_share_before_pct']} % -> {t['long_path_share_after_pct']} % from {t['split_local']}") L = r["loss"] print(f"loss: {L['samples_with_loss_pct']} % of samples; P(loss|loss) = {L['persistence']['p_loss_given_previous_loss']}" f" vs {L['persistence']['p_loss']}") for name, c in L["conditional"].items(): print(f" {name:<14}n={c['n']:>6} jitter med {c['jitter_median']:.2f} tcp med {c['tcp_median']:.2f} " f"http>1s {c['http_over_1s_pct']:.2f} % dns rec>200ms {c['dns_recursive_over_200ms_pct']:.2f} %") s = r["speedtest"] if s.get("tests"): print(f"speed tests: {s['tests']} on {s['servers']} servers, {s['failed_latency_probe']} failed latency probes, " f"{s['zero_download']} zero downloads; download median {s['download']['median']} max {s['download']['max']}; " f"upload median {s['upload']['median']} p95 {s['upload']['p95']}") print() print("labels:") for col, n in r["labels"]["counts"].items(): print(f" {col:<24}{n:>8} ({r['labels']['share_pct'][col]} %)") print() print("hour-of-day (local):") print(f"{'hour':>4}{'n':>7}{'rtt med':>9}{'rtt p95':>9}{'loss %':>8}{'wkday %':>9}{'wkend %':>9}{'http>1s %':>11}{'hi-lat %':>10}") for h in r["hour_profile"]: print(f"{h['hour']:>4}{h['n']:>7}{h['rtt_median']:>9.2f}{h['rtt_p95']:>9.2f}{h['loss_share_pct']:>8.2f}" f"{h['loss_share_weekday_pct']:>9.2f}{h['loss_share_weekend_pct']:>9.2f}{h['http_over_1s_pct']:>11.2f}" f"{h['high_latency_pct']:>10.2f}")
def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description="Statistics and findings for the consolidated dataset.") p.add_argument("--input", default=None, help="consolidated parquet or CSV (default: dataset/localnet_dynamics.parquet)") p.add_argument("--summary", default=None, help="summary.json written by build_dataset.py") p.add_argument("--output", default=None, help="analysis JSON (default: dataset/analysis.json)") p.add_argument("--no-report", action="store_true", help="write the JSON without printing the report") args = p.parse_args(argv)
path = Path(args.input) if args.input else ROOT / "dataset" / "localnet_dynamics.parquet" if not path.exists() and not args.input: path = ROOT / "dataset" / "localnet_dynamics.csv" if not path.exists(): raise SystemExit(f"{path} not found; run build_dataset.py first") summary_path = Path(args.summary) if args.summary else path.parent / "summary.json" summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.exists() else None
df = load(path) result = analyse(df, summary) out = Path(args.output) if args.output else path.parent / "analysis.json" out.write_text(json.dumps(result, indent=2), encoding="utf-8") if not args.no_report: print_report(result) print() print(f"analysis written to {out}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108#!/usr/bin/env python3
"""
Record a manual event annotation for the LocalNet-Dynamics dataset.
Events describe things the collector cannot observe by itself: a household
member starting a 4K stream, a router reboot, a laptop moved to another room,
a known ISP maintenance window. `build_dataset.py` joins them onto every
sample whose timestamp falls inside the event window, producing the
`event_category` and `event_description` columns.
Events are appended to dataset/raw/events.csv with UTC timestamps.
python annotate.py "4K streaming on the living-room TV" --category load --minutes 45
python annotate.py "router rebooted" --category maintenance
python annotate.py "moved laptop to the garden" --category environment \
--start "2026-09-12 16:00" --end "2026-09-12 18:30"
python annotate.py --list
"""
from __future__ import annotations
import argparse
import csv
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
CATEGORIES = ["load", "outage", "maintenance", "environment", "isp", "device", "other"]
COLUMNS = ["start_utc", "end_utc", "category", "description"]
DEFAULT_PATH = Path(__file__).resolve().parent.parent / "dataset" / "raw" / "events.csv"
def parse_time(text: str | None) -> datetime:
"""Interpret a timestamp; naive values are local time."""
if not text or text.lower() == "now":
return datetime.now(timezone.utc)
text = text.strip().replace("Z", "+00:00")
if " " in text and "T" not in text:
text = text.replace(" ", "T", 1)
dt = datetime.fromisoformat(text)
if dt.tzinfo is None:
dt = dt.astimezone() # attach the local zone
return dt.astimezone(timezone.utc)
def fmt(dt: datetime) -> str:
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def append_event(path: Path, start: datetime, end: datetime, category: str, description: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
new_file = not path.exists() or path.stat().st_size == 0
with path.open("a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
if new_file:
writer.writerow(COLUMNS)
writer.writerow([fmt(start), fmt(end), category, description])
def list_events(path: Path) -> None:
if not path.exists():
print(f"no events recorded yet ({path})")
return
with path.open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
print("no events recorded yet")
return
print(f"{'start (UTC)':<21}{'end (UTC)':<21}{'category':<13}description")
for r in rows:
print(f"{r['start_utc']:<21}{r['end_utc']:<21}{r['category']:<13}{r['description']}")
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description="Append a manual event annotation.")
p.add_argument("description", nargs="?", help="what happened, in one short sentence")
p.add_argument("--category", choices=CATEGORIES, default="other")
p.add_argument("--start", default=None,
help="event start, local time unless an offset/Z is given "
"(e.g. '2026-09-12 16:00'); default: now")
p.add_argument("--end", default=None, help="event end (same format)")
p.add_argument("--minutes", type=float, default=1.0,
help="event length when --end is not given")
p.add_argument("--file", default=str(DEFAULT_PATH), help="events CSV to append to")
p.add_argument("--list", action="store_true", help="print the recorded events and exit")
args = p.parse_args(argv)
path = Path(args.file)
if args.list:
list_events(path)
return 0
if not args.description:
p.error("a description is required (or use --list)")
try:
start = parse_time(args.start)
end = parse_time(args.end) if args.end else start + timedelta(minutes=args.minutes)
except ValueError as exc:
p.error(f"invalid timestamp: {exc}")
if end < start:
p.error("--end is before --start")
append_event(path, start, end, args.category, args.description.strip())
print(f"recorded [{args.category}] {fmt(start)} -> {fmt(end)}: {args.description.strip()}")
print(f"file: {path}")
return 0
if __name__ == "__main__":
sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429#!/usr/bin/env python3"""Consolidate raw collector runs into the published LocalNet-Dynamics dataset.
Reads every `localnet_*.csv` (and its `.json` run metadata) from the rawdirectory, validates and merges them (malformed timestamps, duplicates, losspercentages outside 0-100 and failed speed-test latency probes are handled),adds time-of-day features, gap information, rule-based reference labels andmanual event annotations, and writes:
dataset/localnet_dynamics.csv consolidated dataset dataset/localnet_dynamics.parquet same content (needs pyarrow) dataset/summary.json statistics, per-run thresholds, label counts
It also refreshes the auto-generated statistics section of DATASET_CARD.md sothe documentation always matches the data.
python build_dataset.py python build_dataset.py --raw-dir dataset/raw --out-dir dataset --mad-k 5"""
from __future__ import annotations
import argparseimport jsonimport reimport sysfrom datetime import datetime, timezonefrom pathlib import Path
import numpy as npimport pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parent))from collect_data import COLLECTOR_VERSION, CSV_FIELDS # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
STRING_COLUMNS = ["run_id", "host_label", "timestamp_utc", "timestamp_local", "link_type", "gateway_ip", "dns_server", "target", "wifi_ssid", "wifi_phy", "speedtest_server", "notes"]INT_COLUMNS = ["sample_index", "epoch_s", "packets_sent", "packets_received", "http_status", "wifi_signal_pct", "wifi_channel", "speedtest_server_id", "lan_retransmits"]
RUN_COLUMNS = ["collector_version", "collector_os", "interval_s", "rtt_resolution_ms"]TIME_COLUMNS = ["date_local", "hour_local", "weekday_local", "is_weekend", "gap_before_s"]LABEL_COLUMNS = ["label_outage", "label_packet_loss", "label_high_latency", "label_high_jitter", "label_gateway_degraded", "label_anomaly"]EVENT_COLUMNS = ["event_category", "event_description"]
# (column, absolute floor in ms, floor as a fraction of the median)THRESHOLD_RULES = { "rtt_avg_ms": (10.0, 0.5), "jitter_ms": (5.0, 1.0), "gateway_rtt_avg_ms": (5.0, 1.0),}
STATS_COLUMNS = [ "rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct", "gateway_rtt_avg_ms", "gateway_packet_loss_pct", "tcp_connect_median_ms", "dns_resolve_ms", "dns_recursive_ms", "http_ms", "wifi_signal_pct", "wifi_rssi_dbm", "wifi_rx_mbps", "download_mbps", "upload_mbps", "speedtest_ping_ms", "download_loaded_latency_ms", "upload_loaded_latency_ms", "lan_throughput_mbps",]
# speedtest-cli scores a failed latency attempt as 3600 s and averages three attempts# over six, so one failed attempt already yields a value of at least 600,000 ms.SPEEDTEST_PING_FAILED_MS = 600_000
CARD_BEGIN = "<!-- BEGIN GENERATED STATISTICS -->"CARD_END = "<!-- END GENERATED STATISTICS -->"
# --------------------------------------------------------------------------- ## Loading# --------------------------------------------------------------------------- #
def os_family(platform_string: str) -> str: p = (platform_string or "").lower() if p.startswith("windows"): return "Windows" if p.startswith("macos") or p.startswith("darwin"): return "macOS" if p.startswith("linux"): return "Linux" return platform_string.split("-")[0] if platform_string else ""
def load_run(csv_path: Path) -> tuple[pd.DataFrame, dict]: dtypes = {c: "string" for c in STRING_COLUMNS} df = pd.read_csv(csv_path, dtype=dtypes, keep_default_na=True, na_values=[""]) for c in STRING_COLUMNS: if c in df.columns: df[c] = df[c].fillna("").astype(str) meta: dict = {} json_path = csv_path.with_suffix(".json") if json_path.exists(): try: meta = json.loads(json_path.read_text(encoding="utf-8")) except ValueError: meta = {} if "run_id" not in df.columns or df["run_id"].eq("").all(): df["run_id"] = meta.get("run_id") or csv_path.stem.replace("localnet_", "") df["collector_version"] = meta.get("collector_version", "") df["collector_os"] = os_family((meta.get("environment") or {}).get("os", "")) interval = meta.get("interval_s") if interval is None and "epoch_s" in df.columns and len(df) > 1: interval = float(np.nanmedian(np.diff(df["epoch_s"].astype(float).values))) df["interval_s"] = interval df["rtt_resolution_ms"] = (meta.get("environment") or {}).get("ping_resolution_ms") return df, meta
def load_raw(raw_dir: Path) -> tuple[pd.DataFrame, dict[str, dict]]: files = sorted(raw_dir.glob("localnet_*.csv")) if not files: raise SystemExit(f"no localnet_*.csv files found in {raw_dir}") frames, metas = [], {} for path in files: df, meta = load_run(path) if df.empty: print(f"skipping empty file {path.name}") continue frames.append(df) metas[str(df["run_id"].iloc[0])] = meta print(f"loaded {path.name}: {len(df)} rows") df = pd.concat(frames, ignore_index=True, sort=False) for c in CSV_FIELDS: if c not in df.columns: df[c] = "" if c in STRING_COLUMNS else np.nan return df, metas
# --------------------------------------------------------------------------- ## Validation and derived columns# --------------------------------------------------------------------------- #
def validate(df: pd.DataFrame) -> pd.DataFrame: before = len(df) df = df[df["timestamp_utc"].str.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")] dropped = before - len(df) if dropped: print(f"dropped {dropped} rows with malformed timestamps") df = df.drop_duplicates(subset=["run_id", "timestamp_utc"], keep="first") df = df.sort_values(["run_id", "epoch_s"], kind="stable").reset_index(drop=True) for col in ("packet_loss_pct", "gateway_packet_loss_pct"): bad = (df[col] < 0) | (df[col] > 100) if bad.any(): print(f"warning: {int(bad.sum())} rows have {col} outside 0-100; set to missing") df.loc[bad, col] = np.nan failed = df["speedtest_ping_ms"] >= SPEEDTEST_PING_FAILED_MS if failed.any(): print(f"{int(failed.sum())} speed-test rows have a failed server latency probe " f"(speedtest_ping_ms >= {SPEEDTEST_PING_FAILED_MS:,}); set to missing") df.loc[failed, "speedtest_ping_ms"] = np.nan return df
def add_time_features(df: pd.DataFrame) -> pd.DataFrame: local = pd.to_datetime(df["timestamp_local"].str[:19], format="%Y-%m-%dT%H:%M:%S", errors="coerce") df["date_local"] = local.dt.strftime("%Y-%m-%d") df["hour_local"] = local.dt.hour df["weekday_local"] = local.dt.dayofweek df["is_weekend"] = (local.dt.dayofweek >= 5).astype(int) df["gap_before_s"] = df.groupby("run_id")["epoch_s"].diff() return df
def robust_threshold(values: pd.Series, floor_abs: float, floor_rel: float, k: float) -> dict: v = values.dropna().astype(float) if len(v) < 20: return {"n": int(len(v)), "median": None, "mad": None, "threshold": None} median = float(v.median()) mad = float((v - median).abs().median()) threshold = median + max(k * 1.4826 * mad, floor_abs, floor_rel * median) return {"n": int(len(v)), "median": round(median, 3), "mad": round(mad, 3), "threshold": round(threshold, 3)}
def add_labels(df: pd.DataFrame, k: float) -> tuple[pd.DataFrame, dict]: thresholds: dict[str, dict] = {} for col in LABEL_COLUMNS: df[col] = 0 sent = df["packets_sent"].fillna(0) received = df["packets_received"].fillna(0) outage = (sent > 0) & (received == 0) df["label_outage"] = outage.astype(int) df["label_packet_loss"] = (df["packet_loss_pct"].gt(0) & ~outage).astype(int)
for run_id, idx in df.groupby("run_id").groups.items(): part = df.loc[idx] rules = {col: robust_threshold(part[col], fa, fr, k) for col, (fa, fr) in THRESHOLD_RULES.items()} thresholds[run_id] = rules t = rules["rtt_avg_ms"]["threshold"] if t is not None: df.loc[idx, "label_high_latency"] = part["rtt_avg_ms"].gt(t).astype(int) t = rules["jitter_ms"]["threshold"] if t is not None: df.loc[idx, "label_high_jitter"] = part["jitter_ms"].gt(t).astype(int) t = rules["gateway_rtt_avg_ms"]["threshold"] gw = part["gateway_packet_loss_pct"].gt(0) if t is not None: gw |= part["gateway_rtt_avg_ms"].gt(t) df.loc[idx, "label_gateway_degraded"] = gw.astype(int)
df["label_anomaly"] = df[LABEL_COLUMNS[:-1]].max(axis=1).astype(int) return df, thresholds
def load_events(path: Path) -> pd.DataFrame: columns = ["start_utc", "end_utc", "category", "description"] if not path.exists(): return pd.DataFrame(columns=columns) ev = pd.read_csv(path, dtype=str, keep_default_na=False) missing = [c for c in columns if c not in ev.columns] if missing: raise SystemExit(f"{path}: missing columns {missing}") ev["start"] = pd.to_datetime(ev["start_utc"], utc=True, errors="coerce") ev["end"] = pd.to_datetime(ev["end_utc"], utc=True, errors="coerce") bad = ev["start"].isna() | ev["end"].isna() if bad.any(): print(f"warning: ignoring {int(bad.sum())} events with unparsable timestamps") ev = ev[~bad] return ev.reset_index(drop=True)
def add_events(df: pd.DataFrame, events: pd.DataFrame) -> pd.DataFrame: df["event_category"] = "" df["event_description"] = "" if events.empty: return df ts = pd.to_datetime(df["timestamp_utc"], utc=True) cats = [[] for _ in range(len(df))] descs = [[] for _ in range(len(df))] for _, ev in events.iterrows(): hit = np.flatnonzero((ts >= ev["start"]) & (ts <= ev["end"])) for i in hit: cats[i].append(str(ev["category"])) descs[i].append(str(ev["description"])) df["event_category"] = [" | ".join(c) for c in cats] df["event_description"] = [" | ".join(d) for d in descs] return df
def order_columns(df: pd.DataFrame) -> pd.DataFrame: base = [c for c in CSV_FIELDS if c != "notes"] head = base[:11] body = base[11:] ordered = head + RUN_COLUMNS + TIME_COLUMNS + body + LABEL_COLUMNS + EVENT_COLUMNS + ["notes"] extra = [c for c in df.columns if c not in ordered] return df[ordered + extra]
def cast_types(df: pd.DataFrame) -> pd.DataFrame: for col in INT_COLUMNS + ["hour_local", "weekday_local", "is_weekend"] + LABEL_COLUMNS: if col in df.columns: df[col] = df[col].astype("Int64") return df
# --------------------------------------------------------------------------- ## Summary and dataset card# --------------------------------------------------------------------------- #
def column_summary(series: pd.Series) -> dict | None: v = series.dropna().astype(float) if v.empty: return None return {"count": int(v.size), "mean": round(float(v.mean()), 3), "median": round(float(v.median()), 3), "p95": round(float(v.quantile(0.95)), 3), "min": round(float(v.min()), 3), "max": round(float(v.max()), 3)}
def build_summary(df: pd.DataFrame, metas: dict, thresholds: dict, events: pd.DataFrame, k: float) -> dict: ts = pd.to_datetime(df["timestamp_utc"], utc=True) runs = [] expected_total = 0.0 for run_id, part in df.groupby("run_id", sort=True): meta = metas.get(run_id, {}) interval = part["interval_s"].iloc[0] span = float(part["epoch_s"].max() - part["epoch_s"].min()) expected = span / float(interval) + 1 if interval and interval > 0 else len(part) expected_total += expected runs.append({ "run_id": run_id, "host_label": part["host_label"].iloc[0], "rows": int(len(part)), "first_utc": part["timestamp_utc"].iloc[0], "last_utc": part["timestamp_utc"].iloc[-1], "span_hours": round(span / 3600.0, 2), "interval_s": float(interval) if interval else None, "coverage_pct": round(100.0 * len(part) / expected, 2) if expected else None, "link_types": {str(k_): int(v) for k_, v in part["link_type"].value_counts().items()}, "collector_version": meta.get("collector_version", ""), "os": (meta.get("environment") or {}).get("os", ""), "status": meta.get("status", ""), "thresholds": thresholds.get(run_id, {}), }) labels = {col: {"rows": int(df[col].sum()), "share_pct": round(100.0 * float(df[col].mean()), 3)} for col in LABEL_COLUMNS} return { "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "builder_version": COLLECTOR_VERSION, "rows": int(len(df)), "columns": int(df.shape[1]), "runs": runs, "first_utc": ts.min().strftime("%Y-%m-%dT%H:%M:%SZ"), "last_utc": ts.max().strftime("%Y-%m-%dT%H:%M:%SZ"), "span_days": round((ts.max() - ts.min()).total_seconds() / 86400.0, 2), "coverage_pct": round(100.0 * len(df) / expected_total, 2) if expected_total else None, "label_rule": { "mad_k": k, "description": "threshold = median + max(k * 1.4826 * MAD, absolute floor, " "relative floor * median), computed per run", "floors": {c: {"absolute_ms": fa, "relative": fr} for c, (fa, fr) in THRESHOLD_RULES.items()}, }, "labels": labels, "events": int(len(events)), "metrics": {c: column_summary(df[c]) for c in STATS_COLUMNS if column_summary(df[c])}, }
def size_category(n: int) -> str: bounds = [(1_000, "n<1K"), (10_000, "1K<n<10K"), (100_000, "10K<n<100K"), (1_000_000, "100K<n<1M"), (10_000_000, "1M<n<10M")] for limit, label in bounds: if n < limit: return label return "10M<n<100M"
def render_card_block(summary: dict) -> str: lines = [CARD_BEGIN, f"Generated by `scripts/build_dataset.py` on {summary['generated_utc']} " f"from {len(summary['runs'])} collection run(s).", "", "| Item | Value |", "|---|---|", f"| Rows | {summary['rows']:,} |", f"| Columns | {summary['columns']} |", f"| First sample (UTC) | {summary['first_utc']} |", f"| Last sample (UTC) | {summary['last_utc']} |", f"| Span | {summary['span_days']} days |", f"| Sampling coverage | {summary['coverage_pct']} % of the samples expected at the configured interval |", f"| Manual event annotations | {summary['events']} |", ""] lines += ["| Run | Vantage | Link | OS | Interval | Rows | Span | Coverage |", "|---|---|---|---|---|---|---|---|"] for r in summary["runs"]: links = ", ".join(f"{k_} ({v})" for k_, v in r["link_types"].items()) interval = f"{r['interval_s']:.0f} s" if r["interval_s"] else "-" lines.append(f"| {r['run_id']} | {r['host_label'] or '-'} | {links} | {os_family(r['os']) or '-'} | " f"{interval} | {r['rows']:,} | {r['span_hours']} h | {r['coverage_pct']} % |") lines += ["", "| Metric | n | Median | Mean | p95 | Max |", "|---|---|---|---|---|---|"] for col, st in summary["metrics"].items(): lines.append(f"| {col} | {st['count']:,} | {st['median']} | {st['mean']} | {st['p95']} | {st['max']} |") lines += ["", "| Reference label | Rows | Share |", "|---|---|---|"] for col, st in summary["labels"].items(): lines.append(f"| {col} | {st['rows']:,} | {st['share_pct']} % |") lines += ["", CARD_END] return "\n".join(lines)
def update_card(card_path: Path, summary: dict) -> None: text = card_path.read_text(encoding="utf-8") if CARD_BEGIN not in text or CARD_END not in text: print(f"warning: {card_path.name} has no generated-statistics markers; not updated") return block = render_card_block(summary) pattern = re.compile(re.escape(CARD_BEGIN) + r".*?" + re.escape(CARD_END), re.DOTALL) text = pattern.sub(lambda _: block, text, count=1) text = re.sub(r"(size_categories:\s*\n\s*-\s*)(\S+)", lambda m: m.group(1) + size_category(summary["rows"]), text, count=1) card_path.write_text(text, encoding="utf-8") print(f"updated statistics in {card_path}")
# --------------------------------------------------------------------------- ## CLI# --------------------------------------------------------------------------- #
def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description="Build the consolidated LocalNet-Dynamics dataset.") p.add_argument("--raw-dir", default=str(ROOT / "dataset" / "raw")) p.add_argument("--out-dir", default=str(ROOT / "dataset")) p.add_argument("--events", default=None, help="events CSV (default: <raw-dir>/events.csv)") p.add_argument("--card", default=str(ROOT / "DATASET_CARD.md")) p.add_argument("--no-card", action="store_true", help="do not touch the dataset card") p.add_argument("--no-parquet", action="store_true") p.add_argument("--mad-k", type=float, default=5.0, help="MAD multiplier for the high-latency / high-jitter / gateway rules") args = p.parse_args(argv)
raw_dir, out_dir = Path(args.raw_dir), Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True) events_path = Path(args.events) if args.events else raw_dir / "events.csv"
df, metas = load_raw(raw_dir) df = validate(df) df = add_time_features(df) df, thresholds = add_labels(df, args.mad_k) events = load_events(events_path) df = add_events(df, events) df = cast_types(order_columns(df))
csv_out = out_dir / "localnet_dynamics.csv" df.to_csv(csv_out, index=False) print(f"wrote {csv_out} ({len(df):,} rows, {df.shape[1]} columns)") if not args.no_parquet: try: parquet_out = out_dir / "localnet_dynamics.parquet" df.to_parquet(parquet_out, index=False) print(f"wrote {parquet_out}") except (ImportError, ValueError) as exc: print(f"parquet not written ({exc}); install pyarrow to enable it")
summary = build_summary(df, metas, thresholds, events, args.mad_k) (out_dir / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(f"wrote {out_dir / 'summary.json'}") if not args.no_card and Path(args.card).exists(): update_card(Path(args.card), summary)
print(f"\nrows: {summary['rows']:,} span: {summary['span_days']} days " f"coverage: {summary['coverage_pct']} %") for col, st in summary["labels"].items(): print(f" {col:<24}{st['rows']:>8} ({st['share_pct']} %)") return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583#!/usr/bin/env python3"""LocalNet-Dynamics telemetry collector.
Samples the network at a fixed cadence from a single client machine andappends one row per sample to a CSV file in real time. Each sample records:
* ICMP round-trip time to a reference target (min/avg/median/max/stddev), inter-packet jitter and packet loss * ICMP round-trip time and loss to the default gateway (first hop) * TCP connect time to the target (sub-millisecond resolution on every OS) * DNS response time of the configured resolver for a fixed name and for a never-before-seen name (forces a full recursive lookup) * HTTP time-to-first-response for a small connectivity-check URL * Wi-Fi link metrics when the machine is on wireless (signal, PHY rate, channel, band, standard) * WAN throughput (Ookla Speedtest) and LAN throughput (iperf3) on their own, slower cadence
The collector depends only on the Python standard library and the operatingsystem's `ping` utility. Optional external tools: Ookla `speedtest` CLI or the`speedtest-cli` Python package (WAN throughput), `iperf3` (LAN throughput).
Typical use, 30-second cadence for 30 days with an hourly WAN speed test:
python collect_data.py --duration 30d --interval 30s --speedtest --speedtest-every 1h
Run `python collect_data.py --check` to verify the environment and print onesample without writing any files."""
from __future__ import annotations
import argparseimport base64import contextlibimport csvimport jsonimport osimport platformimport randomimport reimport shutilimport signalimport socketimport statisticsimport structimport subprocessimport sysimport timeimport urllib.errorimport urllib.requestfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import asdict, dataclass, fieldsfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Optional
COLLECTOR_VERSION = "2.0.1"
IS_WINDOWS = sys.platform.startswith("win")IS_MACOS = sys.platform == "darwin"IS_LINUX = sys.platform.startswith("linux")
ROUTE_REFRESH_S = 900.0 # re-detect gateway / link type every 15 minMETA_REFRESH_S = 300.0 # rewrite the run metadata JSON every 5 minSPEEDTEST_PING_FAILED_MS = 600_000.0 # speedtest-cli scores a failed latency attempt as 3600 sUSER_AGENT = f"LocalNet-Dynamics/{COLLECTOR_VERSION}"
# --------------------------------------------------------------------------- ## Duration parsing# --------------------------------------------------------------------------- #
_DURATION_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([smhd]?)\s*$", re.IGNORECASE)_UNIT_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}
def parse_duration(text: str) -> float: """Parse '90', '30s', '10m', '2h', '1.5d' into seconds.""" m = _DURATION_RE.match(str(text)) if not m: raise argparse.ArgumentTypeError( f"invalid duration {text!r} (examples: 30s, 10m, 2h, 7d)" ) value, unit = float(m.group(1)), m.group(2).lower() return value * _UNIT_SECONDS[unit]
def human_duration(seconds: float) -> str: seconds = int(round(seconds)) parts = [] for label, size in (("d", 86400), ("h", 3600), ("m", 60), ("s", 1)): if seconds >= size: parts.append(f"{seconds // size}{label}") seconds %= size return " ".join(parts) or "0s"
# --------------------------------------------------------------------------- ## Sample schema# --------------------------------------------------------------------------- #
@dataclassclass Sample: run_id: str = "" host_label: str = "" sample_index: int = 0 timestamp_utc: str = "" timestamp_local: str = "" epoch_s: int = 0 elapsed_s: float = 0.0 link_type: str = "" gateway_ip: str = "" dns_server: str = "" target: str = "" rtt_min_ms: Optional[float] = None rtt_avg_ms: Optional[float] = None rtt_median_ms: Optional[float] = None rtt_max_ms: Optional[float] = None rtt_stddev_ms: Optional[float] = None jitter_ms: Optional[float] = None packets_sent: Optional[int] = None packets_received: Optional[int] = None packet_loss_pct: Optional[float] = None gateway_rtt_min_ms: Optional[float] = None gateway_rtt_avg_ms: Optional[float] = None gateway_rtt_max_ms: Optional[float] = None gateway_jitter_ms: Optional[float] = None gateway_packet_loss_pct: Optional[float] = None tcp_connect_min_ms: Optional[float] = None tcp_connect_median_ms: Optional[float] = None dns_resolve_ms: Optional[float] = None dns_recursive_ms: Optional[float] = None http_ms: Optional[float] = None http_status: Optional[int] = None wifi_ssid: str = "" wifi_signal_pct: Optional[int] = None wifi_rssi_dbm: Optional[float] = None wifi_rx_mbps: Optional[float] = None wifi_tx_mbps: Optional[float] = None wifi_channel: Optional[int] = None wifi_band_ghz: Optional[float] = None wifi_phy: str = "" download_mbps: Optional[float] = None upload_mbps: Optional[float] = None speedtest_ping_ms: Optional[float] = None download_loaded_latency_ms: Optional[float] = None upload_loaded_latency_ms: Optional[float] = None speedtest_server_id: Optional[int] = None speedtest_server: str = "" lan_throughput_mbps: Optional[float] = None lan_retransmits: Optional[int] = None sample_duration_s: Optional[float] = None notes: str = ""
CSV_FIELDS = [f.name for f in fields(Sample)]
SUMMARY_KEYS = [ "rtt_avg_ms", "rtt_min_ms", "rtt_max_ms", "jitter_ms", "packet_loss_pct", "gateway_rtt_avg_ms", "gateway_packet_loss_pct", "tcp_connect_median_ms", "dns_resolve_ms", "dns_recursive_ms", "http_ms", "wifi_signal_pct", "wifi_rssi_dbm", "wifi_rx_mbps", "download_mbps", "upload_mbps", "speedtest_ping_ms", "download_loaded_latency_ms", "upload_loaded_latency_ms", "lan_throughput_mbps", "sample_duration_s",]
# --------------------------------------------------------------------------- ## Subprocess helpers# --------------------------------------------------------------------------- #
def _console_encoding() -> str: """Encoding used by console tools (OEM code page on Windows).""" if IS_WINDOWS: try: import ctypes cp = ctypes.windll.kernel32.GetOEMCP() # type: ignore[attr-defined] if cp: return f"cp{cp}" except Exception: pass return "utf-8"
def decode_output(data: bytes, encoding: Optional[str] = None) -> str: for enc in ((encoding,) if encoding else ()) + ("utf-8", _console_encoding(), "latin-1"): try: return data.decode(enc) except (UnicodeDecodeError, LookupError): continue return data.decode("utf-8", errors="replace")
def run_cmd(args: list[str], timeout: float = 20.0, encoding: Optional[str] = None) -> tuple[Optional[int], str]: """Run a command, returning (exit code, combined decoded output).
The exit code is None when the command timed out or could not be started. """ try: proc = subprocess.run(args, capture_output=True, timeout=timeout) except subprocess.TimeoutExpired as exc: out = (exc.stdout or b"") + (exc.stderr or b"") return None, decode_output(out, encoding) except (FileNotFoundError, OSError): return None, "" return proc.returncode, decode_output(proc.stdout + proc.stderr, encoding)
def run_powershell(script: str, timeout: float = 30.0) -> str: """Run a PowerShell script (Windows only) and return its UTF-8 stdout.""" if not IS_WINDOWS: return "" wrapped = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n" + script encoded = base64.b64encode(wrapped.encode("utf-16-le")).decode("ascii") for exe in ("powershell", "pwsh"): if shutil.which(exe) is None: continue code, out = run_cmd( [exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], timeout=timeout, encoding="utf-8", ) if code == 0 and out.strip(): return out return ""
# --------------------------------------------------------------------------- ## ICMP ping# --------------------------------------------------------------------------- #
@dataclassclass PingResult: sent: int = 0 received: int = 0 rtts: Optional[list[float]] = None error: Optional[str] = None
@property def loss_pct(self) -> Optional[float]: if self.sent <= 0: return None lost = max(0, self.sent - self.received) return round(100.0 * lost / self.sent, 1)
# RTT token of a reply line: "time=14.2 ms", "time=14ms", "time<1ms",# "Zeit=14ms", "时间=14ms", "temps=14 ms", "время=14мс". The localized label# before the operator is irrelevant; the unit is matched in Latin and Cyrillic.# The operator must directly follow a non-space character, which excludes the# summary lines ("Minimum = 14ms", "min/avg/max = 13.9/14.5/15.2 ms")._RTT_RE = re.compile(r"\S([=<])\s*(\d+(?:[.,]\d+)?)\s*(?:ms|мс)\b", re.IGNORECASE)
def parse_ping_output(text: str, sent: int) -> PingResult: """Extract per-reply RTTs from `ping` output in a locale-independent way.
Windows prints integer milliseconds and reports sub-millisecond replies as "<1ms"; those are stored as 0.0. """ rtts: list[float] = [] for line in text.splitlines(): if "DUP!" in line: # duplicate reply (Linux) - not a new echo continue m = _RTT_RE.search(line) if not m: continue if m.group(1) == "<": rtts.append(0.0) else: rtts.append(float(m.group(2).replace(",", "."))) return PingResult(sent=sent, received=len(rtts), rtts=rtts)
_PING_FLAVOR: Optional[str] = None
def ping_flavor() -> str: """windows | iputils | busybox | bsd (cached).""" global _PING_FLAVOR if _PING_FLAVOR is None: if IS_WINDOWS: _PING_FLAVOR = "windows" elif IS_LINUX: _, out = run_cmd(["ping", "-V"], timeout=5.0) _PING_FLAVOR = "busybox" if "busybox" in out.lower() else "iputils" else: _PING_FLAVOR = "bsd" return _PING_FLAVOR
def ping_command(host: str, count: int, timeout_s: float, flavor: str) -> list[str]: ipv6 = ":" in host if flavor == "windows": cmd = ["ping", "-n", str(count), "-w", str(int(timeout_s * 1000))] cmd.append("-6" if ipv6 else "-4") return cmd + [host] wait_s = str(max(1, int(round(timeout_s)))) if flavor == "iputils": return ["ping", "-n", "-c", str(count), "-W", wait_s, host] if flavor == "busybox": return ["ping", "-c", str(count), "-W", wait_s, host] # macOS / BSD: -W is the per-reply wait in milliseconds return ["ping", "-n", "-c", str(count), "-W", str(int(timeout_s * 1000)), host]
def ping(host: str, count: int, timeout_s: float) -> PingResult: if shutil.which("ping") is None: return PingResult(sent=0, received=0, rtts=[], error="ping utility not found") budget = count * (1.0 + timeout_s) + 5.0 code, out = run_cmd(ping_command(host, count, timeout_s, ping_flavor()), timeout=budget) result = parse_ping_output(out, sent=count) if code is None and not out: result.error = "ping could not be started" result.sent = 0 elif result.received == 0: result.error = "no replies" return result
def rtt_stats(rtts: list[float]) -> dict: """min/avg/median/max/stddev/jitter for a burst of RTT samples.""" if not rtts: return {"min": None, "avg": None, "median": None, "max": None, "stddev": None, "jitter": None} jitter = None if len(rtts) > 1: diffs = [abs(rtts[i] - rtts[i - 1]) for i in range(1, len(rtts))] jitter = round(sum(diffs) / len(diffs), 3) return { "min": round(min(rtts), 3), "avg": round(sum(rtts) / len(rtts), 3), "median": round(statistics.median(rtts), 3), "max": round(max(rtts), 3), "stddev": round(statistics.pstdev(rtts), 3) if len(rtts) > 1 else 0.0, "jitter": jitter, }
# --------------------------------------------------------------------------- ## Route, gateway, resolver and link-type detection# --------------------------------------------------------------------------- #
@dataclassclass NetworkInfo: gateway: Optional[str] = None interface: Optional[str] = None local_ip: Optional[str] = None link_type: str = "unknown" # wifi | ethernet | other | unknown dns_servers: Optional[list[str]] = None source: str = ""
_WINDOWS_ROUTE_PS = r"""$ErrorActionPreference = 'SilentlyContinue'$routes = Get-NetRoute -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' | Where-Object { $_.NextHop -ne '0.0.0.0' } | Where-Object { (Get-NetAdapter -InterfaceIndex $_.ifIndex).Status -eq 'Up' }$r = $routes | Sort-Object { $_.RouteMetric + $_.InterfaceMetric } | Select-Object -First 1if ($r) { $a = Get-NetAdapter -InterfaceIndex $r.ifIndex $ip = (Get-NetIPAddress -InterfaceIndex $r.ifIndex -AddressFamily IPv4 | Select-Object -First 1).IPAddress $dns = (Get-DnsClientServerAddress -InterfaceIndex $r.ifIndex -AddressFamily IPv4).ServerAddresses $o = [ordered]@{ gateway = [string]$r.NextHop; ifindex = $r.ifIndex; alias = [string]$a.Name; media = [string]$a.PhysicalMediaType; ip = [string]$ip; dns = @($dns) } $o | ConvertTo-Json -Compress}"""
_ROUTE_PRINT_RE = re.compile( r"^\s*0\.0\.0\.0\s+0\.0\.0\.0\s+([\d.]+)\s+([\d.]+)\s+(\d+)\s*$", re.MULTILINE)
def parse_route_print(text: str) -> Optional[tuple[str, str]]: """Parse `route print -4 0.0.0.0` output -> (gateway, interface_ip).""" best = None for gw, iface_ip, metric in _ROUTE_PRINT_RE.findall(text): m = int(metric) if best is None or m < best[0]: best = (m, gw, iface_ip) return (best[1], best[2]) if best else None
def _link_type_from_media(media: str) -> str: media = (media or "").lower() if "802.11" in media or "wireless" in media or "wi-fi" in media: return "wifi" if "802.3" in media or "ethernet" in media: return "ethernet" if not media or media == "unspecified": return "unknown" return "other"
def detect_network_windows() -> NetworkInfo: info = NetworkInfo() out = run_powershell(_WINDOWS_ROUTE_PS, timeout=40.0) if out.strip(): try: data = json.loads(out.strip().splitlines()[-1]) info.gateway = data.get("gateway") or None info.interface = data.get("alias") or None info.local_ip = data.get("ip") or None info.link_type = _link_type_from_media(data.get("media", "")) dns = data.get("dns") or [] if isinstance(dns, str): dns = [dns] info.dns_servers = [d for d in dns if d and ":" not in d] or None info.source = "powershell" if info.gateway: return info except (ValueError, AttributeError): pass code, out = run_cmd(["route", "print", "-4", "0.0.0.0"], timeout=20.0) parsed = parse_route_print(out) if parsed: info.gateway, info.local_ip = parsed info.source = "route print" return info
def parse_ip_route_get(text: str) -> dict: """Parse `ip -o route get <ip>` output into via/dev/src.""" out = {} for key in ("via", "dev", "src"): m = re.search(rf"\b{key}\s+(\S+)", text) if m: out[key] = m.group(1) return out
def _linux_is_wireless(dev: str) -> bool: base = Path("/sys/class/net") / dev return (base / "wireless").exists() or (base / "phy80211").exists()
def parse_resolv_conf(text: str) -> list[str]: servers = [] for line in text.splitlines(): line = line.split("#", 1)[0].strip() if line.startswith("nameserver"): parts = line.split() if len(parts) >= 2: servers.append(parts[1]) return servers
def detect_network_linux(target: str) -> NetworkInfo: info = NetworkInfo(source="ip route") code, out = run_cmd(["ip", "-o", "route", "get", target], timeout=10.0) parsed = parse_ip_route_get(out) if code == 0 else {} if not parsed.get("via"): code, out = run_cmd(["ip", "-o", "route", "show", "default"], timeout=10.0) parsed = parse_ip_route_get(out) if code == 0 else {} info.gateway = parsed.get("via") info.interface = parsed.get("dev") info.local_ip = parsed.get("src") if info.interface: info.link_type = "wifi" if _linux_is_wireless(info.interface) else "ethernet" if info.interface.startswith(("tun", "tap", "wg", "ppp")): info.link_type = "other" servers: list[str] = [] try: servers = parse_resolv_conf(Path("/etc/resolv.conf").read_text(encoding="utf-8")) except OSError: pass if servers and servers[0].startswith("127.") and shutil.which("resolvectl"): code, out = run_cmd(["resolvectl", "dns"], timeout=10.0) upstream = [] for line in out.splitlines(): if info.interface and f"({info.interface})" in line: upstream += re.findall(r"\b(\d{1,3}(?:\.\d{1,3}){3})\b", line.split(":", 1)[-1]) if not upstream: upstream = re.findall(r":\s*(\d{1,3}(?:\.\d{1,3}){3})", out) if upstream: servers = upstream info.dns_servers = [s for s in servers if ":" not in s] or None return info
def parse_route_get_default(text: str) -> dict: out = {} for key in ("gateway", "interface"): m = re.search(rf"^\s*{key}:\s*(\S+)", text, re.MULTILINE) if m: out[key] = m.group(1) return out
def parse_hardware_ports(text: str) -> dict: """`networksetup -listallhardwareports` -> {device: port name}.""" mapping = {} port = None for line in text.splitlines(): line = line.strip() if line.startswith("Hardware Port:"): port = line.split(":", 1)[1].strip() elif line.startswith("Device:") and port: mapping[line.split(":", 1)[1].strip()] = port return mapping
def detect_network_macos() -> NetworkInfo: info = NetworkInfo(source="route get") code, out = run_cmd(["route", "-n", "get", "default"], timeout=10.0) parsed = parse_route_get_default(out) info.gateway = parsed.get("gateway") info.interface = parsed.get("interface") if info.interface: code, out = run_cmd(["networksetup", "-listallhardwareports"], timeout=10.0) port = parse_hardware_ports(out).get(info.interface, "") if "wi-fi" in port.lower() or "airport" in port.lower(): info.link_type = "wifi" elif "ethernet" in port.lower() or "lan" in port.lower(): info.link_type = "ethernet" elif port: info.link_type = "other" code, out = run_cmd(["scutil", "--dns"], timeout=10.0) servers = re.findall(r"nameserver\[\d+\]\s*:\s*(\d{1,3}(?:\.\d{1,3}){3})", out) info.dns_servers = list(dict.fromkeys(servers)) or None return info
def local_ip_for(target: str) -> Optional[str]: """Local address the OS would use to reach `target` (no packet is sent).""" family = socket.AF_INET6 if ":" in target else socket.AF_INET try: with socket.socket(family, socket.SOCK_DGRAM) as s: s.connect((target, 53)) return s.getsockname()[0] except OSError: return None
def detect_network(target: str) -> NetworkInfo: try: if IS_WINDOWS: info = detect_network_windows() elif IS_MACOS: info = detect_network_macos() else: info = detect_network_linux(target) except Exception as exc: # detection must never stop the collector info = NetworkInfo(source=f"failed: {exc}") if not info.local_ip: info.local_ip = local_ip_for(target) return info
# --------------------------------------------------------------------------- ## DNS probe (raw UDP query, bypasses the operating-system cache)# --------------------------------------------------------------------------- #
def build_dns_query(name: str, qid: int, qtype: int = 1) -> bytes: header = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 0) # RD=1, 1 question qname = b"" for label in name.strip(".").split("."): raw = label.encode("idna") if label else b"" qname += struct.pack("B", len(raw)) + raw return header + qname + b"\x00" + struct.pack(">HH", qtype, 1)
def parse_dns_response(data: bytes, qid: int) -> Optional[int]: """Return the response code, or None if the datagram does not match.""" if len(data) < 12: return None rid, flags = struct.unpack(">HH", data[:4]) if rid != qid or not flags & 0x8000: return None return flags & 0x000F
def dns_query(server: str, name: str, timeout_s: float = 3.0) -> tuple[Optional[float], Optional[int], Optional[str]]: """Time one UDP DNS query. Returns (milliseconds, rcode, error).""" qid = random.randint(0, 0xFFFF) packet = build_dns_query(name, qid) family = socket.AF_INET6 if ":" in server else socket.AF_INET try: with socket.socket(family, socket.SOCK_DGRAM) as s: s.settimeout(timeout_s) start = time.perf_counter() s.sendto(packet, (server, 53)) deadline = start + timeout_s while True: remaining = deadline - time.perf_counter() if remaining <= 0: return None, None, "timeout" s.settimeout(remaining) data, _ = s.recvfrom(4096) elapsed = (time.perf_counter() - start) * 1000.0 rcode = parse_dns_response(data, qid) if rcode is None: continue if rcode in (0, 3): # NOERROR / NXDOMAIN are valid answers return round(elapsed, 3), rcode, None return None, rcode, f"rcode {rcode}" except socket.timeout: return None, None, "timeout" except OSError as exc: return None, None, f"{exc.__class__.__name__}"
def random_label() -> str: return "%012x" % random.getrandbits(48)
# --------------------------------------------------------------------------- ## TCP connect and HTTP probes# --------------------------------------------------------------------------- #
def tcp_connect_times(host: str, port: int, count: int = 5, timeout_s: float = 3.0, gap_s: float = 0.2) -> tuple[list[float], Optional[str]]: try: addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] except (socket.gaierror, IndexError) as exc: return [], f"resolve failed ({exc.__class__.__name__})" family, _, _, _, sockaddr = addr times: list[float] = [] error = None for i in range(count): s = socket.socket(family, socket.SOCK_STREAM) s.settimeout(timeout_s) try: start = time.perf_counter() s.connect(sockaddr) times.append((time.perf_counter() - start) * 1000.0) except socket.timeout: error = "timeout" except OSError as exc: error = exc.__class__.__name__ finally: try: s.close() except OSError: pass if i < count - 1: time.sleep(gap_s) return times, (error if not times else None)
def http_probe(url: str, timeout_s: float = 5.0) -> tuple[Optional[float], Optional[int], Optional[str]]: """Time-to-first-response for a small URL, bypassing any system proxy.""" opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) req = urllib.request.Request(url, headers={ "User-Agent": USER_AGENT, "Cache-Control": "no-cache", "Pragma": "no-cache", }) start = time.perf_counter() try: with opener.open(req, timeout=timeout_s) as resp: elapsed = (time.perf_counter() - start) * 1000.0 resp.read(4096) return round(elapsed, 3), resp.status, None except urllib.error.HTTPError as exc: elapsed = (time.perf_counter() - start) * 1000.0 return round(elapsed, 3), exc.code, None except (urllib.error.URLError, socket.timeout, OSError, ValueError) as exc: reason = getattr(exc, "reason", exc) return None, None, f"{reason}"[:80]
# --------------------------------------------------------------------------- ## Wi-Fi link metrics# --------------------------------------------------------------------------- #
@dataclassclass WifiInfo: connected: bool = False ssid: Optional[str] = None signal_pct: Optional[int] = None rssi_dbm: Optional[float] = None rx_mbps: Optional[float] = None tx_mbps: Optional[float] = None channel: Optional[int] = None band_ghz: Optional[float] = None phy: Optional[str] = None
def rssi_from_quality(pct: int) -> float: """Windows WLAN mapping: quality 0 -> -100 dBm, 100 -> -50 dBm (linear).""" return round(pct / 2.0 - 100.0, 1)
def quality_from_rssi(rssi: float) -> int: return int(max(0, min(100, round((rssi + 100.0) * 2.0))))
def channel_from_freq_mhz(freq: int) -> tuple[Optional[int], Optional[float]]: if 2412 <= freq <= 2472: return (freq - 2407) // 5, 2.4 if freq == 2484: return 14, 2.4 if 5000 <= freq <= 5900: return (freq - 5000) // 5, 5.0 if 5925 <= freq <= 7125: return (freq - 5950) // 5, 6.0 if 57000 <= freq <= 71000: return None, 60.0 return None, None
def band_from_channel(channel: int) -> Optional[float]: if 1 <= channel <= 14: return 2.4 if 32 <= channel <= 177: return 5.0 return None
_NETSH_KV_RE = re.compile(r"^\s*([^:]+?)\s*:\s*(.*?)\s*$")_PCT_RE = re.compile(r"^(\d{1,3})\s*%$")_INT_RE = re.compile(r"^\d{1,3}$")_GHZ_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*GHz$", re.IGNORECASE)_PHY_RE = re.compile(r"^802\.11[a-z]{1,2}$", re.IGNORECASE)_MBPS_KEY_RE = re.compile(r"\(\s*Mbps\s*\)", re.IGNORECASE)
def parse_netsh_wlan(text: str) -> WifiInfo: """Parse `netsh wlan show interfaces` output without relying on localized labels.
Only the SSID/BSSID keys are language independent; every other field is recognised by the shape of its value (a percentage, "(Mbps)" in the key, "802.11xx", "x GHz", a bare channel number). """ blocks: list[list[tuple[str, str]]] = [[]] for line in text.splitlines(): if not line.strip(): if blocks[-1]: blocks.append([]) continue m = _NETSH_KV_RE.match(line) if m: blocks[-1].append((m.group(1), m.group(2))) info = WifiInfo() for block in blocks: kv = dict(block) ssid = kv.get("SSID") if not ssid or not any(_PCT_RE.match(v) for _, v in block): continue info.connected = True info.ssid = ssid rates: list[tuple[str, float]] = [] for key, value in block: if key in ("SSID", "BSSID"): continue if info.signal_pct is None and _PCT_RE.match(value): info.signal_pct = int(_PCT_RE.match(value).group(1)) elif _MBPS_KEY_RE.search(key): try: rates.append((key.lower(), float(value.replace(",", ".")))) except ValueError: pass elif info.phy is None and _PHY_RE.match(value): info.phy = value.lower() elif info.band_ghz is None and _GHZ_RE.match(value): info.band_ghz = float(_GHZ_RE.match(value).group(1)) elif info.channel is None and _INT_RE.match(value): info.channel = int(value) for key, rate in rates: if "transmit" in key or "tx" in key.split(): info.tx_mbps = rate elif "receive" in key or "rx" in key.split(): info.rx_mbps = rate if info.rx_mbps is None and rates: info.rx_mbps = rates[0][1] if info.tx_mbps is None and len(rates) > 1: info.tx_mbps = rates[1][1] if info.signal_pct is not None: info.rssi_dbm = rssi_from_quality(info.signal_pct) if info.band_ghz is None and info.channel is not None: info.band_ghz = band_from_channel(info.channel) break return info
def wifi_info_windows() -> WifiInfo: code, out = run_cmd(["netsh", "wlan", "show", "interfaces"], timeout=15.0) return parse_netsh_wlan(out) if out else WifiInfo()
_IW_PHY = (("EHT", "802.11be"), ("HE", "802.11ax"), ("VHT", "802.11ac"), ("HT", "802.11n"))
def parse_iw_link(text: str) -> WifiInfo: info = WifiInfo() if "Not connected" in text or "SSID:" not in text: return info info.connected = True m = re.search(r"^\s*SSID:\s*(.+?)\s*$", text, re.MULTILINE) info.ssid = m.group(1) if m else None m = re.search(r"^\s*freq:\s*(\d+)", text, re.MULTILINE) if m: info.channel, info.band_ghz = channel_from_freq_mhz(int(m.group(1))) m = re.search(r"^\s*signal:\s*(-?\d+(?:\.\d+)?)\s*dBm", text, re.MULTILINE) if m: info.rssi_dbm = float(m.group(1)) info.signal_pct = quality_from_rssi(info.rssi_dbm) for key, attr in (("rx bitrate", "rx_mbps"), ("tx bitrate", "tx_mbps")): m = re.search(rf"^\s*{key}:\s*(\d+(?:\.\d+)?)\s*MBit/s(.*)$", text, re.MULTILINE | re.IGNORECASE) if m: setattr(info, attr, float(m.group(1))) if info.phy is None: rest = m.group(2).upper() for token, phy in _IW_PHY: if re.search(rf"\b{token}-", rest): info.phy = phy break if info.phy is None and re.search(r"\bMCS\b", rest): info.phy = "802.11n" # HT rates are printed as bare "MCS n" return info
def parse_proc_net_wireless(text: str, iface: str) -> WifiInfo: info = WifiInfo() for line in text.splitlines(): if line.strip().startswith(iface + ":"): parts = line.split() try: level = float(parts[3].rstrip(".")) except (IndexError, ValueError): break info.connected = True info.rssi_dbm = level info.signal_pct = quality_from_rssi(level) break return info
def wifi_info_linux(iface: Optional[str]) -> WifiInfo: if not iface or not _linux_is_wireless(iface): return WifiInfo() if shutil.which("iw"): code, out = run_cmd(["iw", "dev", iface, "link"], timeout=10.0) if code == 0 and out: return parse_iw_link(out) try: return parse_proc_net_wireless(Path("/proc/net/wireless").read_text(), iface) except OSError: return WifiInfo()
def parse_system_profiler_airport(data: dict) -> WifiInfo: info = WifiInfo() try: interfaces = data["SPAirPortDataType"][0]["spairport_airport_interfaces"] except (KeyError, IndexError, TypeError): return info for entry in interfaces: net = entry.get("spairport_current_network_information") if not isinstance(net, dict): continue info.connected = True info.ssid = net.get("_name") m = re.search(r"(-?\d+)\s*dBm", str(net.get("spairport_signal_noise", ""))) if m: info.rssi_dbm = float(m.group(1)) info.signal_pct = quality_from_rssi(info.rssi_dbm) m = re.search(r"(\d+)\s*\((\d+(?:\.\d+)?)\s*GHz", str(net.get("spairport_network_channel", ""))) if m: info.channel = int(m.group(1)) info.band_ghz = float(m.group(2)) phy = str(net.get("spairport_network_phymode", "")).lower() info.phy = phy if phy.startswith("802.11") else None rate = net.get("spairport_network_rate") try: info.rx_mbps = float(rate) if rate is not None else None info.tx_mbps = info.rx_mbps except (TypeError, ValueError): pass break return info
def wifi_info_macos() -> WifiInfo: code, out = run_cmd(["system_profiler", "SPAirPortDataType", "-json"], timeout=25.0) if code != 0 or not out: return WifiInfo() try: return parse_system_profiler_airport(json.loads(out)) except ValueError: return WifiInfo()
def wifi_info(net: NetworkInfo) -> WifiInfo: try: if IS_WINDOWS: return wifi_info_windows() if IS_MACOS: return wifi_info_macos() return wifi_info_linux(net.interface) except Exception: return WifiInfo()
# --------------------------------------------------------------------------- ## Throughput tests (slow cadence)# --------------------------------------------------------------------------- #
def _ookla_cli_path() -> Optional[str]: """Path of the official Ookla CLI, distinguishing it from speedtest-cli.""" exe = shutil.which("speedtest") if not exe: return None code, out = run_cmd([exe, "--version"], timeout=15.0) return exe if "ookla" in out.lower() else None
def parse_ookla_json(data: dict) -> dict: result = {} down = data.get("download") or {} up = data.get("upload") or {} if "bandwidth" in down: result["download_mbps"] = round(down["bandwidth"] * 8 / 1e6, 2) if "bandwidth" in up: result["upload_mbps"] = round(up["bandwidth"] * 8 / 1e6, 2) ping_info = data.get("ping") or {} if ping_info.get("latency") is not None: result["speedtest_ping_ms"] = round(float(ping_info["latency"]), 3) for key, col in (("download", "download_loaded_latency_ms"), ("upload", "upload_loaded_latency_ms")): lat = (data.get(key) or {}).get("latency") or {} if lat.get("iqm") is not None: result[col] = round(float(lat["iqm"]), 3) server = data.get("server") or {} if server.get("id") is not None: result["speedtest_server_id"] = int(server["id"]) name = ", ".join(str(server[k]) for k in ("name", "location") if server.get(k)) if name: result["speedtest_server"] = name return result
def run_speedtest(server_id: Optional[int] = None, timeout_s: float = 180.0) -> dict: exe = _ookla_cli_path() if exe: cmd = [exe, "--accept-license", "--accept-gdpr", "--format=json", "--progress=no"] if server_id: cmd += ["--server-id", str(server_id)] code, out = run_cmd(cmd, timeout=timeout_s, encoding="utf-8") for line in out.splitlines(): line = line.strip() if line.startswith("{"): try: data = json.loads(line) except ValueError: continue if data.get("type") == "result": return parse_ookla_json(data) return {"error": "speedtest (ookla) failed: " + (out.strip().splitlines() or ["no output"])[-1][:80]} try: import speedtest # type: ignore except ImportError: return {"error": "no speedtest tool (install the Ookla CLI or `pip install speedtest-cli`)"} try: st = speedtest.Speedtest(secure=True) if server_id: st.get_servers([server_id]) st.get_best_server() down = st.download() / 1e6 up = st.upload(pre_allocate=False) / 1e6 res = st.results out = {"download_mbps": round(down, 2), "upload_mbps": round(up, 2)} if res.ping is not None and float(res.ping) < SPEEDTEST_PING_FAILED_MS: out["speedtest_ping_ms"] = round(float(res.ping), 3) elif res.ping is not None: out["error"] = "speedtest-cli: server latency probe failed" server = res.server or {} if server.get("id"): out["speedtest_server_id"] = int(server["id"]) name = ", ".join(str(server[k]) for k in ("sponsor", "name") if server.get(k)) if name: out["speedtest_server"] = name return out except Exception as exc: return {"error": f"speedtest-cli failed: {exc}"[:120]}
def run_iperf3(server: str, port: int, duration_s: int, reverse: bool) -> dict: if not shutil.which("iperf3"): return {"error": "iperf3 not found"} cmd = ["iperf3", "-c", server, "-p", str(port), "-t", str(duration_s), "-J"] if reverse: cmd.append("-R") code, out = run_cmd(cmd, timeout=duration_s + 30, encoding="utf-8") try: data = json.loads(out) except ValueError: return {"error": "iperf3 failed: " + (out.strip().splitlines() or ["no output"])[-1][:80]} if data.get("error"): return {"error": f"iperf3 failed: {data['error']}"[:120]} try: end = data["end"] received = end.get("sum_received") or end.get("sum") or {} result = {"lan_throughput_mbps": round(received["bits_per_second"] / 1e6, 2)} sent = end.get("sum_sent") or {} if sent.get("retransmits") is not None: result["lan_retransmits"] = int(sent["retransmits"]) return result except (KeyError, TypeError): return {"error": "iperf3 failed: unexpected JSON"}
# --------------------------------------------------------------------------- ## Keep the machine awake while collecting# --------------------------------------------------------------------------- #
class KeepAwake: """System sleep inhibitor (display may still turn off)."""
ES_CONTINUOUS = 0x80000000 ES_SYSTEM_REQUIRED = 0x00000001
def __init__(self) -> None: self.proc: Optional[subprocess.Popen] = None self.active = False
def __enter__(self) -> "KeepAwake": try: if IS_WINDOWS: import ctypes ok = ctypes.windll.kernel32.SetThreadExecutionState( # type: ignore[attr-defined] self.ES_CONTINUOUS | self.ES_SYSTEM_REQUIRED) self.active = bool(ok) elif IS_MACOS and shutil.which("caffeinate"): self.proc = subprocess.Popen(["caffeinate", "-i", "-w", str(os.getpid())]) self.active = True elif IS_LINUX and shutil.which("systemd-inhibit"): self.proc = subprocess.Popen( ["systemd-inhibit", "--what=sleep:idle", "--who=LocalNet-Dynamics", "--why=telemetry collection in progress", "--mode=block", "sleep", "infinity"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.active = True except Exception: self.active = False return self
def __exit__(self, *exc) -> None: try: if IS_WINDOWS: import ctypes ctypes.windll.kernel32.SetThreadExecutionState(self.ES_CONTINUOUS) # type: ignore[attr-defined] if self.proc: self.proc.terminate() except Exception: pass
# --------------------------------------------------------------------------- ## One sample# --------------------------------------------------------------------------- #
def now_timestamps() -> tuple[str, str, int]: utc = datetime.now(timezone.utc) local = utc.astimezone() return (utc.strftime("%Y-%m-%dT%H:%M:%SZ"), local.isoformat(timespec="seconds"), int(utc.timestamp()))
def collect_sample(cfg: argparse.Namespace, net: NetworkInfo, dns_server: Optional[str], pool: ThreadPoolExecutor, run_speed: bool, run_lan: bool) -> Sample: s = Sample(run_id=cfg.run_id, host_label=cfg.host_label, target=cfg.target, link_type=net.link_type, gateway_ip=net.gateway or "", dns_server=dns_server or "") s.timestamp_utc, s.timestamp_local, s.epoch_s = now_timestamps() t0 = time.perf_counter() notes: list[str] = []
futures = { "ping": pool.submit(ping, cfg.target, cfg.ping_count, cfg.ping_timeout), } if net.gateway: futures["gw"] = pool.submit(ping, net.gateway, cfg.gateway_ping_count, cfg.ping_timeout) if cfg.tcp_port: futures["tcp"] = pool.submit(tcp_connect_times, cfg.target, cfg.tcp_port, cfg.tcp_count, cfg.ping_timeout) if dns_server: futures["dns"] = pool.submit(dns_query, dns_server, cfg.dns_host, cfg.dns_timeout) futures["dnsr"] = pool.submit(dns_query, dns_server, f"{random_label()}.{cfg.dns_host}", cfg.dns_timeout) if cfg.http_url: futures["http"] = pool.submit(http_probe, cfg.http_url, cfg.http_timeout) if cfg.wifi and net.link_type in ("wifi", "unknown"): futures["wifi"] = pool.submit(wifi_info, net)
p: PingResult = futures["ping"].result() st = rtt_stats(p.rtts or []) s.rtt_min_ms, s.rtt_avg_ms, s.rtt_median_ms = st["min"], st["avg"], st["median"] s.rtt_max_ms, s.rtt_stddev_ms, s.jitter_ms = st["max"], st["stddev"], st["jitter"] s.packets_sent, s.packets_received = p.sent, p.received s.packet_loss_pct = p.loss_pct if p.error: notes.append(f"ping: {p.error}")
if "gw" in futures: g: PingResult = futures["gw"].result() gst = rtt_stats(g.rtts or []) s.gateway_rtt_min_ms, s.gateway_rtt_avg_ms = gst["min"], gst["avg"] s.gateway_rtt_max_ms, s.gateway_jitter_ms = gst["max"], gst["jitter"] s.gateway_packet_loss_pct = g.loss_pct if g.error: notes.append(f"gateway ping: {g.error}")
if "tcp" in futures: times, err = futures["tcp"].result() if times: s.tcp_connect_min_ms = round(min(times), 3) s.tcp_connect_median_ms = round(statistics.median(times), 3) if err: notes.append(f"tcp: {err}")
if "dns" in futures: ms, rcode, err = futures["dns"].result() s.dns_resolve_ms = ms if err: notes.append(f"dns: {err}") ms, rcode, err = futures["dnsr"].result() s.dns_recursive_ms = ms if err: notes.append(f"dns recursive: {err}")
if "http" in futures: ms, status, err = futures["http"].result() s.http_ms, s.http_status = ms, status if err: notes.append(f"http: {err}")
if "wifi" in futures: w: WifiInfo = futures["wifi"].result() if w.connected: s.wifi_ssid = w.ssid if (cfg.record_ssid and w.ssid) else "" s.wifi_signal_pct, s.wifi_rssi_dbm = w.signal_pct, w.rssi_dbm s.wifi_rx_mbps, s.wifi_tx_mbps = w.rx_mbps, w.tx_mbps s.wifi_channel, s.wifi_band_ghz = w.channel, w.band_ghz s.wifi_phy = w.phy or ""
# Heavy tests run after the latency probes so they cannot bias them. if run_speed: r = run_speedtest(cfg.speedtest_server) for key, value in r.items(): if key != "error": setattr(s, key, value) if r.get("error"): notes.append(r["error"]) if run_lan: r = run_iperf3(cfg.iperf_server, cfg.iperf_port, cfg.iperf_duration, cfg.iperf_reverse) for key, value in r.items(): if key != "error": setattr(s, key, value) if r.get("error"): notes.append(r["error"])
s.sample_duration_s = round(time.perf_counter() - t0, 2) s.notes = "; ".join(notes) return s
# --------------------------------------------------------------------------- ## Summary statistics and run metadata# --------------------------------------------------------------------------- #
def column_stats(values: list) -> Optional[dict]: vals = [float(v) for v in values if v is not None and v != ""] if not vals: return None vals_sorted = sorted(vals) p95 = vals_sorted[min(len(vals_sorted) - 1, int(0.95 * len(vals_sorted)))] return { "count": len(vals), "mean": round(statistics.mean(vals), 3), "median": round(statistics.median(vals), 3), "min": round(vals_sorted[0], 3), "max": round(vals_sorted[-1], 3), "p95": round(p95, 3), "stddev": round(statistics.pstdev(vals), 3) if len(vals) > 1 else 0.0, }
class RunningSummary: """Keeps per-column value lists so the JSON summary can be refreshed cheaply."""
def __init__(self) -> None: self.values: dict[str, list] = {k: [] for k in SUMMARY_KEYS} self.count = 0 self.first_utc = "" self.last_utc = "" self.link_types: dict[str, int] = {}
def add(self, s: Sample) -> None: self.count += 1 self.first_utc = self.first_utc or s.timestamp_utc self.last_utc = s.timestamp_utc self.link_types[s.link_type] = self.link_types.get(s.link_type, 0) + 1 for k in SUMMARY_KEYS: v = getattr(s, k) if v is not None: self.values[k].append(v)
def summary(self) -> dict: out = {k: column_stats(v) for k, v in self.values.items()} return {k: v for k, v in out.items() if v is not None}
def timezone_name() -> str: local = datetime.now(timezone.utc).astimezone() return local.tzname() or ""
def write_meta(path: Path, cfg: argparse.Namespace, net: NetworkInfo, dns_server: Optional[str], summary: RunningSummary, status: str, started_utc: str, elapsed_s: float, csv_name: str) -> None: local = datetime.now(timezone.utc).astimezone() payload = { "run_id": cfg.run_id, "host_label": cfg.host_label, "collector_version": COLLECTOR_VERSION, "status": status, "started_utc": started_utc, "updated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "planned_duration_s": cfg.duration, "elapsed_s": round(elapsed_s, 1), "interval_s": cfg.interval, "sample_count": summary.count, "first_sample_utc": summary.first_utc, "last_sample_utc": summary.last_utc, "csv_file": csv_name, "config": { "target": cfg.target, "ping_count": cfg.ping_count, "gateway_ping_count": cfg.gateway_ping_count, "ping_timeout_s": cfg.ping_timeout, "tcp_port": cfg.tcp_port, "tcp_count": cfg.tcp_count, "dns_host": cfg.dns_host, "dns_server": dns_server, "dns_timeout_s": cfg.dns_timeout, "http_url": cfg.http_url, "http_timeout_s": cfg.http_timeout, "wifi": cfg.wifi, "record_ssid": cfg.record_ssid, "speedtest": cfg.speedtest, "speedtest_every_s": cfg.speedtest_every if cfg.speedtest else None, "speedtest_server_id": cfg.speedtest_server, "iperf_server": cfg.iperf_server, "iperf_port": cfg.iperf_port, "iperf_every_s": cfg.iperf_every if cfg.iperf_server else None, "iperf_duration_s": cfg.iperf_duration, "iperf_reverse": cfg.iperf_reverse, }, "environment": { "os": platform.platform(), "python": platform.python_version(), "machine": platform.machine(), "timezone": timezone_name(), "utc_offset_s": int(local.utcoffset().total_seconds()) if local.utcoffset() else 0, "ping_resolution_ms": 1.0 if IS_WINDOWS else 0.001, }, "network": { "gateway_ip": net.gateway, "interface": net.interface, "local_ip": net.local_ip, "link_type": net.link_type, "link_types_seen": summary.link_types, "detection_source": net.source, }, "summary": summary.summary(), } tmp = path.with_suffix(".json.tmp") tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8") os.replace(tmp, path)
def print_summary(summary: RunningSummary, elapsed: float) -> None: stats = summary.summary() print() print("=" * 72) print(f" SUMMARY: {summary.count} samples over {human_duration(elapsed)}") print("=" * 72) header = f"{'metric':<28}{'n':>7}{'median':>10}{'mean':>10}{'p95':>10}{'max':>10}" print(header) print("-" * len(header)) for key in SUMMARY_KEYS: st = stats.get(key) if not st: continue print(f"{key:<28}{st['count']:>7}{st['median']:>10}{st['mean']:>10}" f"{st['p95']:>10}{st['max']:>10}") print("=" * 72)
def format_progress(s: Sample) -> str: def f(v, suffix="", nd=1): return "-" if v is None else f"{v:.{nd}f}{suffix}" parts = [ f"[{s.sample_index + 1:>5}] {s.timestamp_utc}", f"rtt={f(s.rtt_avg_ms, 'ms')}", f"jit={f(s.jitter_ms, 'ms')}", f"loss={f(s.packet_loss_pct, '%', 0)}", f"gw={f(s.gateway_rtt_avg_ms, 'ms')}", f"tcp={f(s.tcp_connect_median_ms, 'ms')}", f"dns={f(s.dns_resolve_ms, '', 0)}/{f(s.dns_recursive_ms, 'ms', 0)}", f"http={f(s.http_ms, 'ms', 0)}", ] if s.wifi_signal_pct is not None: parts.append(f"wifi={s.wifi_signal_pct}%/{f(s.wifi_rx_mbps, 'Mbps', 0)}") if s.download_mbps is not None: parts.append(f"down={f(s.download_mbps, '', 1)} up={f(s.upload_mbps, 'Mbps', 1)}") if s.lan_throughput_mbps is not None: parts.append(f"lan={f(s.lan_throughput_mbps, 'Mbps', 0)}") if s.notes: parts.append(f"! {s.notes}") return " ".join(parts)
# --------------------------------------------------------------------------- ## CLI# --------------------------------------------------------------------------- #
def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( description="LocalNet-Dynamics: continuous network telemetry collector.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) default_out = Path(__file__).resolve().parent.parent / "dataset" / "raw"
g = p.add_argument_group("schedule") g.add_argument("--duration", type=parse_duration, default="24h", help="total run time (e.g. 6h, 7d, 30d)") g.add_argument("--interval", type=parse_duration, default="30s", help="time between sample starts (e.g. 30s, 1m, 5m)")
g = p.add_argument_group("latency probes") g.add_argument("--target", default="8.8.8.8", help="reference host for ICMP and TCP probes") g.add_argument("--ping-count", type=int, default=10, help="ICMP echo requests per sample (sent 1 s apart)") g.add_argument("--gateway-ping-count", type=int, default=5, help="ICMP echo requests to the default gateway per sample") g.add_argument("--ping-timeout", type=float, default=2.0, help="seconds to wait for each ICMP reply / TCP connect") g.add_argument("--tcp-port", type=int, default=443, help="TCP port on the target for connect-time probes (0 disables)") g.add_argument("--tcp-count", type=int, default=5, help="TCP connections per sample") g.add_argument("--dns-host", default="example.com", help="name queried for DNS timing; the recursive probe queries a " "random subdomain of it") g.add_argument("--dns-server", default=None, help="resolver IP to query (default: the system resolver of the " "default-route interface, then the gateway)") g.add_argument("--dns-timeout", type=float, default=3.0, help="DNS query timeout (s)") g.add_argument("--http-url", default="http://www.msftconnecttest.com/connecttest.txt", help="small URL for the HTTP time-to-first-response probe " "('' disables)") g.add_argument("--http-timeout", type=float, default=5.0, help="HTTP probe timeout (s)")
g = p.add_argument_group("wireless") g.add_argument("--no-wifi", dest="wifi", action="store_false", help="do not query Wi-Fi link metrics") g.add_argument("--record-ssid", action="store_true", help="store the Wi-Fi network name in the dataset (off by default " "because it can identify the collection site)")
g = p.add_argument_group("throughput tests") g.add_argument("--speedtest", action="store_true", help="run a WAN speed test periodically (Ookla CLI or speedtest-cli)") g.add_argument("--speedtest-every", type=parse_duration, default="30m", help="interval between WAN speed tests") g.add_argument("--speedtest-server", type=int, default=None, help="Ookla server id to pin (recommended for consistency)") g.add_argument("--iperf-server", default=None, help="address of an `iperf3 -s` host on the LAN") g.add_argument("--iperf-port", type=int, default=5201, help="iperf3 server port") g.add_argument("--iperf-every", type=parse_duration, default="30m", help="interval between LAN throughput tests") g.add_argument("--iperf-duration", type=int, default=10, help="seconds per iperf3 test") g.add_argument("--iperf-reverse", action="store_true", help="measure server-to-client (download) direction instead")
g = p.add_argument_group("output") g.add_argument("--output-dir", default=str(default_out), help="directory for the run's CSV and JSON files") g.add_argument("--run-id", default=None, help="run identifier and file stem (default: <label_>YYYYMMDD_HHMMSS)") g.add_argument("--host-label", default="", help="free-text label for this vantage point, e.g. desktop-eth or " "laptop-wifi (stored in every row)") g.add_argument("--no-keep-awake", dest="keep_awake", action="store_false", help="do not inhibit system sleep while collecting") g.add_argument("--quiet", action="store_true", help="print only the summary") g.add_argument("--check", action="store_true", help="detect the environment, take one sample, print it as JSON " "and exit without writing files") return p
def resolve_dns_server(cfg: argparse.Namespace, net: NetworkInfo) -> Optional[str]: if cfg.dns_server: return cfg.dns_server if net.dns_servers: return net.dns_servers[0] return net.gateway
def sanitize_label(text: str) -> str: return re.sub(r"[^A-Za-z0-9_-]+", "-", text.strip()).strip("-")
def install_sigterm_handler() -> None: def handler(signum, frame): raise KeyboardInterrupt try: signal.signal(signal.SIGTERM, handler) except (ValueError, OSError, AttributeError): pass
def main(argv: Optional[list[str]] = None) -> int: for stream in (sys.stdout, sys.stderr): # never crash on an unprintable path try: stream.reconfigure(errors="replace") except (AttributeError, ValueError): pass cfg = build_parser().parse_args(argv) cfg.duration = float(cfg.duration) cfg.interval = float(cfg.interval) cfg.speedtest_every = float(cfg.speedtest_every) cfg.iperf_every = float(cfg.iperf_every) cfg.host_label = sanitize_label(cfg.host_label) if cfg.interval <= 0: print("error: --interval must be positive", file=sys.stderr) return 2 if cfg.ping_count < 1 or cfg.gateway_ping_count < 1: print("error: ping counts must be at least 1", file=sys.stderr) return 2 stamp = f"{datetime.now():%Y%m%d_%H%M%S}" cfg.run_id = sanitize_label(cfg.run_id) if cfg.run_id else \ (f"{cfg.host_label}_{stamp}" if cfg.host_label else stamp)
net = detect_network(cfg.target) dns_server = resolve_dns_server(cfg, net) pool = ThreadPoolExecutor(max_workers=8)
if cfg.check: print(json.dumps({ "collector_version": COLLECTOR_VERSION, "os": platform.platform(), "python": platform.python_version(), "ping_utility": shutil.which("ping"), "ookla_cli": _ookla_cli_path(), "iperf3": shutil.which("iperf3"), "network": asdict(net), "dns_server": dns_server, }, indent=2)) s = collect_sample(cfg, net, dns_server, pool, run_speed=cfg.speedtest, run_lan=bool(cfg.iperf_server)) print(json.dumps(asdict(s), indent=2)) pool.shutdown(wait=False) return 0
out_dir = Path(cfg.output_dir) out_dir.mkdir(parents=True, exist_ok=True) csv_path = out_dir / f"localnet_{cfg.run_id}.csv" json_path = out_dir / f"localnet_{cfg.run_id}.json" if csv_path.exists(): print(f"error: {csv_path} already exists; choose another --run-id", file=sys.stderr) return 2
light_budget = max(cfg.ping_count, cfg.gateway_ping_count) * max(1.0, cfg.ping_timeout) + 2.0 print(f"LocalNet-Dynamics collector {COLLECTOR_VERSION}") print(f"run id : {cfg.run_id}") print(f"target : {cfg.target} (ICMP x{cfg.ping_count}, TCP :{cfg.tcp_port} x{cfg.tcp_count})") print(f"gateway : {net.gateway or 'not detected'} link: {net.link_type}" f" interface: {net.interface or '?'} local ip: {net.local_ip or '?'}") print(f"dns server : {dns_server or 'none (DNS probes disabled)'} name: {cfg.dns_host}") print(f"http probe : {cfg.http_url or 'disabled'}") print(f"schedule : every {human_duration(cfg.interval)} for {human_duration(cfg.duration)}" f" (~{int(cfg.duration // cfg.interval) + 1} samples)") if cfg.speedtest: print(f"wan speed : every {human_duration(cfg.speedtest_every)}" f" ({'ookla cli' if _ookla_cli_path() else 'speedtest-cli module'})") if cfg.iperf_server: print(f"lan iperf3 : {cfg.iperf_server}:{cfg.iperf_port} every " f"{human_duration(cfg.iperf_every)}, {cfg.iperf_duration}s per test") print(f"output : {csv_path}") if cfg.interval < light_budget: print(f"warning: the worst-case probe time ({light_budget:.0f}s) exceeds the interval;" f" samples will be skipped during outages") if not net.gateway: print("warning: default gateway not detected; gateway metrics will be empty") print("Press Ctrl-C to stop; every completed sample is already on disk.\n")
install_sigterm_handler() started_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") summary = RunningSummary() status = "completed"
csv_file = csv_path.open("w", newline="", encoding="utf-8") writer = csv.DictWriter(csv_file, fieldnames=CSV_FIELDS) writer.writeheader() csv_file.flush() write_meta(json_path, cfg, net, dns_server, summary, "running", started_utc, 0.0, csv_path.name)
start_mono = time.monotonic() next_speed = start_mono if cfg.speedtest else None next_lan = start_mono if cfg.iperf_server else None next_route = start_mono + ROUTE_REFRESH_S next_meta = start_mono + META_REFRESH_S tick = 0 index = 0
try: with (KeepAwake() if cfg.keep_awake else contextlib.nullcontext()) as awake: if cfg.keep_awake and not (awake and awake.active): print("note: could not inhibit system sleep; disable sleep in the OS power settings") while True: due = start_mono + tick * cfg.interval if due - start_mono >= cfg.duration: break now = time.monotonic() if due > now: time.sleep(due - now) elapsed = time.monotonic() - start_mono
if time.monotonic() >= next_route: fresh = detect_network(cfg.target) if fresh.gateway: net = fresh dns_server = resolve_dns_server(cfg, net) next_route = time.monotonic() + ROUTE_REFRESH_S
run_speed = next_speed is not None and time.monotonic() >= next_speed run_lan = next_lan is not None and time.monotonic() >= next_lan s = collect_sample(cfg, net, dns_server, pool, run_speed, run_lan) s.sample_index = index s.elapsed_s = round(elapsed, 1) if run_speed: next_speed += cfg.speedtest_every if run_lan: next_lan += cfg.iperf_every if s.gateway_packet_loss_pct == 100.0: next_route = min(next_route, time.monotonic() + 60.0)
writer.writerow(asdict(s)) csv_file.flush() summary.add(s) index += 1 if not cfg.quiet: print(format_progress(s), flush=True)
if time.monotonic() >= next_meta: write_meta(json_path, cfg, net, dns_server, summary, "running", started_utc, time.monotonic() - start_mono, csv_path.name) next_meta = time.monotonic() + META_REFRESH_S
tick += 1 finished = time.monotonic() if finished > start_mono + tick * cfg.interval: skipped = int((finished - start_mono) // cfg.interval) - tick + 1 tick += skipped if not cfg.quiet: print(f" sample took {s.sample_duration_s}s; skipping {skipped} tick(s)") except KeyboardInterrupt: status = "interrupted" print("\nStopping; finalizing files...") finally: csv_file.close() pool.shutdown(wait=False)
elapsed = time.monotonic() - start_mono write_meta(json_path, cfg, net, dns_server, summary, status, started_utc, elapsed, csv_path.name) if summary.count: print_summary(summary, elapsed) print(f"\n{summary.count} samples written to {csv_path}\nrun metadata: {json_path}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126#!/usr/bin/env python3"""Assemble the huggingface/ folder: a self-contained copy of everything that ispublished on the Hugging Face Hub, ready for `hf upload`.
huggingface/ ├── README.md the dataset card (DATASET_CARD.md, unchanged) ├── LICENSE ├── CITATION.cff citation metadata for the dataset ├── requirements.txt ├── dataset/ consolidated files, analysis, raw run files ├── figures/png, pdf the figures the card embeds ├── scripts/ collector, builder, analysis, plotting, packaging └── tests/
Run it after build_dataset.py, analyze.py and plot_figures.py. The folder isrebuilt from scratch on every run and is ignored by git.
python package_huggingface.py python package_huggingface.py --out-dir /some/other/place"""
from __future__ import annotations
import argparseimport reimport shutilimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATASET_CITATION = """cff-version: 1.2.0message: "If you use this dataset, please cite it as below. The toolkit that produced it has its own citation in the source repository."type: datasettitle: "LocalNet-Dynamics: A Longitudinal Local Area Network Telemetry Dataset"authors: - family-names: "Ezharjan" given-names: "Alexander"version: {version}date-released: "{date}"license: MITurl: "https://huggingface.co/datasets/ezharjan/LocalNetDynamics"repository-code: "https://github.com/Ezharjan/LocalNetDynamicsDataset"abstract: >- A longitudinal telemetry dataset of a residential local area network, sampled every 30 seconds around the clock from a wired desktop for 19 days. Each sample records ICMP latency, jitter and loss to a reference host and to the gateway, TCP connect time, cached and recursive DNS response time, HTTP time-to-first-response and hourly WAN throughput tests, with time-of-day features and rule-based reference labels for forecasting, anomaly detection and quality-of-service research.keywords: - network telemetry - latency - jitter - packet loss - DNS - throughput - quality of service - anomaly detection - time series"""
def field(text: str, name: str) -> str: m = re.search(rf"^{name}:\s*\"?([^\"\n]+)\"?\s*$", text, re.MULTILINE) if not m: raise SystemExit(f"CITATION.cff has no '{name}' field") return m.group(1).strip()
def copy_tree(src: Path, dst: Path, patterns: tuple[str, ...]) -> list[Path]: copied = [] for pattern in patterns: for path in sorted(src.glob(pattern)): if path.is_file(): target = dst / path.relative_to(src) target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) copied.append(target) return copied
def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description="Assemble the folder that is uploaded to Hugging Face.") p.add_argument("--out-dir", default=str(ROOT / "huggingface")) args = p.parse_args(argv) out = Path(args.out_dir)
required = [ROOT / "DATASET_CARD.md", ROOT / "LICENSE", ROOT / "CITATION.cff", ROOT / "dataset" / "localnet_dynamics.parquet", ROOT / "dataset" / "analysis.json", ROOT / "figures" / "png"] missing = [str(path) for path in required if not path.exists()] if missing: raise SystemExit("missing, run build_dataset.py, analyze.py and plot_figures.py first:\n " + "\n ".join(missing))
if out.exists(): shutil.rmtree(out) out.mkdir(parents=True)
shutil.copy2(ROOT / "DATASET_CARD.md", out / "README.md") shutil.copy2(ROOT / "LICENSE", out / "LICENSE") shutil.copy2(ROOT / "requirements.txt", out / "requirements.txt") code_citation = (ROOT / "CITATION.cff").read_text(encoding="utf-8") (out / "CITATION.cff").write_text( DATASET_CITATION.format(version=field(code_citation, "version"), date=field(code_citation, "date-released")), encoding="utf-8")
files = [out / "README.md", out / "LICENSE", out / "requirements.txt", out / "CITATION.cff"] files += copy_tree(ROOT / "dataset", out / "dataset", ("localnet_dynamics.csv", "localnet_dynamics.parquet", "summary.json", "analysis.json", "raw/localnet_*.csv", "raw/localnet_*.json", "raw/events.csv")) files += copy_tree(ROOT / "figures", out / "figures", ("png/*.png", "pdf/*.pdf")) files += copy_tree(ROOT / "scripts", out / "scripts", ("*.py",)) files += copy_tree(ROOT / "tests", out / "tests", ("*.py",))
total = sum(f.stat().st_size for f in files) for f in files: print(f" {f.relative_to(out).as_posix():<60}{f.stat().st_size / 1e6:>9.2f} MB") print(f"{len(files)} files, {total / 1e6:.1f} MB written to {out}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570#!/usr/bin/env python3"""Render the LocalNet-Dynamics figures as PNG and PDF.
Reads the consolidated dataset and dataset/analysis.json (written byanalyze.py) and writes every figure twice, figures/png/<name>.png andfigures/pdf/<name>.pdf, cropped to the drawn area with no margin:
overview_timeline the whole capture: target RTT, TCP connect, first hop, loss diurnal_profile hour-of-day latency, loss (weekday/weekend) and tail shares calendar_heatmaps day-by-hour loss share, high-latency share, HTTP > 1 s share degradation_anatomy a path change next to a first-hop event, probe by probe tcp_vs_icmp the TCP/ICMP floor split that ping cannot see loss_anatomy what a lost echo means for the other probes regimes distributions before and after the change point autocorrelation persistence of every metric up to a one-day lag speedtest WAN throughput by time and by server labels reference-label shares in the two regimes
python plot_figures.py python plot_figures.py --input dataset/localnet_dynamics.parquet --out-dir figures"""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
import numpy as npimport pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parent))from analyze import ROOT, analyse, load # noqa: E402
BLUE, ORANGE, AQUA, YELLOW = "#2a78d6", "#eb6834", "#1baf7a", "#eda100"MAGENTA, GREEN, VIOLET, RED = "#e87ba4", "#008300", "#6250d6", "#e34948"INK, INK2, MUTED, GRID, AXIS = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"BLUES = ["#f3f7fd", "#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", "#0d366b"]NAVY = "#0d366b"LOSS_CLASSES = [("no_loss", "no loss"), ("one_lost", "1 of 10 lost"), ("two_plus_lost", "2+ of 10 lost")]WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
def style(plt) -> None: plt.rcParams.update({ "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white", "font.family": "sans-serif", "font.sans-serif": ["Inter", "Segoe UI", "Helvetica Neue", "Arial", "DejaVu Sans"], "font.size": 15, "axes.titlesize": 18, "axes.titleweight": "semibold", "axes.titlepad": 14, "axes.labelsize": 15, "axes.labelcolor": INK2, "xtick.labelsize": 13, "ytick.labelsize": 13, "xtick.color": INK2, "ytick.color": INK2, "legend.fontsize": 13, "legend.frameon": False, "axes.edgecolor": AXIS, "axes.linewidth": 1.0, "axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.8, "axes.axisbelow": True, "axes.spines.top": False, "axes.spines.right": False, "lines.linewidth": 2.0, "xtick.major.size": 0, "ytick.major.size": 0, "xtick.major.pad": 8, "ytick.major.pad": 8, "legend.handlelength": 1.6, })
def save(fig, out: Path, name: str) -> None: (out / "png").mkdir(parents=True, exist_ok=True) (out / "pdf").mkdir(parents=True, exist_ok=True) fig.savefig(out / "png" / f"{name}.png", dpi=200, bbox_inches="tight", pad_inches=0) fig.savefig(out / "pdf" / f"{name}.pdf", bbox_inches="tight", pad_inches=0, metadata={"CreationDate": None, "ModDate": None})
def month_day(ts) -> str: return f"{ts:%b %-d}" if sys.platform != "win32" else f"{ts:%b %d}".replace(" 0", " ")
def period_label(g: dict, key: str) -> str: first, last = pd.Timestamp(g[key]["first_date"]), pd.Timestamp(g[key]["last_date"]) return f"{month_day(first)} to {month_day(last)}"
def date_axis(ax, mdates) -> None: ax.xaxis.set_major_locator(mdates.DayLocator(interval=2)) ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d")) ax.xaxis.set_minor_locator(mdates.DayLocator()) for label in ax.get_xticklabels(): label.set_rotation(0)
def shade_episodes(ax, a: dict, labels: bool = False) -> list: handles = [] kinds = {"path change": (BLUE, 0.14, "path change (latency floor moved)"), "first hop": (AQUA, 0.22, "first-hop degradation"), "queueing": (YELLOW, 0.22, "queueing")} seen = set() for e in a["latency_episodes"]: color, alpha, text = kinds[e["kind"]] s, t = pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19]) ax.axvspan(s, t, color=color, alpha=alpha, linewidth=0, zorder=0) if e["kind"] not in seen: seen.add(e["kind"]) handles.append((color, alpha, text)) for o in a["outages"]: ax.axvline(pd.Timestamp(o["start_local"][:19]), color=RED, linewidth=2.2, alpha=0.9, zorder=1) split = pd.Timestamp(a["regimes"]["split_date"]) ax.axvline(split, color=INK2, linewidth=1.6, linestyle=(0, (5, 4)), zorder=1) return handles
# --------------------------------------------------------------------------- ## Figures# --------------------------------------------------------------------------- #
def fig_overview(df, a, out, plt, mdates): from matplotlib.lines import Line2D from matplotlib.patches import Patch x = df["ts_local"] fig, axes = plt.subplots(4, 1, figsize=(18, 13), sharex=True, gridspec_kw={"height_ratios": [3, 2.2, 1.6, 1.6], "hspace": 0.32}) rtt_cap = 40 ax = axes[0] handles = shade_episodes(ax, a) ax.plot(x, df["rtt_avg_ms"].clip(upper=rtt_cap), color=BLUE, linewidth=0.5, alpha=0.45) roll = df["rtt_avg_ms"].rolling(60, center=True, min_periods=20).median() ax.plot(x, roll, color=NAVY, linewidth=1.8) ax.set_ylim(0, rtt_cap) ax.set_ylabel("ms") ax.set_title(f"Round-trip time to {df['target'].iloc[0]} (ICMP, 10-echo mean per sample, clipped at {rtt_cap} ms)", loc="left") series = [Line2D([], [], color=BLUE, linewidth=1.2, alpha=0.7, label="per sample"), Line2D([], [], color=NAVY, linewidth=2.2, label="30-minute rolling median")] bands = [Patch(facecolor=c, alpha=min(1.0, al * 2.2), label=t) for c, al, t in handles] bands += [Line2D([], [], color=RED, linewidth=2.2, label="outage (gateway unreachable)"), Line2D([], [], color=INK2, linewidth=1.6, linestyle=(0, (5, 4)), label="change point in daily loss share")] fig.legend(handles=series + bands, loc="lower center", bbox_to_anchor=(0.5, 0.925), ncol=6, frameon=False, columnspacing=1.6, handletextpad=0.6)
ax = axes[1] shade_episodes(ax, a) ax.scatter(x, df["tcp_connect_min_ms"].clip(upper=rtt_cap), s=2.5, color=ORANGE, alpha=0.35, linewidth=0, rasterized=True) ax.set_ylim(0, rtt_cap) ax.set_ylabel("ms") ax.set_title("Fastest of 5 TCP handshakes to port 443 of the same host (sub-millisecond resolution)", loc="left")
ax = axes[2] shade_episodes(ax, a) ax.plot(x, df["gateway_rtt_avg_ms"].clip(upper=20), color=AQUA, linewidth=0.7) ax.set_ylim(0, 20) ax.set_ylabel("ms") ax.set_title("Round-trip time to the default gateway (first hop, clipped at 20 ms)", loc="left")
ax = axes[3] shade_episodes(ax, a) hourly = (df["packet_loss_pct"] > 0).groupby(df["ts_local"].dt.floor("h")).mean() * 100 ax.bar(hourly.index, hourly.values, width=pd.Timedelta(hours=1), color=RED, linewidth=0, alpha=0.9) ax.set_ylim(0, 100) ax.set_ylabel("% of samples") ax.set_title("Samples with at least one lost echo, per hour", loc="left") ax.set_xlabel("local time (America/New_York)") date_axis(ax, mdates) ax.set_xlim(x.min() - pd.Timedelta(hours=3), x.max() + pd.Timedelta(hours=3)) save(fig, out, "overview_timeline") plt.close(fig)
def fig_diurnal(df, a, out, plt): prof = pd.DataFrame(a["hour_profile"]).set_index("hour").reindex(range(24)) hours = np.arange(24) fig, axes = plt.subplots(1, 3, figsize=(20, 6.4), gridspec_kw={"wspace": 0.28}) ax = axes[0] ax.fill_between(hours, prof["rtt_p25"], prof["rtt_p75"], color=BLUE, alpha=0.16, linewidth=0, label="interquartile range") ax.plot(hours, prof["rtt_median"], color=BLUE, marker="o", markersize=6, label="median") ax.plot(hours, prof["rtt_p95"], color=NAVY, marker="o", markersize=6, label="95th percentile") ax.set_ylim(0, max(32, float(prof["rtt_p95"].max()) * 1.15)) ax.set_ylabel("target RTT (ms)") ax.set_title("Latency by local hour", loc="left") ax.legend(loc="upper center", ncol=1) ax = axes[1] ax.plot(hours, prof["loss_share_weekday_pct"], color=BLUE, marker="o", markersize=6, label="weekdays") ax.plot(hours, prof["loss_share_weekend_pct"], color=ORANGE, marker="o", markersize=6, label="weekends") ax.set_ylim(0, max(30, float(prof[["loss_share_weekday_pct", "loss_share_weekend_pct"]].max().max()) * 1.2)) ax.set_ylabel("% of samples with a lost echo") ax.set_title("Loss by local hour", loc="left") ax.legend(loc="upper left") ax = axes[2] ax.plot(hours, prof["http_over_1s_pct"], color=VIOLET, marker="o", markersize=6, label="HTTP response > 1 s") ax.plot(hours, prof["high_latency_pct"], color=BLUE, marker="o", markersize=6, label="high-latency label") ax.set_ylim(0, max(25, float(prof[["http_over_1s_pct", "high_latency_pct"]].max().max()) * 1.25)) ax.set_ylabel("% of samples") ax.set_title("Two tails with opposite clocks", loc="left") ax.legend(loc="upper center") for ax in axes: ax.set_xticks(range(0, 24, 3)) ax.set_xticklabels([f"{h:02d}" for h in range(0, 24, 3)]) ax.set_xlim(-0.5, 23.5) ax.set_xlabel("local hour") save(fig, out, "diurnal_profile") plt.close(fig)
def fig_heatmaps(df, a, out, plt): from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list("blues", BLUES).with_extremes(bad="#eeede9") panels = [ ("packet_loss_pct", lambda s: 100 * (s > 0).mean(), "Samples with a lost echo (%)"), ("label_high_latency", lambda s: 100 * s.mean(), "Samples over the high-latency threshold (%)"), ("http_ms", lambda s: 100 * (s.dropna() > 1000).mean(), "HTTP responses slower than 1 s (%)"), ] dates = sorted(df["date_local"].unique()) weekday = df.groupby("date_local")["weekday_local"].first() fig, axes = plt.subplots(1, 3, figsize=(22, 0.42 * len(dates) + 2.4), gridspec_kw={"wspace": 0.12}) for ax, (col, fn, title) in zip(axes, panels): pivot = df.pivot_table(index="date_local", columns="hour_local", values=col, aggfunc=fn) pivot = pivot.reindex(index=dates, columns=range(24)) vmax = max(1.0, float(np.nanpercentile(pivot.values, 98))) im = ax.imshow(np.ma.masked_invalid(pivot.values.astype(float)), aspect="auto", cmap=cmap, vmin=0, vmax=vmax, interpolation="nearest") ax.set_xticks(range(0, 24, 3)) ax.set_xticklabels([f"{h:02d}" for h in range(0, 24, 3)]) ax.set_xlabel("local hour") ax.set_title(title, loc="left") ax.grid(False) for spine in ax.spines.values(): spine.set_visible(False) cbar = fig.colorbar(im, ax=ax, orientation="horizontal", fraction=0.045, pad=0.14, aspect=28) cbar.outline.set_visible(False) cbar.ax.tick_params(labelsize=12) axes[0].set_yticks(range(len(dates))) axes[0].set_yticklabels([f"{WEEKDAYS[int(weekday[d])]} {pd.Timestamp(d):%b %d}" for d in dates]) for d, label in zip(dates, axes[0].get_yticklabels()): if int(weekday[d]) >= 5: label.set_color(ORANGE) label.set_fontweight("semibold") for ax in axes[1:]: ax.set_yticks([]) save(fig, out, "calendar_heatmaps") plt.close(fig)
def fig_anatomy(df, a, out, plt, mdates): def window(kind): """The longest episode of this kind, extended over same-kind episodes within two hours of it.""" eps = [e for e in a["latency_episodes"] if e["kind"] == kind] if not eps: return None chain = [max(eps, key=lambda e: e["hours"])] grown = True while grown: grown = False lo = min(pd.Timestamp(e["start_local"][:19]) for e in chain) - pd.Timedelta(hours=2) hi = max(pd.Timestamp(e["end_local"][:19]) for e in chain) + pd.Timedelta(hours=2) for e in eps: if e not in chain and lo <= pd.Timestamp(e["start_local"][:19]) <= hi: chain.append(e) grown = True return sorted(chain, key=lambda e: e["start_local"])
chosen = [(window("path change"), "Path change"), (window("first hop"), "First-hop event")] chosen = [(c, t) for c, t in chosen if c] if not chosen: return fig, axes = plt.subplots(2, len(chosen), figsize=(10 * len(chosen), 9.5), sharex="col", gridspec_kw={"height_ratios": [2.4, 1], "hspace": 0.22, "wspace": 0.16}, squeeze=False) cap, top = 45, 60 for col, (chain, title) in enumerate(chosen): start = pd.Timestamp(chain[0]["start_local"][:19]) end = pd.Timestamp(chain[-1]["end_local"][:19]) part = df[(df["ts_local"] >= start - pd.Timedelta(hours=2)) & (df["ts_local"] <= end + pd.Timedelta(hours=2))] x = part["ts_local"] tint = BLUE if chain[0]["kind"] == "path change" else AQUA ax = axes[0, col] for e in chain: ax.axvspan(pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19]), color=tint, alpha=0.12, linewidth=0) ax.plot(x, part["rtt_avg_ms"].clip(upper=cap), color=BLUE, linewidth=1.0, alpha=0.5, label="ICMP mean of 10") ax.plot(x, part["rtt_min_ms"].clip(upper=cap), color=NAVY, linewidth=1.4, label="ICMP minimum of 10") ax.plot(x, part["tcp_connect_min_ms"].clip(upper=cap), color=ORANGE, linewidth=1.2, alpha=0.9, label="TCP fastest of 5") ax.set_ylim(0, top) ax.set_ylabel(f"ms to target (clipped at {cap})") hours = (end - start).total_seconds() / 3600.0 ax.set_title(f"{title}: {WEEKDAYS[chain[0]['weekday']]} {month_day(start)}, {hours:.1f} h", loc="left") ax.legend(loc="upper left", ncol=3) ax = axes[1, col] for e in chain: ax.axvspan(pd.Timestamp(e["start_local"][:19]), pd.Timestamp(e["end_local"][:19]), color=tint, alpha=0.12, linewidth=0) ax.plot(x, part["gateway_rtt_avg_ms"].clip(upper=30), color=AQUA, linewidth=1.2) ax.set_ylim(0, 30) ax.set_ylabel("ms to gateway") ax.set_xlabel("local time") ax.xaxis.set_major_locator(mdates.HourLocator(interval=2)) ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M")) save(fig, out, "degradation_anatomy") plt.close(fig)
def fig_tcp_icmp(df, a, out, plt, mdates): split = pd.Timestamp(a["tcp_icmp"]["split_local"]) fig, axes = plt.subplots(1, 2, figsize=(20, 6.4), gridspec_kw={"width_ratios": [2.3, 1], "wspace": 0.2}) ax = axes[0] x = df["ts_local"] cap = 35 from matplotlib.lines import Line2D ax.scatter(x, df["tcp_connect_min_ms"].clip(upper=cap), s=2.5, color=ORANGE, alpha=0.35, linewidth=0, rasterized=True) roll = df["rtt_min_ms"].rolling(120, center=True, min_periods=30).median() ax.plot(x, roll, color=NAVY, linewidth=2.0) handles = [Line2D([], [], marker="o", color=ORANGE, linestyle="none", markersize=8, label="TCP fastest of 5 handshakes, per sample"), Line2D([], [], color=NAVY, linewidth=2.2, label="ICMP minimum of 10, 1-hour rolling median")] ax.axvline(split, color=INK2, linewidth=1.6, linestyle=(0, (5, 4))) ax.text(split, cap * 0.97, f" {month_day(split)} {split:%H:%M}", color=INK2, va="top", ha="left", fontsize=13) ax.set_ylim(0, cap) ax.set_ylabel("ms") ax.set_xlabel("local time") ax.set_title("Latency floor seen by TCP and by ICMP", loc="left") ax.legend(handles=handles, loc="lower left") date_axis(ax, mdates) ax = axes[1] before = df.loc[df["ts_local"] < split, "tcp_connect_min_ms"].dropna() after = df.loc[df["ts_local"] >= split, "tcp_connect_min_ms"].dropna() bins = np.arange(8, 32.5, 0.5) ax.hist(before.clip(8, 32), bins=bins, density=True, color=MUTED, alpha=0.75, linewidth=0, label=f"before ({len(before):,} samples)") ax.hist(after.clip(8, 32), bins=bins, density=True, color=ORANGE, alpha=0.8, linewidth=0, label=f"after ({len(after):,} samples)") ax.set_xlabel("TCP fastest handshake (ms)") ax.set_ylabel("density") ax.set_title("Before and after the split", loc="left") ax.legend(loc="upper right") save(fig, out, "tcp_vs_icmp") plt.close(fig)
def fig_loss(df, a, out, plt): L = a["loss"] fig = plt.figure(figsize=(20, 11)) gs = fig.add_gridspec(2, 3, height_ratios=[1, 1.1], hspace=0.45, wspace=0.3) ax = fig.add_subplot(gs[0, 0]) counts = {int(k): v for k, v in L["packets_received_counts"].items()} keys = sorted(counts, reverse=True) ax.bar(range(len(keys)), [counts[k] for k in keys], color=BLUE, linewidth=0, width=0.72) ax.set_xticks(range(len(keys))) ax.set_xticklabels([str(k) for k in keys]) ax.set_yscale("log") ax.set_ylim(1, max(counts.values()) * 4) ax.set_xlabel("echo replies received out of 10") ax.set_ylabel("samples (log scale)") ax.set_title("Loss comes one echo at a time", loc="left") for i, k in enumerate(keys): ax.text(i, counts[k] * 1.25, f"{counts[k]:,}", ha="center", va="bottom", fontsize=12, color=INK2)
xs = np.arange(len(LOSS_CLASSES)) w = 0.36 c = L["conditional"]
def grouped(ax, left, right, unit, title): for offset, (key, color, name) in zip((-w / 2, w / 2), (left, right)): values = [c[k][key] or 0.0 for k, _ in LOSS_CLASSES] ax.bar(xs + offset, values, w, color=color, linewidth=0, label=name) for i, v in enumerate(values): ax.text(i + offset, v + 0.02 * top, f"{v:.1f}", ha="center", fontsize=12, color=INK2) ax.set_xticks(xs) ax.set_xticklabels([t for _, t in LOSS_CLASSES]) ax.set_ylabel(unit) ax.set_ylim(0, top) ax.set_title(title, loc="left") ax.legend(loc="upper left")
top = max(1.0, max((c[k]["http_over_1s_pct"] or 0.0) for k, _ in LOSS_CLASSES) * 1.35) grouped(fig.add_subplot(gs[0, 1]), ("http_over_1s_pct", VIOLET, "HTTP response > 1 s"), ("dns_recursive_over_200ms_pct", GREEN, "recursive DNS > 200 ms"), "% of samples", "Application tails grow with ICMP loss") top = max(1.0, max((c[k]["tcp_median"] or 0.0) for k, _ in LOSS_CLASSES) * 1.4) grouped(fig.add_subplot(gs[0, 2]), ("jitter_median", MAGENTA, "jitter, median"), ("tcp_median", ORANGE, "TCP handshake, median"), "ms", "Jitter rises, the TCP handshake does not")
ax = fig.add_subplot(gs[1, :]) h = df["http_ms"].dropna() lo, hi = 20, 8000 bins = np.logspace(np.log10(lo), np.log10(hi), 150) ax.hist(h.clip(lo, hi), bins=bins, color=VIOLET, linewidth=0) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlim(lo, hi) ticks = [20, 50, 100, 200, 500, 1000, 2000, 5000] ax.set_xticks(ticks) ax.set_xticklabels([f"{t:,}" for t in ticks]) ax.set_xlabel("HTTP time to response headers (ms, log scale)") ax.set_ylabel("samples (log scale)") H = a["dns_http"]["http"] ax.set_title(f"HTTP response time: a smooth body around {H['median']:.0f} ms, then discrete modes near " "1.1 s, 1.3 s and 4.1 s where lost packets wait for retransmission timers", loc="left") ax.axvspan(1000, 1400, color=VIOLET, alpha=0.1, linewidth=0) ax.axvspan(3900, 4400, color=VIOLET, alpha=0.1, linewidth=0) save(fig, out, "loss_anatomy") plt.close(fig)
def fig_regimes(df, a, out, plt): g = a["regimes"] split = g["split_date"] before, after = df[df["date_local"] < split], df[df["date_local"] >= split] panels = [("rtt_avg_ms", "ICMP round-trip time, mean of 10 (ms)", (8, 60), [10, 15, 20, 30, 40, 60]), ("jitter_ms", "ICMP jitter (ms)", (0.1, 30), [0.1, 0.3, 1, 3, 10, 30]), ("tcp_connect_median_ms", "TCP handshake, median of 5 (ms)", (10, 80), [10, 15, 20, 30, 40, 60, 80]), ("dns_resolve_ms", "DNS, resolver-cached name (ms)", (5, 300), [5, 10, 20, 50, 100, 200, 300]), ("dns_recursive_ms", "DNS, recursive lookup (ms)", (20, 2000), [20, 50, 100, 200, 500, 1000, 2000]), ("http_ms", "HTTP time to response headers (ms)", (30, 5000), [30, 100, 300, 1000, 3000])] fig, axes = plt.subplots(2, 3, figsize=(20, 10), gridspec_kw={"hspace": 0.5, "wspace": 0.18}) for i, (ax, (col, title, lim, ticks)) in enumerate(zip(axes.ravel(), panels)): for part, color, key in ((before, BLUE, "before"), (after, ORANGE, "after")): v = np.sort(part[col].dropna().values) if v.size == 0: continue v = np.clip(v, lim[0], lim[1]) ax.step(v, np.arange(1, v.size + 1) / v.size * 100, where="post", color=color, linewidth=2.2, label=f"{key}: {period_label(g, key)}") ax.set_xscale("log") ax.set_xlim(*lim) ax.set_xticks(ticks) ax.set_xticklabels([f"{t:g}" for t in ticks]) ax.xaxis.set_minor_locator(plt.NullLocator()) ax.set_ylim(0, 100) ax.set_yticks([0, 25, 50, 75, 100]) if i % 3 == 0: ax.set_ylabel("% of samples at or below") ax.set_title(title, loc="left") axes[0, 0].legend(loc="lower right") save(fig, out, "regimes") plt.close(fig)
def fig_acf(df, a, out, plt): A = a["autocorrelation"] lags = A["lag_minutes"] series = [("log_rtt_avg_ms", "ICMP RTT (log)", BLUE), ("jitter_ms", "jitter", MAGENTA), ("loss_indicator", "lost echo (0/1)", RED), ("tcp_connect_min_ms", "TCP fastest handshake", ORANGE), ("dns_recursive_ms", "recursive DNS", GREEN), ("http_ms", "HTTP", VIOLET)] fig, ax = plt.subplots(figsize=(16, 7)) for key, name, color in series: pts = [(l, v) for l, v in zip(lags, A["values"][key]) if v is not None] if pts: ax.plot([l for l, _ in pts], [v for _, v in pts], color=color, marker="o", markersize=6, label=name) ax.set_xscale("log") ticks = [0.5, 1, 2.5, 5, 10, 30, 60, 180, 360, 720, 1440] ax.set_xticks(ticks) 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"]) ax.set_xlim(0.4, 1440 * 1.3) ax.set_ylim(-0.05, 1.0) ax.axhline(0, color=AXIS, linewidth=1.0) ax.set_xlabel("lag") ax.set_ylabel("autocorrelation") ax.set_title("How long the network remembers: autocorrelation of each probe against lag", loc="left") ax.legend(loc="upper right", ncol=2) save(fig, out, "autocorrelation") plt.close(fig)
def fig_speedtest(df, a, out, plt, mdates): sp = df[df["download_mbps"].notna()].copy() if sp.empty: return S = a["speedtest"] failed = sp["speedtest_ping_ms"].isna() | (sp["speedtest_ping_ms"] >= 600_000) fig = plt.figure(figsize=(20, 9.5)) gs = fig.add_gridspec(2, 2, width_ratios=[1.45, 1], hspace=0.42, wspace=0.12) for row, (col, color, title) in enumerate((("download_mbps", BLUE, "Download"), ("upload_mbps", ORANGE, "Upload"))): ax = fig.add_subplot(gs[row, 0]) ok, bad = sp[~failed], sp[failed] ax.scatter(ok["ts_local"], ok[col], s=30, color=color, alpha=0.85, linewidth=0, label="server latency probe succeeded") ax.scatter(bad["ts_local"], bad[col], s=42, facecolor="white", edgecolor=color, linewidth=1.4, label="server latency probe failed") ax.set_ylabel("Mbit/s") ax.set_title(f"{title}: {len(sp)} hourly tests on {S['servers']} different servers" if row == 0 else title, loc="left") ax.set_ylim(0, float(sp[col].max()) * 1.12) if row == 0: ax.legend(loc="upper left", ncol=2) else: ax.set_xlabel("local time") date_axis(ax, mdates) ax = fig.add_subplot(gs[:, 1]) top = S["top_servers"] names = [t["server"] for t in top] for i, t in enumerate(top): part = sp[sp["speedtest_server"] == t["server"]] y = np.full(len(part), i) + np.random.default_rng(i).uniform(-0.18, 0.18, len(part)) ax.scatter(part["download_mbps"], y, s=34, color=BLUE, alpha=0.6, linewidth=0) ax.plot([t["download_median"], t["download_median"]], [i - 0.32, i + 0.32], color=NAVY, linewidth=3) ax.set_yticks(range(len(top))) ax.set_yticklabels([f"{n} ({t['n']})" for n, t in zip(names, top)]) ax.yaxis.tick_right() ax.invert_yaxis() ax.set_xlabel("download (Mbit/s); bar = median of that server") ax.set_title("Download depends on which server was picked", loc="left") save(fig, out, "speedtest") plt.close(fig)
def fig_labels(df, a, out, plt): g = a["regimes"] names = [("label_outage", "outage"), ("label_packet_loss", "packet loss"), ("label_high_latency", "high latency"), ("label_high_jitter", "high jitter"), ("label_gateway_degraded", "gateway degraded"), ("label_anomaly", "any (anomaly)")] ys = np.arange(len(names)) h = 0.38 fig, ax = plt.subplots(figsize=(14, 6.6)) b = [g["before"]["labels_pct"][k] for k, _ in names] c = [g["after"]["labels_pct"][k] for k, _ in names] ax.barh(ys - h / 2, b, h, color=BLUE, linewidth=0, label=period_label(g, "before")) ax.barh(ys + h / 2, c, h, color=ORANGE, linewidth=0, label=period_label(g, "after")) for y, v in zip(ys - h / 2, b): ax.text(v + 0.6, y, f"{v:.1f} %", va="center", fontsize=13, color=INK2) for y, v in zip(ys + h / 2, c): ax.text(v + 0.6, y, f"{v:.1f} %", va="center", fontsize=13, color=INK2) ax.set_yticks(ys) ax.set_yticklabels([n for _, n in names]) ax.invert_yaxis() ax.set_xlim(0, max(b + c) * 1.18) ax.set_xlabel("% of samples carrying the label") ax.set_title("Reference labels before and after the change point", loc="left") ax.legend(loc="upper right") save(fig, out, "labels") plt.close(fig)
# --------------------------------------------------------------------------- ## CLI# --------------------------------------------------------------------------- #
def render_all(df: pd.DataFrame, a: dict, out: Path) -> list[str]: import matplotlib matplotlib.use("Agg") import matplotlib.dates as mdates import matplotlib.pyplot as plt style(plt) out.mkdir(parents=True, exist_ok=True) fig_overview(df, a, out, plt, mdates) fig_diurnal(df, a, out, plt) fig_heatmaps(df, a, out, plt) fig_anatomy(df, a, out, plt, mdates) fig_tcp_icmp(df, a, out, plt, mdates) fig_loss(df, a, out, plt) fig_regimes(df, a, out, plt) fig_acf(df, a, out, plt) fig_speedtest(df, a, out, plt, mdates) fig_labels(df, a, out, plt) return sorted(p.name for p in (out / "png").glob("*.png"))
def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description="Render the dataset figures as PNG and PDF.") p.add_argument("--input", default=None, help="consolidated parquet or CSV (default: dataset/localnet_dynamics.parquet)") p.add_argument("--analysis", default=None, help="analysis JSON from analyze.py (default: next to the input; recomputed if missing)") p.add_argument("--out-dir", default=str(ROOT / "figures")) args = p.parse_args(argv)
path = Path(args.input) if args.input else ROOT / "dataset" / "localnet_dynamics.parquet" if not path.exists() and not args.input: path = ROOT / "dataset" / "localnet_dynamics.csv" if not path.exists(): raise SystemExit(f"{path} not found; run build_dataset.py first") df = load(path) analysis_path = Path(args.analysis) if args.analysis else path.parent / "analysis.json" if analysis_path.exists(): a = json.loads(analysis_path.read_text(encoding="utf-8")) else: summary_path = path.parent / "summary.json" summary = json.loads(summary_path.read_text(encoding="utf-8")) if summary_path.exists() else None a = analyse(df, summary) names = render_all(df, a, Path(args.out_dir)) print(f"{len(names)} figures written to {args.out_dir} (png/ and pdf/): " + ", ".join(names)) return 0
if __name__ == "__main__": sys.exit(main())123456import sys
from pathlib import Path
SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"
if str(SCRIPTS) not in sys.path:
sys.path.insert(0, str(SCRIPTS))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""End-to-end tests for build_dataset.py, annotate.py, analyze.py and plot_figures.py.
A small raw run is synthesised in a temporary directory with the collector'sown schema so that the build pipeline, label rules, event join and figurerendering can be exercised without network access. Nothing here is writteninto the repository's dataset directory."""
import csvimport jsonimport mathimport randomfrom datetime import datetime, timedelta, timezonefrom pathlib import Path
import pytest
pd = pytest.importorskip("pandas")
import annotate # noqa: E402import build_dataset as bd # noqa: E402import collect_data as cd # noqa: E402
START = datetime(2026, 9, 6, 22, 0, 0, tzinfo=timezone.utc) # 18:00 local (UTC-4)INTERVAL = 60ROWS = 3 * 60 * 6 # 18 h of 1-minute samplesLOCAL_OFFSET = timedelta(hours=-4)
def write_synthetic_run(raw_dir: Path, run_id: str = "testhost_20260906_180000") -> Path: rng = random.Random(7) rows = [] for i in range(ROWS): t = START + timedelta(seconds=i * INTERVAL) if 400 <= i < 405: # simulated gap of five samples (machine asleep) continue s = cd.Sample(run_id=run_id, host_label="testhost", sample_index=i, timestamp_utc=t.strftime("%Y-%m-%dT%H:%M:%SZ"), timestamp_local=(t + LOCAL_OFFSET).strftime("%Y-%m-%dT%H:%M:%S-04:00"), epoch_s=int(t.timestamp()), elapsed_s=float(i * INTERVAL), link_type="wifi", gateway_ip="192.168.1.1", dns_server="192.168.1.1", target="8.8.8.8") base = 14.0 + 4.0 * math.sin((i / 60.0) / 24.0 * 2 * math.pi) rtts = [max(1.0, rng.gauss(base, 1.2)) for _ in range(10)] if i in (700, 701, 702): # simulated outage rtts = [] elif i % 97 == 0: # occasional single lost packet rtts = rtts[:9] elif i == 900: # latency spike rtts = [r + 120 for r in rtts] st = cd.rtt_stats(rtts) s.rtt_min_ms, s.rtt_avg_ms, s.rtt_median_ms = st["min"], st["avg"], st["median"] s.rtt_max_ms, s.rtt_stddev_ms, s.jitter_ms = st["max"], st["stddev"], st["jitter"] s.packets_sent, s.packets_received = 10, len(rtts) s.packet_loss_pct = round(100.0 * (10 - len(rtts)) / 10, 1) g = [max(0.3, rng.gauss(2.0, 0.5)) for _ in range(5)] if i == 1000: g = [r + 60 for r in g] gst = cd.rtt_stats(g) s.gateway_rtt_min_ms, s.gateway_rtt_avg_ms = gst["min"], gst["avg"] s.gateway_rtt_max_ms, s.gateway_jitter_ms = gst["max"], gst["jitter"] s.gateway_packet_loss_pct = 0.0 s.tcp_connect_min_ms = round(base - 0.5, 3) s.tcp_connect_median_ms = round(base, 3) s.dns_resolve_ms = round(rng.gauss(2.5, 0.4), 3) s.dns_recursive_ms = round(rng.gauss(40, 8), 3) s.http_ms, s.http_status = round(rng.gauss(60, 10), 3), 200 s.wifi_signal_pct = 80 + (i % 5) s.wifi_rssi_dbm = cd.rssi_from_quality(s.wifi_signal_pct) s.wifi_rx_mbps, s.wifi_tx_mbps = 866.7, 866.7 s.wifi_channel, s.wifi_band_ghz, s.wifi_phy = 36, 5.0, "802.11ax" if i % 30 == 0: s.download_mbps, s.upload_mbps = round(rng.gauss(450, 30), 2), round(rng.gauss(22, 2), 2) s.speedtest_ping_ms = 1800000.0 if i == 60 else 9.5 # one failed latency probe s.speedtest_server_id, s.speedtest_server = 1234, "Example ISP, Springfield" s.sample_duration_s = 10.4 s.notes = "ping: no replies" if not rtts else "" rows.append(cd.asdict(s)) raw_dir.mkdir(parents=True, exist_ok=True) csv_path = raw_dir / f"localnet_{run_id}.csv" with csv_path.open("w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=cd.CSV_FIELDS) w.writeheader() w.writerows(rows) meta = {"run_id": run_id, "collector_version": cd.COLLECTOR_VERSION, "status": "completed", "interval_s": float(INTERVAL), "sample_count": len(rows), "environment": {"os": "Windows-11-10.0.22631-SP0", "ping_resolution_ms": 1.0}, "network": {"link_type": "wifi"}} csv_path.with_suffix(".json").write_text(json.dumps(meta), encoding="utf-8") return csv_path
@pytest.fixture(scope="module")def built(tmp_path_factory): root = tmp_path_factory.mktemp("ds") raw = root / "raw" write_synthetic_run(raw) # a manual annotation covering the simulated outage annotate.main(["router rebooted", "--category", "maintenance", "--start", "2026-09-07T09:39:30Z", "--end", "2026-09-07T09:43:00Z", "--file", str(raw / "events.csv")]) card = root / "DATASET_CARD.md" card.write_text("---\nsize_categories:\n - n<1K\n---\n# card\n\n" f"{bd.CARD_BEGIN}\nold\n{bd.CARD_END}\n", encoding="utf-8") bd.main(["--raw-dir", str(raw), "--out-dir", str(root), "--card", str(card)]) df = pd.read_csv(root / "localnet_dynamics.csv") summary = json.loads((root / "summary.json").read_text(encoding="utf-8")) return root, df, summary, card
def test_rows_and_columns(built): root, df, summary, _ = built assert len(df) == ROWS - 5 assert list(df.columns[:11]) == cd.CSV_FIELDS[:11] assert df.columns[-1] == "notes" for col in bd.RUN_COLUMNS + bd.TIME_COLUMNS + bd.LABEL_COLUMNS + bd.EVENT_COLUMNS: assert col in df.columns assert (root / "localnet_dynamics.parquet").exists() assert summary["rows"] == len(df) and summary["runs"][0]["interval_s"] == 60.0 assert summary["runs"][0]["os"].startswith("Windows") assert df["collector_os"].iloc[0] == "Windows" and df["rtt_resolution_ms"].iloc[0] == 1.0
def test_time_features_and_gaps(built): _, df, summary, _ = built first = df.iloc[0] assert first["hour_local"] == 18 and first["date_local"] == "2026-09-06" assert first["weekday_local"] == 6 and first["is_weekend"] == 1 # Sunday gaps = df["gap_before_s"].dropna() assert gaps.max() == 6 * INTERVAL and (gaps == INTERVAL).sum() == len(gaps) - 1 assert 99.0 < summary["coverage_pct"] < 100.0
def test_reference_labels(built): _, df, summary, _ = built outages = df[df["label_outage"] == 1] assert list(outages["sample_index"]) == [700, 701, 702] assert df.loc[df["sample_index"] == 900, "label_high_latency"].item() == 1 assert df.loc[df["sample_index"] == 1000, "label_gateway_degraded"].item() == 1 assert df.loc[df["sample_index"] == 97, "label_packet_loss"].item() == 1 assert df.loc[df["sample_index"] == 97, "label_outage"].item() == 0 assert df["label_high_latency"].sum() <= 5 # rule is not over-sensitive assert (df["label_anomaly"] >= df["label_outage"]).all() thr = summary["runs"][0]["thresholds"]["rtt_avg_ms"] assert thr["threshold"] >= thr["median"] + 10.0 assert summary["labels"]["label_outage"]["rows"] == 3
def test_failed_speedtest_latency_is_missing(built): _, df, summary, _ = built tests = df[df["download_mbps"].notna()] assert len(tests) == 36 assert tests["speedtest_ping_ms"].isna().sum() == 1 assert tests.loc[tests["sample_index"] == 60, "speedtest_ping_ms"].isna().all() assert summary["metrics"]["speedtest_ping_ms"]["max"] == 9.5
def test_event_join(built): _, df, summary, _ = built tagged = df[df["event_category"].fillna("") != ""] assert summary["events"] == 1 assert set(tagged["sample_index"]) == {700, 701, 702, 703} assert (tagged["event_description"] == "router rebooted").all()
def test_card_updated(built): _, _, summary, card = built text = card.read_text(encoding="utf-8") assert "old" not in text assert f"| Rows | {summary['rows']:,} |" in text assert "size_categories:\n - 1K<n<10K" in text assert text.count(bd.CARD_BEGIN) == 1 and text.count(bd.CARD_END) == 1
def test_size_category(): assert bd.size_category(500) == "n<1K" assert bd.size_category(86_400) == "10K<n<100K" assert bd.size_category(2_000_000) == "1M<n<10M"
def test_analysis_json(built): import analyze root, df, summary, _ = built analyze.main(["--input", str(root / "localnet_dynamics.csv"), "--no-report"]) a = json.loads((root / "analysis.json").read_text(encoding="utf-8")) assert a["overview"]["rows"] == len(df) assert len(a["hour_profile"]) == 18 and len(a["daily"]) == 2 assert len(a["outages"]) == 1 and a["outages"][0]["samples"] == 3 assert a["regimes"]["before"]["n"] + a["regimes"]["after"]["n"] == len(df) assert a["speedtest"]["tests"] == 36 and a["speedtest"]["failed_latency_probe"] == 1 assert a["labels"]["counts"]["label_outage"] == 3 assert set(a["autocorrelation"]["values"]) >= {"log_rtt_avg_ms", "loss_indicator", "http_ms"}
def test_figures(built, tmp_path): pytest.importorskip("matplotlib") import plot_figures root, _, _, _ = built out = tmp_path / "figures" plot_figures.main(["--input", str(root / "localnet_dynamics.csv"), "--out-dir", str(out)]) for name in ("overview_timeline", "diurnal_profile", "calendar_heatmaps", "tcp_vs_icmp", "loss_anatomy", "regimes", "autocorrelation", "speedtest", "labels"): assert (out / "png" / f"{name}.png").stat().st_size > 10_000, name assert (out / "pdf" / f"{name}.pdf").stat().st_size > 1_000, name
def test_annotate_parses_local_and_utc_times(): assert annotate.parse_time("2026-09-12T16:00:00Z").isoformat() == "2026-09-12T16:00:00+00:00" assert annotate.parse_time("2026-09-12 16:00+02:00").isoformat() == "2026-09-12T14:00:00+00:00" local = annotate.parse_time("2026-09-12 16:00") assert local.tzinfo == timezone.utc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531"""Unit tests for the parsing and measurement helpers in collect_data.py.
The fixtures below reproduce the output formats of the system utilities onthe platforms and locales the collector supports. They exercise the parserswithout needing network access."""
import jsonimport struct
import pytest
import collect_data as cd
# --------------------------------------------------------------------------- ## ping output# --------------------------------------------------------------------------- #
WINDOWS_EN = """Pinging 8.8.8.8 with 32 bytes of data:Reply from 8.8.8.8: bytes=32 time=14ms TTL=117Reply from 8.8.8.8: bytes=32 time<1ms TTL=117Request timed out.Reply from 8.8.8.8: bytes=32 time=20ms TTL=117
Ping statistics for 8.8.8.8: Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 20ms, Average = 11ms"""
WINDOWS_ZH = """正在 Ping 8.8.8.8 具有 32 字节的数据:来自 8.8.8.8 的回复: 字节=32 时间=14ms TTL=117来自 8.8.8.8 的回复: 字节=32 时间=15ms TTL=117请求超时。来自 8.8.8.8 的回复: 字节=32 时间<1ms TTL=117
8.8.8.8 的 Ping 统计信息: 数据包: 已发送 = 4,已接收 = 3,丢失 = 1 (25% 丢失),往返行程的估计时间(以毫秒为单位): 最短 = 0ms,最长 = 15ms,平均 = 9ms"""
WINDOWS_DE = """Ping wird ausgeführt für 8.8.8.8 mit 32 Bytes Daten:Antwort von 8.8.8.8: Bytes=32 Zeit=14ms TTL=117Antwort von 8.8.8.8: Bytes=32 Zeit=15ms TTL=117
Ping-Statistik für 8.8.8.8: Pakete: Gesendet = 2, Empfangen = 2, Verloren = 0 (0% Verlust),Ca. Zeitangaben in Millisek.: Minimum = 14ms, Maximum = 15ms, Mittelwert = 14ms"""
WINDOWS_FR = """Envoi d'une requête 'Ping' 8.8.8.8 avec 32 octets de données :Réponse de 8.8.8.8 : octets=32 temps=14 ms TTL=117Réponse de 8.8.8.8 : octets=32 temps=16 ms TTL=117
Statistiques Ping pour 8.8.8.8: Paquets : envoyés = 2, reçus = 2, perdus = 0 (perte 0%),Durée approximative des boucles en millisecondes : Minimum = 14ms, Maximum = 16ms, Moyenne = 15ms"""
WINDOWS_RU = """Обмен пакетами с 8.8.8.8 по с 32 байтами данных:Ответ от 8.8.8.8: число байт=32 время=14мс TTL=117Ответ от 8.8.8.8: число байт=32 время=17мс TTL=117
Статистика Ping для 8.8.8.8: Пакетов: отправлено = 2, получено = 2, потеряно = 0 (0% потерь)Приблизительное время приема-передачи в мс: Минимальное = 14мсек, Максимальное = 17 мсек, Среднее = 15 мсек"""
WINDOWS_IPV6 = """Pinging 2001:4860:4860::8888 with 32 bytes of data:Reply from 2001:4860:4860::8888: time=15msReply from 2001:4860:4860::8888: time=14ms
Ping statistics for 2001:4860:4860::8888: Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),Approximate round trip times in milli-seconds: Minimum = 14ms, Maximum = 15ms, Average = 14ms"""
WINDOWS_UNREACHABLE = """Pinging 10.9.9.9 with 32 bytes of data:Reply from 192.168.1.23: Destination host unreachable.Reply from 192.168.1.23: Destination host unreachable.PING: transmit failed. General failure.
Ping statistics for 10.9.9.9: Packets: Sent = 3, Received = 2, Lost = 1 (33% loss),"""
LINUX = """PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=14.2 ms64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=13.9 ms64 bytes from 8.8.8.8: icmp_seq=2 ttl=117 time=14.1 ms (DUP!)From 192.168.1.1 icmp_seq=3 Destination Host Unreachable64 bytes from 8.8.8.8: icmp_seq=4 ttl=117 time=15.0 ms
--- 8.8.8.8 ping statistics ---4 packets transmitted, 3 received, +1 duplicates, 25% packet loss, time 3004msrtt min/avg/max/mdev = 13.900/14.367/15.000/0.464 ms"""
MACOS = """PING 8.8.8.8 (8.8.8.8): 56 data bytes64 bytes from 8.8.8.8: icmp_seq=0 ttl=117 time=14.234 ms64 bytes from 8.8.8.8: icmp_seq=1 ttl=117 time=13.877 msRequest timeout for icmp_seq 264 bytes from 8.8.8.8: icmp_seq=3 ttl=117 time=15.001 ms
--- 8.8.8.8 ping statistics ---4 packets transmitted, 3 packets received, 25.0% packet lossround-trip min/avg/max/stddev = 13.877/14.371/15.001/0.478 ms"""
BUSYBOX = """PING 8.8.8.8 (8.8.8.8): 56 data bytes64 bytes from 8.8.8.8: seq=0 ttl=117 time=14.210 ms64 bytes from 8.8.8.8: seq=1 ttl=117 time=13.905 ms
--- 8.8.8.8 ping statistics ---2 packets transmitted, 2 packets received, 0% packet lossround-trip min/avg/max = 13.905/14.057/14.210 ms"""
@pytest.mark.parametrize("text, sent, expected", [ (WINDOWS_EN, 4, [14.0, 0.0, 20.0]), (WINDOWS_ZH, 4, [14.0, 15.0, 0.0]), (WINDOWS_DE, 2, [14.0, 15.0]), (WINDOWS_FR, 2, [14.0, 16.0]), (WINDOWS_RU, 2, [14.0, 17.0]), (WINDOWS_IPV6, 2, [15.0, 14.0]), (WINDOWS_UNREACHABLE, 3, []), (LINUX, 4, [14.2, 13.9, 15.0]), (MACOS, 4, [14.234, 13.877, 15.001]), (BUSYBOX, 2, [14.21, 13.905]),])def test_parse_ping_output(text, sent, expected): result = cd.parse_ping_output(text, sent=sent) assert result.rtts == expected assert result.received == len(expected) assert result.sent == sent assert result.loss_pct == round(100.0 * (sent - len(expected)) / sent, 1)
def test_loss_is_clamped_and_none_when_nothing_sent(): assert cd.PingResult(sent=0, received=0).loss_pct is None assert cd.PingResult(sent=2, received=5).loss_pct == 0.0
def test_rtt_stats(): st = cd.rtt_stats([10.0, 12.0, 11.0, 15.0]) assert st["min"] == 10.0 and st["max"] == 15.0 assert st["avg"] == 12.0 and st["median"] == 11.5 assert st["jitter"] == round((2 + 1 + 4) / 3, 3) assert st["stddev"] == pytest.approx(1.871, abs=1e-3) assert cd.rtt_stats([]) == {k: None for k in ("min", "avg", "median", "max", "stddev", "jitter")} single = cd.rtt_stats([7.0]) assert single["jitter"] is None and single["stddev"] == 0.0
def test_ping_command_flags(): assert cd.ping_command("8.8.8.8", 10, 2.0, "windows") == \ ["ping", "-n", "10", "-w", "2000", "-4", "8.8.8.8"] assert cd.ping_command("2001:db8::1", 3, 2.0, "windows")[-2] == "-6" assert cd.ping_command("8.8.8.8", 10, 2.0, "iputils") == \ ["ping", "-n", "-c", "10", "-W", "2", "8.8.8.8"] assert cd.ping_command("8.8.8.8", 4, 0.4, "iputils")[5] == "1" assert cd.ping_command("8.8.8.8", 10, 2.0, "busybox") == \ ["ping", "-c", "10", "-W", "2", "8.8.8.8"] assert cd.ping_command("8.8.8.8", 10, 2.5, "bsd") == \ ["ping", "-n", "-c", "10", "-W", "2500", "8.8.8.8"]
# --------------------------------------------------------------------------- ## routes, resolvers, interfaces# --------------------------------------------------------------------------- #
ROUTE_PRINT = """===========================================================================Interface List 12...00 11 22 33 44 55 ......Intel(R) Wi-Fi 6 AX201 160MHz===========================================================================
IPv4 Route Table===========================================================================Active Routes:Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.23 35 0.0.0.0 0.0.0.0 10.10.0.1 10.10.0.5 50===========================================================================Persistent Routes: Network Address Netmask Gateway Address Metric 0.0.0.0 0.0.0.0 192.168.1.1 Default==========================================================================="""
def test_parse_route_print_picks_lowest_metric(): assert cd.parse_route_print(ROUTE_PRINT) == ("192.168.1.1", "192.168.1.23") assert cd.parse_route_print("no routes here") is None
def test_parse_ip_route_get(): text = "8.8.8.8 via 192.168.1.1 dev wlp3s0 src 192.168.1.50 uid 1000 \\ cache \n" assert cd.parse_ip_route_get(text) == {"via": "192.168.1.1", "dev": "wlp3s0", "src": "192.168.1.50"} assert cd.parse_ip_route_get("default via 10.0.0.1 dev eth0 proto dhcp metric 100") == \ {"via": "10.0.0.1", "dev": "eth0"}
def test_parse_resolv_conf(): text = "# generated\nsearch lan\nnameserver 127.0.0.53 # stub\nnameserver 192.168.1.1\noptions edns0\n" assert cd.parse_resolv_conf(text) == ["127.0.0.53", "192.168.1.1"]
def test_parse_route_get_default_macos(): text = """ route to: defaultdestination: default mask: default gateway: 192.168.1.1 interface: en0 flags: <UP,GATEWAY,DONE,STATIC,PRCLONING,GLOBAL>""" assert cd.parse_route_get_default(text) == {"gateway": "192.168.1.1", "interface": "en0"}
def test_parse_hardware_ports(): text = """Hardware Port: Wi-FiDevice: en0Ethernet Address: 00:11:22:33:44:55
Hardware Port: Thunderbolt EthernetDevice: en5Ethernet Address: 66:77:88:99:aa:bb""" assert cd.parse_hardware_ports(text) == {"en0": "Wi-Fi", "en5": "Thunderbolt Ethernet"}
def test_link_type_from_media(): assert cd._link_type_from_media("Native 802.11") == "wifi" assert cd._link_type_from_media("802.3") == "ethernet" assert cd._link_type_from_media("Unspecified") == "unknown" assert cd._link_type_from_media("") == "unknown" assert cd._link_type_from_media("BlueTooth") == "other"
# --------------------------------------------------------------------------- ## DNS packets# --------------------------------------------------------------------------- #
def test_dns_query_roundtrip(): packet = cd.build_dns_query("example.com", qid=0x1234) qid, flags, qd, an, ns, ar = struct.unpack(">HHHHHH", packet[:12]) assert (qid, flags, qd, an, ns, ar) == (0x1234, 0x0100, 1, 0, 0, 0) assert packet[12:] == b"\x07example\x03com\x00" + struct.pack(">HH", 1, 1)
response = struct.pack(">HHHHHH", 0x1234, 0x8183, 1, 0, 0, 0) + packet[12:] assert cd.parse_dns_response(response, 0x1234) == 3 # NXDOMAIN other = struct.pack(">HHHHHH", 0x9999, 0x8180, 1, 0, 0, 0) assert cd.parse_dns_response(other, 0x1234) is None # wrong id assert cd.parse_dns_response(packet, 0x1234) is None # a query, not a response assert cd.parse_dns_response(b"\x00", 0x1234) is None
def test_random_label_is_hex(): label = cd.random_label() assert len(label) == 12 and int(label, 16) >= 0
# --------------------------------------------------------------------------- ## Wi-Fi parsers# --------------------------------------------------------------------------- #
NETSH_EN = """There is 1 interface on the system:
Name : Wi-Fi Description : Intel(R) Wi-Fi 6 AX201 160MHz GUID : 4d1a2b3c-0000-1111-2222-333344445555 Physical address : 00:11:22:33:44:55 Interface type : Primary State : connected SSID : Home:Net BSSID : aa:bb:cc:dd:ee:ff Network type : Infrastructure Radio type : 802.11ax Authentication : WPA2-Personal Cipher : CCMP Connection mode : Auto Connect Band : 5 GHz Channel : 36 Receive rate (Mbps) : 1200.9 Transmit rate (Mbps) : 1200.9 Signal : 84% Profile : Home:Net
Hosted network status : Not available"""
NETSH_ZH = """系统上有 1 个接口:
名称 : WLAN 描述 : Intel(R) Wi-Fi 6 AX201 160MHz GUID : 4d1a2b3c-0000-1111-2222-333344445555 物理地址 : 00:11:22:33:44:55 接口类型 : 主要 状态 : 已连接 SSID : 家里的WiFi BSSID : aa:bb:cc:dd:ee:ff 网络类型 : 结构 无线电类型 : 802.11ac 身份验证 : WPA2 - 个人 密码 : CCMP 连接模式 : 自动连接 信道 : 149 接收速率(Mbps) : 866.7 传输速率(Mbps) : 866.7 信号 : 91% 配置文件 : 家里的WiFi
承载网络状态 : 不可用"""
NETSH_DISCONNECTED = """There is 1 interface on the system:
Name : Wi-Fi Description : Intel(R) Wi-Fi 6 AX201 160MHz GUID : 4d1a2b3c-0000-1111-2222-333344445555 Physical address : 00:11:22:33:44:55 Interface type : Primary State : disconnected Radio status : Hardware On Software On
Hosted network status : Not available"""
def test_parse_netsh_english(): w = cd.parse_netsh_wlan(NETSH_EN) assert w.connected and w.ssid == "Home:Net" assert w.signal_pct == 84 and w.rssi_dbm == -58.0 assert w.rx_mbps == 1200.9 and w.tx_mbps == 1200.9 assert w.channel == 36 and w.band_ghz == 5.0 and w.phy == "802.11ax"
def test_parse_netsh_chinese_without_band_line(): w = cd.parse_netsh_wlan(NETSH_ZH) assert w.connected and w.ssid == "家里的WiFi" assert w.signal_pct == 91 and w.rssi_dbm == -54.5 assert w.rx_mbps == 866.7 and w.tx_mbps == 866.7 assert w.channel == 149 and w.band_ghz == 5.0 and w.phy == "802.11ac"
def test_parse_netsh_disconnected(): w = cd.parse_netsh_wlan(NETSH_DISCONNECTED) assert not w.connected and w.signal_pct is None
IW_LINK = """Connected to aa:bb:cc:dd:ee:ff (on wlp3s0)\tSSID: HomeNet\tfreq: 5180\tRX: 123456 bytes (789 packets)\tTX: 23456 bytes (234 packets)\tsignal: -55 dBm\trx bitrate: 866.7 MBit/s VHT-MCS 9 80MHz short GI VHT-NSS 2\ttx bitrate: 780.0 MBit/s VHT-MCS 8 80MHz short GI VHT-NSS 2
\tbss flags:\tshort-slot-time\tdtim period:\t1\tbeacon int:\t100"""
def test_parse_iw_link(): w = cd.parse_iw_link(IW_LINK) assert w.connected and w.ssid == "HomeNet" assert w.channel == 36 and w.band_ghz == 5.0 assert w.rssi_dbm == -55.0 and w.signal_pct == 90 assert w.rx_mbps == 866.7 and w.tx_mbps == 780.0 and w.phy == "802.11ac" assert not cd.parse_iw_link("Not connected.\n").connected 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") assert ht.phy == "802.11n" and ht.channel == 6 and ht.band_ghz == 2.4
def test_parse_proc_net_wireless(): text = ("Inter-| sta-| Quality | Discarded packets | Missed | WE\n" " face | tus | link level noise | nwid crypt frag retry misc | beacon | 22\n" " wlan0: 0000 60. -50. -256 0 0 0 0 0 0\n") w = cd.parse_proc_net_wireless(text, "wlan0") assert w.connected and w.rssi_dbm == -50.0 and w.signal_pct == 100 assert not cd.parse_proc_net_wireless(text, "wlan1").connected
def test_parse_system_profiler(): data = {"SPAirPortDataType": [{"spairport_airport_interfaces": [{ "_name": "en0", "spairport_current_network_information": { "_name": "HomeNet", "spairport_network_channel": "44 (5GHz, 80MHz)", "spairport_network_phymode": "802.11ax", "spairport_network_rate": 1200, "spairport_signal_noise": "-52 dBm / -92 dBm", }}]}]} w = cd.parse_system_profiler_airport(data) assert w.connected and w.ssid == "HomeNet" and w.channel == 44 and w.band_ghz == 5.0 assert w.phy == "802.11ax" and w.rx_mbps == 1200 and w.rssi_dbm == -52.0 assert not cd.parse_system_profiler_airport({}).connected
def test_channel_and_rssi_helpers(): assert cd.channel_from_freq_mhz(2412) == (1, 2.4) assert cd.channel_from_freq_mhz(2484) == (14, 2.4) assert cd.channel_from_freq_mhz(5745) == (149, 5.0) assert cd.channel_from_freq_mhz(5955) == (1, 6.0) assert cd.channel_from_freq_mhz(1000) == (None, None) assert cd.rssi_from_quality(100) == -50.0 and cd.rssi_from_quality(0) == -100.0 assert cd.quality_from_rssi(-75) == 50 and cd.quality_from_rssi(-120) == 0 assert cd.band_from_channel(11) == 2.4 and cd.band_from_channel(100) == 5.0
# --------------------------------------------------------------------------- ## throughput tool output# --------------------------------------------------------------------------- #
def test_parse_ookla_json(): data = {"type": "result", "ping": {"jitter": 0.6, "latency": 9.5}, "download": {"bandwidth": 58231421, "latency": {"iqm": 21.3}}, "upload": {"bandwidth": 2500000, "latency": {"iqm": 45.0}}, "server": {"id": 1234, "name": "Example ISP", "location": "Springfield"}} r = cd.parse_ookla_json(data) assert r["download_mbps"] == pytest.approx(465.85, abs=0.01) assert r["upload_mbps"] == 20.0 assert r["speedtest_ping_ms"] == 9.5 assert r["download_loaded_latency_ms"] == 21.3 and r["upload_loaded_latency_ms"] == 45.0 assert r["speedtest_server_id"] == 1234 and r["speedtest_server"] == "Example ISP, Springfield"
class _FakeResults: ping = 1800000.0 server = {"id": 42, "sponsor": "Example ISP", "name": "Springfield"}
class _FakeSpeedtest: def __init__(self, secure=True): self.results = _FakeResults()
def get_servers(self, ids): pass
def get_best_server(self): pass
def download(self): return 120e6
def upload(self, pre_allocate=False): return 20e6
def test_speedtest_cli_failed_latency_probe(monkeypatch): import sys import types module = types.ModuleType("speedtest") module.Speedtest = _FakeSpeedtest monkeypatch.setitem(sys.modules, "speedtest", module) monkeypatch.setattr(cd, "_ookla_cli_path", lambda: None) out = cd.run_speedtest() assert out["download_mbps"] == 120.0 and out["upload_mbps"] == 20.0 assert "speedtest_ping_ms" not in out assert out["error"] == "speedtest-cli: server latency probe failed" assert out["speedtest_server"] == "Example ISP, Springfield" _FakeResults.ping = 23.4 out = cd.run_speedtest() assert out["speedtest_ping_ms"] == 23.4 and "error" not in out
def test_iperf_json_parsing(monkeypatch): payload = {"end": {"sum_sent": {"bits_per_second": 9.4e8, "retransmits": 12}, "sum_received": {"bits_per_second": 9.38e8}}} monkeypatch.setattr(cd.shutil, "which", lambda name: "/usr/bin/iperf3") monkeypatch.setattr(cd, "run_cmd", lambda *a, **k: (0, json.dumps(payload))) assert cd.run_iperf3("10.0.0.2", 5201, 10, False) == {"lan_throughput_mbps": 938.0, "lan_retransmits": 12} monkeypatch.setattr(cd, "run_cmd", lambda *a, **k: (1, json.dumps({"error": "unable to connect"}))) assert "unable to connect" in cd.run_iperf3("10.0.0.2", 5201, 10, False)["error"]
# --------------------------------------------------------------------------- ## configuration helpers# --------------------------------------------------------------------------- #
def test_parse_duration(): assert cd.parse_duration("90") == 90 assert cd.parse_duration("30s") == 30 assert cd.parse_duration("1.5h") == 5400 assert cd.parse_duration("7d") == 7 * 86400 with pytest.raises(Exception): cd.parse_duration("1w")
def test_human_duration(): assert cd.human_duration(0) == "0s" assert cd.human_duration(90) == "1m 30s" assert cd.human_duration(7 * 86400 + 3600) == "7d 1h"
def test_sanitize_label(): assert cd.sanitize_label(" laptop wifi/5G ") == "laptop-wifi-5G" assert cd.sanitize_label("") == ""
def test_csv_fields_match_dataclass(): assert cd.CSV_FIELDS[0] == "run_id" and cd.CSV_FIELDS[-1] == "notes" assert len(cd.CSV_FIELDS) == len(set(cd.CSV_FIELDS)) for key in cd.SUMMARY_KEYS: assert key in cd.CSV_FIELDS.gitattributes+5
CITATION.cffAdded+30
LICENSEAdded+21
README.mdAdded+627
dataset/analysis.jsonAdded+1504
dataset/localnet_dynamics.csvAdded+3
dataset/localnet_dynamics.parquetAdded+3
dataset/raw/localnet_desktop-eth_20260920_123407.csvAdded+3
dataset/raw/localnet_desktop-eth_20260920_123407.jsonAdded+220
dataset/summary.jsonAdded+231
figures/pdf/autocorrelation.pdfAdded
figures/pdf/calendar_heatmaps.pdfAdded
figures/pdf/degradation_anatomy.pdfAdded
figures/pdf/diurnal_profile.pdfAdded
figures/pdf/labels.pdfAdded
figures/pdf/loss_anatomy.pdfAdded
figures/pdf/overview_timeline.pdfAdded+3
figures/pdf/regimes.pdfAdded+3
figures/pdf/speedtest.pdfAdded
figures/pdf/tcp_vs_icmp.pdfAdded+3
figures/png/autocorrelation.pngAdded

Large File Pointer Details
- SHA256: 6dd47cfce534e5ff3b0b7b01761c6f043360f8ecc47572b19d6554e0d390db86
- Pointer size: 131 Bytes
- Size of remote file: 211 kB
figures/png/calendar_heatmaps.pngAdded

Large File Pointer Details
- SHA256: 92cc676a687a7dfa27ab6f3c6fb865c95d8d659eeaf837be1eb31f63d1837893
- Pointer size: 131 Bytes
- Size of remote file: 189 kB
figures/png/degradation_anatomy.pngAdded

Large File Pointer Details
- SHA256: 56014082bd2e7e846c77d1eddde594ecf4b74b221df85f7fc0914d3c5184e2ea
- Pointer size: 131 Bytes
- Size of remote file: 587 kB
figures/png/diurnal_profile.pngAdded

Large File Pointer Details
- SHA256: bf1db4eb66f675ed4877aae327a1c64d4de95c4490b1384efe827787808f08b7
- Pointer size: 131 Bytes
- Size of remote file: 298 kB
figures/png/labels.pngAdded

Large File Pointer Details
- SHA256: 014b74bff202a9fb455c9edd224e792e4aef2235b328d7b3ad1d53a4da66266e
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
figures/png/loss_anatomy.pngAdded

Large File Pointer Details
- SHA256: 38c6fad5ce8dab57f01286842c439ce4f783a8b47d56e94d40c370759493ac34
- Pointer size: 131 Bytes
- Size of remote file: 296 kB
figures/png/overview_timeline.pngAdded

Large File Pointer Details
- SHA256: 24aeb40928878f418789f2ebae4ca23dfc14a600275298ce6663915e58ab68e7
- Pointer size: 131 Bytes
- Size of remote file: 744 kB
figures/png/regimes.pngAdded

Large File Pointer Details
- SHA256: 9c281d7612c41d6e49dda37860dd445148c31664086ab2e836f7151ebe9ffbb0
- Pointer size: 131 Bytes
- Size of remote file: 286 kB
figures/png/speedtest.pngAdded

Large File Pointer Details
- SHA256: f85e6929340bb305788c575b4a48f72d8404b1ed0ebac58b9940a855bb01cc19
- Pointer size: 131 Bytes
- Size of remote file: 520 kB
figures/png/tcp_vs_icmp.pngAdded

Large File Pointer Details
- SHA256: bedd58c76abb8df39b9f4186667a02ad3de6ee9c16a12cf99a4d9b6859a5ef1f
- Pointer size: 131 Bytes
- Size of remote file: 604 kB
requirements.txtAdded+9
scripts/analyze.pyAdded+557
scripts/annotate.pyAdded+108
scripts/build_dataset.pyAdded+429
scripts/collect_data.pyAdded+1583
scripts/package_huggingface.pyAdded+126
scripts/plot_figures.pyAdded+570
tests/conftest.pyAdded+6
tests/test_build.pyAdded+211
tests/test_collector.pyAdded+531