jitterbug-inference 2.3.0__tar.gz → 2.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/PKG-INFO +21 -4
  2. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/README.md +20 -3
  3. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/pyproject.toml +1 -1
  4. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/pyproject.toml.orig +1 -1
  5. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/cli/main.py +322 -0
  6. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/__init__.py +2 -0
  7. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/config.py +116 -1
  8. jitterbug_inference-2.4.0/src/jitterbug/streaming/__init__.py +53 -0
  9. jitterbug_inference-2.4.0/src/jitterbug/streaming/online_analyzer.py +356 -0
  10. jitterbug_inference-2.4.0/src/jitterbug/streaming/replay.py +159 -0
  11. jitterbug_inference-2.4.0/src/jitterbug/streaming/verdict.py +96 -0
  12. jitterbug_inference-2.4.0/src/jitterbug/streaming/window_backend.py +363 -0
  13. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/__init__.py +0 -0
  14. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/__init__.py +0 -0
  15. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/clustering_analyzer.py +0 -0
  16. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/congestion_inference_analyzer.py +0 -0
  17. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/jitter_analyzer.py +0 -0
  18. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analysis/latency_jump_analyzer.py +0 -0
  19. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/analyzer.py +0 -0
  20. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/cli/__init__.py +0 -0
  21. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/__init__.py +0 -0
  22. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/algorithms.py +0 -0
  23. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/detection/change_point_detector.py +0 -0
  24. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/__init__.py +0 -0
  25. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/compression.py +0 -0
  26. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/data_loader.py +0 -0
  27. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/io/exporters.py +0 -0
  28. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/analysis.py +0 -0
  29. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/models/rtt_data.py +0 -0
  30. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/py.typed +0 -0
  31. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/visualization/__init__.py +0 -0
  32. {jitterbug_inference-2.3.0 → jitterbug_inference-2.4.0}/src/jitterbug/visualization/plotter.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: jitterbug-inference
3
- Version: 2.3.0
3
+ Version: 2.4.0
4
4
  Summary: Framework for jitter-based network congestion inference
5
5
  Keywords: network,congestion,rtt,jitter,analysis,changepoint,detection
6
6
  Author: Esteban Carisimo
@@ -115,7 +115,7 @@ See [docs/INSTALLATION.md](https://github.com/estcarisimo/jitterbug/blob/main/do
115
115
 
116
116
  | Extra | Installs | Use it for |
117
117
  | --- | --- | --- |
118
- | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper |
118
+ | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper, and the online mode (`jitterbug stream` / `replay`) |
119
119
  | `clustering` | scikit-learn | The non-sequential mode (`--mode clustering`) |
120
120
  | `influx` | influxdb-client | Loading RTTs straight from InfluxDB |
121
121
  | `zstd` | zstandard (not needed on Python 3.14+) | Reading and writing `.zst`-compressed files |
@@ -176,6 +176,20 @@ jitterbug visualize examples/network_analysis/data/raw.csv --output-dir plots
176
176
 
177
177
  The figures are described in [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md), together with the `JitterbugPlotter` API for your own scripts.
178
178
 
179
+ ### Online mode: stream and replay
180
+
181
+ ```bash
182
+ # Infer congestion as samples arrive: `epoch,rtt` lines on stdin, one JSON event per line;
183
+ # needs `uv sync --extra bcp`
184
+ my-probe | jitterbug stream --events verdicts
185
+
186
+ # Replay a recorded dataset through the online pipeline and score it against a reference
187
+ jitterbug replay examples/network_analysis/data/raw.csv \
188
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv
189
+ ```
190
+
191
+ On the paper dataset congestion onsets are reported 15 min after they start (median; 90 min at most); see [docs/ONLINE_MODE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ONLINE_MODE.md) for the method, the results on the paper dataset and the `streaming` configuration section.
192
+
179
193
  ### Configuration files
180
194
 
181
195
  ```bash
@@ -325,8 +339,10 @@ src/jitterbug/
325
339
  │ ├── jitter_analyzer.py # jitter dispersion and KS test
326
340
  │ ├── congestion_inference_analyzer.py
327
341
  │ └── clustering_analyzer.py # non-sequential mode (GMM / k-means over intervals)
342
+ ├── streaming/ # Online mode: OnlineJitterbug (Bayesian online change points) and
343
+ │ # SlidingWindowJitterbug (offline pipeline on a window); replay/score
328
344
  ├── io/ # DataLoader (CSV, scamper JSON, InfluxDB) and exporters
329
- ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, version
345
+ ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, stream, replay, version
330
346
  └── visualization/ # JitterbugPlotter (matplotlib): the figures behind `jitterbug visualize`
331
347
  ```
332
348
 
@@ -444,6 +460,7 @@ Contributions are welcome! Please see the [Contributing Guide](https://github.co
444
460
  | [docs/ALGORITHM_SELECTION_GUIDE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_SELECTION_GUIDE.md) | Choosing a change point detector |
445
461
  | [docs/ALGORITHM_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_USAGE.md) | Per-detector options and examples |
446
462
  | [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md) | `jitterbug visualize`, the five figures, `JitterbugPlotter` |
463
+ | [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md) | Runtime across releases, and where the speedup comes from |
447
464
  | [examples/README.md](https://github.com/estcarisimo/jitterbug/blob/main/examples/README.md) | Scripts and notebooks |
448
465
 
449
466
  ## 📄 License
@@ -453,7 +470,7 @@ This project is licensed under the MIT License - see the [LICENSE](https://githu
453
470
  ## 🔗 Related Resources
454
471
 
455
472
  - [Jitterbug paper (PAM 2022)](https://doi.org/10.1007/978-3-030-98785-5_7)
456
- - [bayesian_changepoint_detection](https://github.com/estcarisimo/bayesian_changepoint_detection): the Bayesian detector behind the `bcp` extra
473
+ - [bayesian_changepoint_detection](https://github.com/hildensia/bayesian_changepoint_detection) ([docs](https://estcarisimo.github.io/bayesian_changepoint_detection/), PyPI [`bayesian-changepoint`](https://pypi.org/project/bayesian-changepoint/)): the Bayesian detector behind the `bcp` extra. Its 1.2 release made the paper's configuration about 6× faster than Jitterbug 1.0 and more accurate than the version Jitterbug used before; see [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md#what-changed-in-the-bayesian-library)
457
474
  - [ruptures](https://centre-borelli.github.io/ruptures-docs/): the default change point library
458
475
  - [scamper](https://www.caida.org/catalog/software/scamper/): the measurement tool whose JSON output Jitterbug reads
459
476
 
@@ -51,7 +51,7 @@ See [docs/INSTALLATION.md](https://github.com/estcarisimo/jitterbug/blob/main/do
51
51
 
52
52
  | Extra | Installs | Use it for |
53
53
  | --- | --- | --- |
54
- | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper |
54
+ | `bcp` | [bayesian-changepoint](https://pypi.org/project/bayesian-changepoint/) + torch | The Bayesian detector used in the paper, and the online mode (`jitterbug stream` / `replay`) |
55
55
  | `clustering` | scikit-learn | The non-sequential mode (`--mode clustering`) |
56
56
  | `influx` | influxdb-client | Loading RTTs straight from InfluxDB |
57
57
  | `zstd` | zstandard (not needed on Python 3.14+) | Reading and writing `.zst`-compressed files |
@@ -112,6 +112,20 @@ jitterbug visualize examples/network_analysis/data/raw.csv --output-dir plots
112
112
 
113
113
  The figures are described in [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md), together with the `JitterbugPlotter` API for your own scripts.
114
114
 
115
+ ### Online mode: stream and replay
116
+
117
+ ```bash
118
+ # Infer congestion as samples arrive: `epoch,rtt` lines on stdin, one JSON event per line;
119
+ # needs `uv sync --extra bcp`
120
+ my-probe | jitterbug stream --events verdicts
121
+
122
+ # Replay a recorded dataset through the online pipeline and score it against a reference
123
+ jitterbug replay examples/network_analysis/data/raw.csv \
124
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv
125
+ ```
126
+
127
+ On the paper dataset congestion onsets are reported 15 min after they start (median; 90 min at most); see [docs/ONLINE_MODE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ONLINE_MODE.md) for the method, the results on the paper dataset and the `streaming` configuration section.
128
+
115
129
  ### Configuration files
116
130
 
117
131
  ```bash
@@ -261,8 +275,10 @@ src/jitterbug/
261
275
  │ ├── jitter_analyzer.py # jitter dispersion and KS test
262
276
  │ ├── congestion_inference_analyzer.py
263
277
  │ └── clustering_analyzer.py # non-sequential mode (GMM / k-means over intervals)
278
+ ├── streaming/ # Online mode: OnlineJitterbug (Bayesian online change points) and
279
+ │ # SlidingWindowJitterbug (offline pipeline on a window); replay/score
264
280
  ├── io/ # DataLoader (CSV, scamper JSON, InfluxDB) and exporters
265
- ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, version
281
+ ├── cli/main.py # Typer CLI: analyze, validate, config, visualize, stream, replay, version
266
282
  └── visualization/ # JitterbugPlotter (matplotlib): the figures behind `jitterbug visualize`
267
283
  ```
268
284
 
@@ -380,6 +396,7 @@ Contributions are welcome! Please see the [Contributing Guide](https://github.co
380
396
  | [docs/ALGORITHM_SELECTION_GUIDE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_SELECTION_GUIDE.md) | Choosing a change point detector |
381
397
  | [docs/ALGORITHM_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/ALGORITHM_USAGE.md) | Per-detector options and examples |
382
398
  | [docs/VISUALIZATION_USAGE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/VISUALIZATION_USAGE.md) | `jitterbug visualize`, the five figures, `JitterbugPlotter` |
399
+ | [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md) | Runtime across releases, and where the speedup comes from |
383
400
  | [examples/README.md](https://github.com/estcarisimo/jitterbug/blob/main/examples/README.md) | Scripts and notebooks |
384
401
 
385
402
  ## 📄 License
@@ -389,7 +406,7 @@ This project is licensed under the MIT License - see the [LICENSE](https://githu
389
406
  ## 🔗 Related Resources
390
407
 
391
408
  - [Jitterbug paper (PAM 2022)](https://doi.org/10.1007/978-3-030-98785-5_7)
392
- - [bayesian_changepoint_detection](https://github.com/estcarisimo/bayesian_changepoint_detection): the Bayesian detector behind the `bcp` extra
409
+ - [bayesian_changepoint_detection](https://github.com/hildensia/bayesian_changepoint_detection) ([docs](https://estcarisimo.github.io/bayesian_changepoint_detection/), PyPI [`bayesian-changepoint`](https://pypi.org/project/bayesian-changepoint/)): the Bayesian detector behind the `bcp` extra. Its 1.2 release made the paper's configuration about 6× faster than Jitterbug 1.0 and more accurate than the version Jitterbug used before; see [docs/PERFORMANCE.md](https://github.com/estcarisimo/jitterbug/blob/main/docs/PERFORMANCE.md#what-changed-in-the-bayesian-library)
393
410
  - [ruptures](https://centre-borelli.github.io/ruptures-docs/): the default change point library
394
411
  - [scamper](https://www.caida.org/catalog/software/scamper/): the measurement tool whose JSON output Jitterbug reads
395
412
 
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "jitterbug-inference"
7
- version = "2.3.0"
7
+ version = "2.4.0"
8
8
  description = "Framework for jitter-based network congestion inference"
9
9
  readme = "README.md"
10
10
  keywords = [
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "jitterbug-inference"
7
- version = "2.3.0"
7
+ version = "2.4.0"
8
8
  description = "Framework for jitter-based network congestion inference"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -4,7 +4,10 @@ Main CLI application using Typer.
4
4
 
5
5
  import json
6
6
  import logging
7
+ import math
7
8
  import sys
9
+ import time
10
+ from collections.abc import Iterator
8
11
  from pathlib import Path
9
12
  from typing import Any
10
13
 
@@ -16,6 +19,7 @@ from rich.table import Table
16
19
 
17
20
  from ..analyzer import JitterbugAnalyzer
18
21
  from ..io import DataLoader
22
+ from ..io.compression import open_text
19
23
  from ..models import CongestionInferenceResult, JitterbugConfig
20
24
 
21
25
  # matplotlib is an optional dependency; the visualize command checks for it at run time.
@@ -27,6 +31,8 @@ except ImportError: # pragma: no cover - only if the package itself is broken
27
31
 
28
32
  # Initialize Rich console
29
33
  console = Console()
34
+ # `jitterbug stream` writes JSON lines to stdout, so its messages go to stderr.
35
+ err_console = Console(stderr=True)
30
36
 
31
37
 
32
38
  def _apply_overrides(
@@ -64,6 +70,33 @@ def _apply_overrides(
64
70
  return JitterbugConfig.model_validate(data)
65
71
 
66
72
 
73
+ def _apply_streaming_overrides(
74
+ base: JitterbugConfig,
75
+ *,
76
+ backend: str | None = None,
77
+ decision: str | None = None,
78
+ hazard_lambda: float | None = None,
79
+ min_period_samples: int | None = None,
80
+ min_time_elapsed: int | None = None,
81
+ verbose: bool = False,
82
+ ) -> JitterbugConfig:
83
+ """Return a copy of ``base`` with the online-mode flags that were actually given."""
84
+ data = base.model_dump()
85
+ if backend is not None:
86
+ data["streaming"]["backend"] = backend
87
+ if decision is not None:
88
+ data["streaming"]["decision"] = decision
89
+ if hazard_lambda is not None:
90
+ data["streaming"]["hazard_lambda"] = hazard_lambda
91
+ if min_period_samples is not None:
92
+ data["streaming"]["min_period_samples"] = min_period_samples
93
+ if min_time_elapsed is not None:
94
+ data["streaming"]["min_time_elapsed"] = min_time_elapsed
95
+ if verbose:
96
+ data["verbose"] = True
97
+ return JitterbugConfig.model_validate(data)
98
+
99
+
67
100
  # Create Typer app
68
101
  app = typer.Typer(
69
102
  name="jitterbug",
@@ -426,6 +459,295 @@ def visualize(
426
459
  raise typer.Exit(1) from None
427
460
 
428
461
 
462
+ def _iter_lines(source: Path | None, follow: bool) -> Iterator[str]:
463
+ """
464
+ Complete lines of ``source`` (stdin when None); with ``follow``, keep waiting for more.
465
+
466
+ A writer that is still appending may have flushed half a line; it is held back until
467
+ its newline arrives. Without ``follow`` a trailing unterminated line is yielded at EOF.
468
+ """
469
+ if source is None:
470
+ yield from sys.stdin
471
+ return
472
+ with open_text(source) as f:
473
+ partial = ""
474
+ while True:
475
+ chunk = f.readline()
476
+ if chunk:
477
+ partial += chunk
478
+ if partial.endswith("\n"):
479
+ yield partial
480
+ partial = ""
481
+ elif follow:
482
+ time.sleep(0.5)
483
+ else:
484
+ if partial:
485
+ yield partial
486
+ return
487
+
488
+
489
+ def _parse_sample(line: str) -> tuple[float, float] | None:
490
+ """``epoch,rtt`` (extra columns ignored) or None for blank, header and junk lines."""
491
+ parts = line.strip().split(",")
492
+ if len(parts) < 2:
493
+ return None
494
+ try:
495
+ epoch, rtt = float(parts[0]), float(parts[1])
496
+ except ValueError:
497
+ return None
498
+ if not (math.isfinite(epoch) and math.isfinite(rtt)):
499
+ return None
500
+ return epoch, rtt
501
+
502
+
503
+ @app.command()
504
+ def stream(
505
+ source: str = typer.Argument(
506
+ "-", help="File with one 'epoch,rtt' sample per line, or '-' for standard input"
507
+ ),
508
+ follow: bool = typer.Option(
509
+ False, "--follow", "-f", help="Keep reading the file as it grows (like tail -f)"
510
+ ),
511
+ output: Path | None = typer.Option(
512
+ None, "--output", "-o", help="Write events here as JSON lines instead of stdout"
513
+ ),
514
+ events: str = typer.Option(
515
+ "all", "--events", help="Which events to emit: all, verdicts, change-points"
516
+ ),
517
+ config: Path | None = typer.Option(
518
+ None, "--config", "-c", help="Configuration file (YAML or JSON)", exists=True
519
+ ),
520
+ backend: str | None = typer.Option(
521
+ None, "--backend", help="Online back end: bocpd (incremental) or window (offline rerun)"
522
+ ),
523
+ decision: str | None = typer.Option(
524
+ None, "--decision", help="Change point rule: map, lag, window (bocpd back end only)"
525
+ ),
526
+ hazard_lambda: float | None = typer.Option(
527
+ None, "--hazard-lambda", help="Expected run length in bins (bocpd back end only)"
528
+ ),
529
+ min_period_samples: int | None = typer.Option(
530
+ None, "--min-period-samples", help="Jitter samples before a provisional verdict"
531
+ ),
532
+ min_time_elapsed: int | None = typer.Option(
533
+ None,
534
+ "--min-time-elapsed",
535
+ help="Minimum seconds between change points (bocpd; the window back end uses "
536
+ "change_point_detection.min_time_elapsed)",
537
+ ),
538
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose logging"),
539
+ ) -> None:
540
+ """
541
+ Infer congestion online from a stream of RTT samples.
542
+
543
+ The default back end (bocpd) needs the bcp extra; --backend window reruns the offline
544
+ pipeline on a trailing window instead (its cadence and window come from the streaming
545
+ section of --config; --decision and --hazard-lambda do not apply to it).
546
+
547
+ Reads 'epoch,rtt' lines (seconds, milliseconds; a header line is skipped) and prints one
548
+ JSON object per event: change points, provisional verdicts and final verdicts. Samples
549
+ must arrive in time order; a sample older than the last one is dropped. The last bin is
550
+ closed when the input ends (or on Ctrl-C with --follow), as 'jitterbug replay' does.
551
+
552
+ [bold]Examples:[/bold]
553
+
554
+ • From a probe writing to standard output:
555
+ [cyan]my-probe | jitterbug stream[/cyan]
556
+
557
+ • Following a file that another process appends to:
558
+ [cyan]jitterbug stream rtts.csv --follow --events verdicts[/cyan]
559
+ """
560
+ logging.basicConfig(
561
+ level=logging.DEBUG if verbose else logging.WARNING,
562
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
563
+ stream=sys.stderr,
564
+ )
565
+ if events not in ("all", "verdicts", "change-points"):
566
+ err_console.print(
567
+ f"❌ Error: --events must be all, verdicts or change-points, not {events}"
568
+ )
569
+ raise typer.Exit(2)
570
+ if follow and source == "-":
571
+ err_console.print("--follow has no effect on standard input", style="yellow")
572
+ try:
573
+ from ..streaming import create_online_analyzer
574
+
575
+ jitterbug_config = JitterbugConfig.from_file(config) if config else JitterbugConfig()
576
+ jitterbug_config = _apply_streaming_overrides(
577
+ jitterbug_config,
578
+ backend=backend,
579
+ decision=decision,
580
+ hazard_lambda=hazard_lambda,
581
+ min_period_samples=min_period_samples,
582
+ min_time_elapsed=min_time_elapsed,
583
+ verbose=verbose,
584
+ )
585
+ online = create_online_analyzer(jitterbug_config)
586
+ path = None if source == "-" else Path(source)
587
+ if path is not None and not path.exists():
588
+ raise FileNotFoundError(f"Input file not found: {path}")
589
+ sink = output.open("w") if output else sys.stdout
590
+ n_samples = n_skipped = n_events = 0
591
+ wanted = {"all": None, "verdicts": "verdict", "change-points": "change_point"}[events]
592
+
593
+ def emit(batch: list[Any]) -> None:
594
+ nonlocal n_events
595
+ for event in batch:
596
+ if wanted is not None and event.kind != wanted:
597
+ continue
598
+ sink.write(json.dumps(event.to_dict()) + "\n")
599
+ sink.flush()
600
+ n_events += 1
601
+
602
+ try:
603
+ try:
604
+ for line in _iter_lines(path, follow):
605
+ sample = _parse_sample(line)
606
+ if sample is None:
607
+ n_skipped += bool(line.strip())
608
+ continue
609
+ n_samples += 1
610
+ emit(online.push(*sample))
611
+ except KeyboardInterrupt:
612
+ # Ctrl-C is how a --follow stream ends; close it like an EOF.
613
+ err_console.print("interrupted", style="yellow")
614
+ # The input ended (stdin EOF, a file without --follow, or Ctrl-C): close the
615
+ # open bin so the result matches `jitterbug replay` on the same data.
616
+ emit(online.flush())
617
+ finally:
618
+ if output:
619
+ sink.close()
620
+ err_console.print(
621
+ f"{n_samples} samples read, {n_skipped} lines skipped, {n_events} events emitted"
622
+ )
623
+ except Exception as e:
624
+ err_console.print(f"❌ Error: {e}", style="red")
625
+ raise typer.Exit(1) from None
626
+
627
+
628
+ @app.command()
629
+ def replay(
630
+ input_file: Path = typer.Argument(
631
+ ..., help="RTT data file to replay in time order", exists=True
632
+ ),
633
+ output: Path | None = typer.Option(
634
+ None, "--output", "-o", help="Write every event as a JSON array to this file"
635
+ ),
636
+ reference: Path | None = typer.Option(
637
+ None,
638
+ "--reference",
639
+ help="CSV with starts,ends,congestion columns to score the final verdicts against",
640
+ exists=True,
641
+ ),
642
+ format: str | None = typer.Option(
643
+ None, "--format", help="Input format (csv, json, scamper); inferred from the file"
644
+ ),
645
+ config: Path | None = typer.Option(
646
+ None, "--config", "-c", help="Configuration file (YAML or JSON)", exists=True
647
+ ),
648
+ backend: str | None = typer.Option(
649
+ None, "--backend", help="Online back end: bocpd (incremental) or window (offline rerun)"
650
+ ),
651
+ decision: str | None = typer.Option(
652
+ None, "--decision", help="Change point rule: map, lag, window (bocpd back end only)"
653
+ ),
654
+ hazard_lambda: float | None = typer.Option(
655
+ None, "--hazard-lambda", help="Expected run length in bins (bocpd back end only)"
656
+ ),
657
+ min_period_samples: int | None = typer.Option(
658
+ None, "--min-period-samples", help="Jitter samples before a provisional verdict"
659
+ ),
660
+ min_time_elapsed: int | None = typer.Option(
661
+ None,
662
+ "--min-time-elapsed",
663
+ help="Minimum seconds between change points (bocpd; the window back end uses "
664
+ "change_point_detection.min_time_elapsed)",
665
+ ),
666
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose logging"),
667
+ ) -> None:
668
+ """
669
+ Replay a recorded dataset through the online pipeline and summarize the result.
670
+
671
+ [bold]Examples:[/bold]
672
+
673
+ • Paper dataset against the paper's KS reference:
674
+ [cyan]jitterbug replay examples/network_analysis/data/raw.csv \\
675
+ --reference examples/network_analysis/expected_results/kstest_inferences.csv[/cyan]
676
+
677
+ • Keep every event:
678
+ [cyan]jitterbug replay rtts.csv --output events.json[/cyan]
679
+ """
680
+ logging.basicConfig(
681
+ level=logging.DEBUG if verbose else logging.WARNING,
682
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
683
+ stream=sys.stderr,
684
+ )
685
+ try:
686
+ from ..streaming import events_to_json, score
687
+ from ..streaming import replay as replay_dataset
688
+
689
+ jitterbug_config = JitterbugConfig.from_file(config) if config else JitterbugConfig()
690
+ jitterbug_config = _apply_streaming_overrides(
691
+ jitterbug_config,
692
+ backend=backend,
693
+ decision=decision,
694
+ hazard_lambda=hazard_lambda,
695
+ min_period_samples=min_period_samples,
696
+ min_time_elapsed=min_time_elapsed,
697
+ verbose=verbose,
698
+ )
699
+ with Progress(
700
+ SpinnerColumn(),
701
+ TextColumn("[progress.description]{task.description}"),
702
+ console=console,
703
+ transient=True,
704
+ ) as progress:
705
+ task = progress.add_task("Replaying...", total=None)
706
+ dataset = DataLoader().load_from_file(input_file, format)
707
+ events = replay_dataset(dataset, jitterbug_config)
708
+ progress.update(task, total=1, completed=1)
709
+ summary = score(events, reference)
710
+ if output:
711
+ events_to_json(events, output)
712
+
713
+ table = Table(title="Online replay", show_header=True, header_style="bold")
714
+ table.add_column("Metric")
715
+ table.add_column("Value", justify="right")
716
+ labels = {
717
+ "change_points": "Change points",
718
+ "periods": "Periods with a final verdict",
719
+ "congested": "Congested periods",
720
+ "onset_delay_min_median": "Onset delay, median (min)",
721
+ "onset_delay_min_max": "Onset delay, max (min)",
722
+ "return_delay_min_median": "Return delay, median (min)",
723
+ "return_delay_min_max": "Return delay, max (min)",
724
+ "provisional_flips": "Provisional verdicts that flipped",
725
+ "provisional_pairs": "Provisional/final pairs",
726
+ "provisional_lead_h_mean": "Provisional lead, mean (h)",
727
+ "recovered": "Reference congested periods recovered",
728
+ "reference_congested": "Reference congested periods",
729
+ "spurious": "Spurious congested periods",
730
+ "boundaries_within_30min": "Reference boundaries with a change point within 30 min",
731
+ "reference_boundaries": "Reference boundaries",
732
+ }
733
+ for key, label in labels.items():
734
+ if key in summary:
735
+ value = summary[key]
736
+ if value is None:
737
+ text = "-"
738
+ elif isinstance(value, float):
739
+ text = f"{value:.1f}"
740
+ else:
741
+ text = str(value)
742
+ table.add_row(label, text)
743
+ console.print(table)
744
+ if output:
745
+ console.print(f"\n✅ Events saved to [bold]{output}[/bold]")
746
+ except Exception as e:
747
+ console.print(f"❌ Error: {e}", style="red")
748
+ raise typer.Exit(1) from None
749
+
750
+
429
751
  @app.command()
430
752
  def version() -> None:
431
753
  """Show Jitterbug version information."""
@@ -16,6 +16,7 @@ from .config import (
16
16
  JitterAnalysisConfig,
17
17
  JitterbugConfig,
18
18
  LatencyJumpConfig,
19
+ StreamingConfig,
19
20
  )
20
21
  from .rtt_data import MAX_RTT_MS, MinimumRTTDataset, RTTDataset, RTTMeasurement
21
22
 
@@ -35,4 +36,5 @@ __all__ = [
35
36
  "LatencyJumpConfig",
36
37
  "DataProcessingConfig",
37
38
  "ClusteringConfig",
39
+ "StreamingConfig",
38
40
  ]
@@ -5,7 +5,7 @@ Configuration models using Pydantic for validation and serialization.
5
5
  from pathlib import Path
6
6
  from typing import Literal
7
7
 
8
- from pydantic import BaseModel, ConfigDict, Field, field_validator
8
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
9
9
  from pydantic_settings import BaseSettings, SettingsConfigDict
10
10
 
11
11
 
@@ -265,6 +265,118 @@ class ClusteringConfig(BaseModel):
265
265
  model_config = ConfigDict(validate_assignment=True)
266
266
 
267
267
 
268
+ class StreamingConfig(BaseModel):
269
+ """
270
+ Settings of the online (streaming) mode, ``jitterbug.streaming.OnlineJitterbug``.
271
+
272
+ The online mode reuses the sequential decision rule: minimum-RTT bins of
273
+ ``data_processing.minimum_interval_minutes``, the latency jump threshold of
274
+ ``latency_jump.threshold``, the significance level of
275
+ ``jitter_analysis.significance_level`` and the device of
276
+ ``change_point_detection.bcp_device``. The fields below are specific to the
277
+ Bayesian online change point detector and to the two-stage verdicts.
278
+
279
+ Attributes
280
+ ----------
281
+ backend : Literal['bocpd', 'window']
282
+ ``bocpd`` (default): incremental Bayesian online change point detection, one bin
283
+ at a time. ``window``: rerun the offline sequential pipeline on a trailing window
284
+ of ``window_hours`` every ``rerun_every_bins`` closed bins and emit a verdict once
285
+ it has been identical in ``stable_runs`` consecutive reruns. The baseline the
286
+ incremental detector is compared with; heavier per bin, no new algorithm.
287
+ window_hours : float
288
+ Length of the trailing window of the ``window`` back end, in hours.
289
+ rerun_every_bins : int
290
+ Closed bins between two reruns of the ``window`` back end.
291
+ stable_runs : int
292
+ Consecutive reruns in which a change point or a verdict must be identical before
293
+ the ``window`` back end emits it.
294
+ hazard_lambda : float
295
+ Expected run length in bins (constant hazard ``1 / hazard_lambda``).
296
+ decision : Literal['map', 'lag', 'window']
297
+ Change point rule. ``map`` (default) fires when the most probable run length
298
+ drops; ``lag`` thresholds the posterior that a segment started exactly ``lag`` bins
299
+ ago; ``window`` thresholds the posterior that it started within the last ``lag``
300
+ bins and places the change at the most probable run length.
301
+ lag : int
302
+ Decision delay in bins for the ``lag`` and ``window`` rules.
303
+ threshold : float
304
+ Posterior threshold for the ``lag`` and ``window`` rules.
305
+ max_run_length : int or None
306
+ Run lengths kept by the detector (bounds memory and time per bin); ``None`` keeps
307
+ the exact posterior.
308
+ min_time_elapsed : int
309
+ Minimum seconds between change points. The MAP rule refines a boundary a few
310
+ bins after first reporting it; one hour absorbs those refinements.
311
+ prior_alpha, prior_beta, prior_kappa : float
312
+ Normal-Gamma prior of the Student-t predictive (see ``online_likelihoods.StudentT``).
313
+ prior_mu : float or None
314
+ Prior mean; ``None`` uses the first minimum RTT seen.
315
+ min_ks_statistic : float
316
+ Smallest Kolmogorov-Smirnov statistic that counts as a jitter change (effect-size
317
+ guard, 0-1); ``0`` relies on the p-value only.
318
+ min_period_samples : int
319
+ Jitter samples the open period must hold before a provisional verdict. About
320
+ three 15-minute bins on the paper dataset; 30 gives noisy p-values.
321
+ """
322
+
323
+ backend: Literal["bocpd", "window"] = Field(
324
+ default="bocpd",
325
+ description="bocpd: incremental Bayesian detector; window: offline pipeline on a window",
326
+ )
327
+ window_hours: float = Field(default=72.0, gt=0, description="Trailing window (window backend)")
328
+ rerun_every_bins: int = Field(
329
+ default=1, ge=1, description="Closed bins between reruns (window backend)"
330
+ )
331
+ stable_runs: int = Field(
332
+ default=2, ge=1, description="Identical consecutive reruns before emitting (window backend)"
333
+ )
334
+ hazard_lambda: float = Field(
335
+ default=50.0, ge=1, description="Expected run length in bins (constant hazard)"
336
+ )
337
+ decision: Literal["map", "lag", "window"] = Field(
338
+ default="map", description="Change point rule: MAP run-length drop, fixed lag, or window"
339
+ )
340
+ lag: int = Field(default=4, ge=1, description="Decision delay in bins (lag and window rules)")
341
+ threshold: float = Field(
342
+ default=0.5, gt=0, le=1, description="Posterior threshold (lag and window rules)"
343
+ )
344
+ max_run_length: int | None = Field(
345
+ default=1000, ge=1, description="Run lengths kept; None keeps the exact posterior"
346
+ )
347
+ min_time_elapsed: int = Field(
348
+ default=3600, gt=0, description="Minimum seconds between change points"
349
+ )
350
+ prior_alpha: float = Field(default=0.1, gt=0, description="Gamma prior shape on precision")
351
+ prior_beta: float = Field(default=0.1, gt=0, description="Gamma prior rate on precision")
352
+ prior_kappa: float = Field(default=1.0, gt=0, description="Normal prior precision on mean")
353
+ prior_mu: float | None = Field(
354
+ default=None, description="Prior mean; None uses the first minimum RTT seen"
355
+ )
356
+ min_ks_statistic: float = Field(
357
+ default=0.0, ge=0, le=1, description="Smallest KS statistic that counts as a jitter change"
358
+ )
359
+ min_period_samples: int = Field(
360
+ default=100, ge=2, description="Jitter samples before a provisional verdict"
361
+ )
362
+
363
+ @model_validator(mode="after")
364
+ def _lag_fits_in_run_length(self) -> "StreamingConfig":
365
+ """``lag`` is only used by the fixed-delay rules, and must be a kept run length."""
366
+ if (
367
+ self.decision != "map"
368
+ and self.max_run_length is not None
369
+ and self.lag > self.max_run_length
370
+ ):
371
+ raise ValueError(
372
+ f"lag ({self.lag}) must not exceed max_run_length ({self.max_run_length}): "
373
+ "the detector cannot report a run length it does not keep"
374
+ )
375
+ return self
376
+
377
+ model_config = ConfigDict(validate_assignment=True)
378
+
379
+
268
380
  class JitterbugConfig(BaseSettings):
269
381
  """
270
382
  Main configuration class for Jitterbug.
@@ -286,6 +398,8 @@ class JitterbugConfig(BaseSettings):
286
398
  Configuration for data processing.
287
399
  clustering : ClusteringConfig
288
400
  Configuration for the clustering mode.
401
+ streaming : StreamingConfig
402
+ Configuration for the online (streaming) mode.
289
403
  output_format : Literal['json', 'csv', 'parquet']
290
404
  Output format for results.
291
405
  verbose : bool
@@ -302,6 +416,7 @@ class JitterbugConfig(BaseSettings):
302
416
  latency_jump: LatencyJumpConfig = Field(default_factory=LatencyJumpConfig)
303
417
  data_processing: DataProcessingConfig = Field(default_factory=DataProcessingConfig)
304
418
  clustering: ClusteringConfig = Field(default_factory=ClusteringConfig)
419
+ streaming: StreamingConfig = Field(default_factory=StreamingConfig)
305
420
 
306
421
  output_format: Literal["json", "csv", "parquet"] = Field(
307
422
  default="json", description="Output format for results"