Skip to content

Input and output

jitterbug.io.data_loader

Data loading: file, database and DataFrame entry points.

A file goes through a reader (jitterbug.io.readers, chosen by format) and a database query through a source (jitterbug.io.sources, chosen by kind); both return a raw DataFrame, which then goes through the normalizer (jitterbug.io.normalize) that applies the column mapping, units and row policies of InputConfig.

EPOCH_COLUMN = 'epoch' module-attribute

Default time column (InputConfig.time_column).

RTT_COLUMNS = RTT_COLUMN_SYNONYMS module-attribute

Accepted names for the RTT column when InputConfig.rtt_column is None.

SKIPPED_NO_VALID_ROWS = 'no valid RTT rows (every row was missing, non-positive or too large)' module-attribute

Reason recorded for a series whose rows the row policies all dropped.

DataLoader

Data loader for RTT data.

Supports loading from files (CSV, TSV, generic JSONL, scamper JSON, RIPE Atlas results, ping/fping output, optionally compressed, and Parquet/Arrow; see jitterbug.io.readers), database queries (ClickHouse, InfluxDB 2 and 3, DuckDB; see jitterbug.io.sources) and pandas DataFrames.

Parameters:

Name Type Description Default
input_config InputConfig | None

Column mapping, units and row policies; None uses the defaults.

None

load_from_file(file_path, file_format=None)

Load RTT data from a file.

Parameters:

Name Type Description Default
file_path Union[str, Path]

Path to the data file. A trailing .zst, .gz, .bz2 or .xz means the file is compressed (rtts.csv.gz) and does not count as the extension.

required
file_format Optional[str]

A registered format (jitterbug.io.readers.available_formats(): parquet, arrow, ping, fping, csv, tsv, atlas, json, scamper, jsonl). If None, it is inferred from the extension, then from the magic bytes of a binary format, then from the first non-empty line.

None

Returns:

Type Description
RTTDataset

Loaded RTT dataset; metadata records the source, the file path, the format and what normalization did. Rows not matching input.series are left out; with input.group_by, the rows must form a single series.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the format is unknown, the content does not satisfy the input contract, a series filter matches nothing, or group_by finds several series (the message lists them; use :meth:load_series).

ImportError

If the file is compressed with a codec that is not installed.

read_raw(file_path, file_format=None, apply_series_filter=True)

Read a file into raw rows, without normalizing them; series filters applied.

This is the first half of :meth:load_from_file, shared with :meth:load_series and jitterbug inspect.

Parameters:

Name Type Description Default
file_path str | Path

Path to the data file (possibly compressed).

required
file_format str | None

A registered format, or None to infer it.

None
apply_series_filter bool

Whether to keep only the rows matching input.series.

True

Returns:

Type Description
tuple[Reader, RawData, InputConfig]

The reader used; its raw data, with frame reduced to the rows matching series; and the input settings in effect for the file (this loader's, with the fields the format fixes, as for scamper).

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the format is unknown, the file cannot be read, or a series filter names a missing column or matches no row.

ImportError

If the file is compressed with a codec that is not installed, or is Parquet or Arrow and pyarrow is not installed.

load_series(file_path, file_format=None, skipped=None)

Load a file as one dataset per series (InputConfig.group_by).

The series filters are applied first; the rows are then split by the group_by columns and each series is normalized on its own, so duplicates, sorting and drops are handled per series. time_unit: auto is inferred once, on all the rows, so every series is read in the same unit. Without group_by the result has one entry, under the key ().

Parameters:

Name Type Description Default
file_path str | Path

Path to the data file (possibly compressed).

required
file_format str | None

A registered format, or None to infer it.

None
skipped dict[SeriesKey, str] | None

If given, receives the series left out because the row policies dropped every one of their rows, with the reason. They are logged either way.

None

Returns:

Type Description
dict[SeriesKey, RTTDataset]

Datasets in order of first appearance in the file. Each dataset's metadata["series_key"] is its key as a {name: value} mapping.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

As :meth:load_from_file, except that several series are expected; a row policy set to error that one series violates fails the whole file.

ImportError

If the file is compressed with a codec that is not installed.

load_from_dataframe(df)

Load RTT data from a pandas DataFrame.

The frame is mapped through this loader's InputConfig (see docs/INPUT_FORMATS.md); with the defaults: an epoch column with Unix seconds (UTC) and one RTT column named values, rtt_value, rtt or latency holding milliseconds; source and destination are optional. Rows not matching input.series are left out first. Validation happens once, on the whole frame (jitterbug.io.normalize):

  • a missing column or a value that cannot be read in its unit raises ValueError;
  • rows with a missing time or RTT are dropped; non-positive RTTs and RTTs above MAX_RTT_MS are dropped (or rejected with out_of_range: error); drops are counted in metadata["dropped_rows"];
  • rows are sorted by time (stable) if they are not already (or rejected with unsorted: error); rows sharing a timestamp are handled by duplicates (kept by default).

Parameters:

Name Type Description Default
df DataFrame

DataFrame containing RTT data.

required

Returns:

Type Description
RTTDataset

Loaded RTT dataset.

Raises:

Type Description
ValueError

If a required column is missing, a value cannot be read, a policy set to error is violated, no valid rows remain, a series filter matches nothing, or group_by finds several series (use :meth:load_series_from_dataframe).

load_series_from_dataframe(df, skipped=None)

Load a DataFrame as one dataset per series; see :meth:load_series.

Parameters:

Name Type Description Default
df DataFrame

Raw rows, mapped through this loader's InputConfig.

required
skipped dict[SeriesKey, str] | None

If given, receives the series whose rows were all dropped, with the reason.

None

Returns:

Type Description
dict[SeriesKey, RTTDataset]

Datasets in order of first appearance.

Raises:

Type Description
ValueError

As :meth:load_from_dataframe, except that several series are expected.

read_raw_source(source, apply_series_filter=True)

Run the query of a database source into raw rows, without normalizing them.

The counterpart of :meth:read_raw for databases, shared with :meth:load_from_source, :meth:load_series_from_source and jitterbug inspect.

Parameters:

Name Type Description Default
source SourceConfig

Back end, connection settings (no secrets) and query.

required
apply_series_filter bool

Whether to keep only the rows matching input.series.

True

Returns:

Type Description
tuple[RawData, InputConfig]

The result rows (metadata records source, source_details and query) and the input settings in effect (this loader's, with the column names and time unit the result decides: _time/_value for Flux, time for InfluxDB 3, iso for a datetime time column).

Raises:

Type Description
ValueError

If there is no query, or a series filter names a missing column or matches no row.

ImportError

If the back end's client library is not installed.

SourceError

If the connection or the query fails (the message is redacted).

load_from_source(source)

Load RTT data from a database query.

The result rows are mapped like a file's: input column mapping, units, row policies, series filters; with group_by, they must form a single series. Credentials come from environment variables (SourceConfig.secret_env).

Parameters:

Name Type Description Default
source SourceConfig

Back end, connection settings and query.

required

Returns:

Type Description
RTTDataset

Loaded dataset; metadata records source (the kind), source_details (host, port, database, ... never a secret) and query.

Raises:

Type Description
ValueError

As :meth:load_from_file.

ImportError

If the back end's client library is not installed.

SourceError

If the connection or the query fails (the message is redacted).

load_series_from_source(source, skipped=None)

Load a database query as one dataset per series; see :meth:load_series.

Parameters:

Name Type Description Default
source SourceConfig

Back end, connection settings and query.

required
skipped dict[SeriesKey, str] | None

If given, receives the series whose rows were all dropped, with the reason.

None

Returns:

Type Description
dict[SeriesKey, RTTDataset]

Datasets in order of first appearance in the result.

Raises:

Type Description
ValueError

As :meth:load_series.

ImportError

If the back end's client library is not installed.

SourceError

If the connection or the query fails (the message is redacted).

load_from_influxdb(url, token, org, bucket, query)

Load RTT data directly from InfluxDB 2 with a Flux query.

Kept for existing callers; :meth:load_from_source with an influxdb2 SourceConfig does the same and reads the token from the environment. The Flux columns _time and _value are used unless input maps others.

Parameters:

Name Type Description Default
url str

InfluxDB URL.

required
token str

InfluxDB token.

required
org str

InfluxDB organization.

required
bucket str

InfluxDB bucket (unused: the Flux query names it).

required
query str

Flux query to execute.

required

Returns:

Type Description
RTTDataset

Loaded RTT dataset.

Raises:

Type Description
ValueError

If the result has no RTT column, or as :meth:load_from_file.

ImportError

If influxdb-client is not installed.

SourceError

If the connection or the query fails (the message is redacted).

validate_data(dataset)

Validate RTT dataset and return quality metrics.

Parameters:

Name Type Description Default
dataset RTTDataset

Dataset to validate.

required

Returns:

Type Description
Dict[str, any]

Validation results and quality metrics.

jitterbug.io.normalize

The single normalization path from raw rows to an RTTDataset.

Every reader (CSV, TSV, JSONL, scamper, ...) and DataLoader.load_from_dataframe end here, so the input contract is enforced in one place. The steps, in order:

  1. Mapping. Find the time and RTT columns named by InputConfig (the RTT column falls back to the synonyms values, rtt_value, rtt, latency).
  2. Units. Convert times to Unix seconds (from s, ms, us, ns, ISO 8601 strings, or a unit inferred by auto) and RTTs to milliseconds. A value that cannot be read in the given unit is an error.
  3. Row policies. Drop rows with a missing time or RTT; drop (or reject) RTTs outside (0, MAX_RTT_MS]; sort (or reject) rows out of time order; keep, thin out or reject rows that share a timestamp. Nothing is imputed or resampled.

Selecting series (InputConfig.series and group_by) happens before, on the raw rows (jitterbug.io.series), so these steps apply to each series on its own. When neither is set and the rows hold several paths (distinct (source, destination) pairs, or the combinations of a format's path_keys), a warning says so.

TIME_UNIT_DIVISORS = {'s': 1.0, 'ms': 1000.0, 'us': 1000000.0, 'ns': 1000000000.0} module-attribute

Divide a numeric time in this unit by the value to get Unix seconds.

RTT_UNIT_SCALES = {'ms': (1.0, 1.0), 's': (1000.0, 1.0), 'us': (1.0, 1000.0), 'ns': (1.0, 1000000.0)} module-attribute

(multiplier, divisor) that turn an RTT in this unit into milliseconds. Dividing, rather than multiplying by a fraction, keeps e.g. 1500 us at exactly 1.5 ms.

AUTO_TIME_UNIT_LIMITS = ((100000000000.0, 's'), (100000000000000.0, 'ms'), (1e+17, 'us')) module-attribute

time_unit: auto picks the first unit whose limit exceeds the median absolute time: Unix seconds stay below 1e11 until the year 5138, milliseconds since 1973 are above it, and each finer unit is 1000 times larger. Anything at or above 1e17 is nanoseconds.

EPOCH_RANGE = (datetime(1, 1, 2, tzinfo=UTC).timestamp(), datetime(9999, 12, 30, tzinfo=UTC).timestamp()) module-attribute

Unix seconds a timestamp can hold (datetime years 1 to 9999, a day of margin on each side for local-time conversions).

NoValidRowsError

Bases: ValueError

Every row was dropped by the row policies (missing, non-positive or too large RTTs). A ValueError, so callers that catch that keep working; per-series loading uses it to skip one series instead of failing the whole input.

normalize(df, config=None, path_keys=())

Turn a raw frame into a validated, time-ordered RTTDataset.

Parameters:

Name Type Description Default
df DataFrame

Raw rows, one RTT sample each, with column names as in the input.

required
config InputConfig | None

Column mapping, units and row policies; None uses the defaults (epoch in seconds, RTT in milliseconds, duplicates kept, out-of-range RTTs dropped, unsorted rows sorted).

None
path_keys Sequence[str]

Key names that tell the input's paths apart (RawData.path_keys); empty means source and destination. Several distinct combinations, without group_by or series, log a warning that suggests grouping by them.

()

Returns:

Type Description
RTTDataset

The samples, with metadata describing what was done: original_columns, rtt_column, time_column, time_unit (the unit used, inferred or not), time_unit_inferred, rtt_unit, total_rows, dropped_rows (counts by reason), sorted_on_load, duplicate_rows (rows sharing a timestamp with an earlier one), duplicates_removed and source_destination_pairs (distinct (source, destination) pairs among the kept rows).

Raises:

Type Description
ValueError

If a column is missing, a value cannot be read in its unit, a policy set to error is violated, or no valid rows remain.

resolve_rtt_column(df, config)

Return the name of the RTT column of df under config.

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
config InputConfig

rtt_column if set, otherwise the first synonym present.

required

Returns:

Type Description
str

Column name.

Raises:

Type Description
ValueError

If the configured column, or every synonym, is missing.

epoch_seconds(column, time_unit, name)

Convert a time column to Unix seconds (floats, NaN where missing).

Parameters:

Name Type Description Default
column Series

Raw time values.

required
time_unit str

One of InputConfig.time_unit's values.

required
name str

Column name, for messages.

required

Returns:

Type Description
tuple[Series, str]

Seconds since the epoch, and the unit that was applied (the inferred one for auto).

Raises:

Type Description
ValueError

If a value cannot be read in the unit.

infer_time_unit(column, name)

Guess the unit of a time column (time_unit: auto).

Datetime values, and strings that are not numbers, are iso. Numbers are judged by the median absolute value against AUTO_TIME_UNIT_LIMITS. The choice is logged at INFO level.

Parameters:

Name Type Description Default
column Series

Raw time values.

required
name str

Column name, for the log message.

required

Returns:

Type Description
str

s, ms, us, ns or iso.

datetimes_to_epoch(times)

Seconds since the Unix epoch for tz-aware UTC datetimes, whatever their resolution.

Rounded to microseconds like pd.Timestamp.timestamp(): a float64 epoch cannot hold nanoseconds. NaT becomes NaN.

Parameters:

Name Type Description Default
times Series

datetime64[*, UTC] values.

required

Returns:

Type Description
Series

Float seconds.

numeric_column(column, name, hint='')

Return column as floats; NaN and blank strings become NaN.

Parameters:

Name Type Description Default
column Series

Raw values.

required
name str

Column name, for messages.

required
hint str

Appended to the error message.

''

Returns:

Type Description
Series

Float values.

Raises:

Type Description
ValueError

If any other value is not numeric.

jitterbug.io.series

Series selection on raw rows: the series filters and group_by keys of InputConfig.

Both work on the raw frame a reader returns, before normalization, so that the row policies (duplicates, sorting) apply to each series on its own. A name in group_by or series is resolved by :func:resolve_key_column: source and destination stand for the mapped source_column and destination_column; any other name is a raw column. Values are compared as text (:func:key_values).

SeriesKey = tuple[tuple[str, str | None], ...] module-attribute

Identifies one series: (name, value) pairs in group_by order, e.g. (("destination", "8.8.8.8"),). A missing value is None. The empty tuple is the whole input (no group_by).

MAX_LISTED_VALUES = 20 module-attribute

Error messages list at most this many available values or keys.

resolve_key_column(name, config)

Return the raw column a group_by or series name refers to.

Parameters:

Name Type Description Default
name str

source, destination or a raw column name.

required
config InputConfig

Supplies source_column and destination_column.

required

Returns:

Type Description
str

The column name in the raw frame.

key_values(df, name, config)

Return the values of a key column as text (None where missing).

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
name str

source, destination or a raw column name.

required
config InputConfig

Column mapping.

required

Returns:

Type Description
Series

Object series aligned with df.

Raises:

Type Description
ValueError

If the column does not exist.

format_series_key(key)

Render a series key as name=value pairs, the syntax of --series.

Parameters:

Name Type Description Default
key SeriesKey

The key.

required

Returns:

Type Description
str

E.g. "destination=8.8.8.8,source=10.0.0.1"; "(all rows)" for the empty key; a missing value is written <missing>.

series_key_dict(key)

Return a series key as a {name: value} mapping (the form written to JSON).

Parameters:

Name Type Description Default
key SeriesKey

The key.

required

Returns:

Type Description
dict[str, str | None]

Names in group_by order.

filter_rows(df, config)

Keep the rows that match every config.series filter.

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
config InputConfig

series filters and the column mapping.

required

Returns:

Type Description
DataFrame

The matching rows (df itself when there is no filter).

Raises:

Type Description
ValueError

If a filter names a column that does not exist, or no row matches; the message lists the values the column does have among the rows the earlier filters kept.

split_series(df, config)

Split raw rows by config.group_by.

Parameters:

Name Type Description Default
df DataFrame

Raw rows (already filtered by :func:filter_rows).

required
config InputConfig

group_by names and the column mapping.

required

Returns:

Type Description
dict[SeriesKey, DataFrame]

One frame per distinct key, in order of first appearance; rows keep their file order. Without group_by, the single key () maps to df.

Raises:

Type Description
ValueError

If a group_by column does not exist.

describe_keys(keys)

List series keys for an error or log message.

Parameters:

Name Type Description Default
keys list[SeriesKey]

Keys.

required

Returns:

Type Description
str

name=value keys separated by ;, truncated to MAX_LISTED_VALUES.

count_source_destination_pairs(df, config)

Count the distinct (source, destination) pairs of raw rows.

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
config InputConfig

Column mapping; an absent source or destination column counts as one value.

required

Returns:

Type Description
int

Number of distinct pairs (0 for an empty frame).

path_key_names(df, config, path_keys=())

Return the key names that tell the paths of raw rows apart.

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
config InputConfig

Column mapping, for source and destination.

required
path_keys Sequence[str]

Names a format declares for its paths (RawData.path_keys, e.g. prb_id, msm_id and destination for RIPE Atlas); empty means source and destination.

()

Returns:

Type Description
list[str]

The names among those whose column is present, usable as group_by.

count_paths(df, config, names)

Count the distinct combinations of the names key columns among raw rows.

Parameters:

Name Type Description Default
df DataFrame

Raw rows.

required
config InputConfig

Column mapping, for source and destination.

required
names Sequence[str]

Key names whose columns are present (see :func:path_key_names).

required

Returns:

Type Description
int

Number of distinct combinations (0 for an empty frame, 1 without names).

series_flags(names)

Return the --series flags that keep one path, one per key name.

Parameters:

Name Type Description Default
names Sequence[str]

Key names (see :func:path_key_names).

required

Returns:

Type Description
str

--series NAME=VALUE for each name, separated by spaces (--series destination=VALUE without names).

jitterbug.io.inspection

A dry run of ingestion: what loading a file or a database query would do, without analyzing anything.

:func:inspect_file reads a file with the same reader, column mapping, units and row policies as :meth:jitterbug.io.DataLoader.load_from_file, but instead of building a dataset it reports the format, the mapping in effect, how many rows each policy would drop or reorder, and the series the file holds. It never raises for a policy set to error: it says the load would fail and why. :func:inspect_source does the same for a database query. jitterbug inspect prints these reports.

inspect_file(file_path, file_format=None, input_config=None)

Report what loading file_path would do, without analyzing it.

Parameters:

Name Type Description Default
file_path str | Path

Input file (possibly compressed).

required
file_format str | None

A registered format, or None to infer it as the loader does.

None
input_config InputConfig | None

Mapping, units, row policies, series and group_by; None uses the defaults.

None

Returns:

Type Description
dict[str, Any]

JSON-serializable report with the keys:

  • file, format, format_detail (e.g. scamper_warts), compression (codec or None), reader (reader metadata such as the delimiter and invalid JSON lines), columns (raw column names);
  • mapping: the columns and units in effect, time_unit_applied (what auto inferred), fixed_by_format (settings the format imposes);
  • rows: read, selected (after series filters), missing, non_positive, too_large, valid;
  • policies: per policy, its setting, the rows concerned and the effect (dropped, sorted, kept or error), counted per series as the loader applies them;
  • series_by: the key names the series list is split by (group_by, or, when group_by is empty, the format's path keys present: source and destination, or e.g. prb_id, msm_id, destination for RIPE Atlas); grouped: whether the analysis would separate them;
  • series: per series, its key, rows, samples (after the policies), start/end (ISO 8601, UTC), duration_seconds, median_interval_seconds and max_gap_seconds (between distinct timestamps), duplicate_timestamps and out_of_order_rows;
  • errors: why loading would fail (a missing column, an unreadable value, a policy set to error); empty when it would succeed.

When a series filter, the mapping or a group_by column fails, the report stops after columns with the reason in errors.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

ValueError

If the format is unknown or the file cannot be read at all.

inspect_source(source, input_config=None)

Report what loading a database query would do, without analyzing it.

The query runs (it is the only way to see its columns), then the rows are examined as :func:inspect_file examines a file's.

Parameters:

Name Type Description Default
source SourceConfig

Back end, connection settings and query.

required
input_config InputConfig | None

Mapping, units, row policies, series and group_by.

None

Returns:

Type Description
dict[str, Any]

The keys of :func:inspect_file, with source (kind and connection details, never a secret) and query (the text run) in place of file, format, format_detail, compression and reader.

Raises:

Type Description
ValueError

If there is no query.

ImportError

If the back end's client library is not installed.

SourceError

If the connection or the query fails (the message is redacted).

jitterbug.io.readers.base

The reader registry: one small reader per file format.

A reader turns a file into a raw pandas.DataFrame and nothing more; column mapping, units and row policies are applied afterwards by :func:jitterbug.io.normalize.normalize. Adding a format is one module that calls :func:register_reader.

MAGIC_SIZE = 8 module-attribute

Bytes read from the start of a file to match Reader.magic.

RawData dataclass

What a reader returns.

Attributes:

Name Type Description
frame DataFrame

Raw rows, column names as in the file.

metadata dict[str, Any]

Merged into the dataset metadata after normalization (source, format, delimiter, ...).

schema dict[str, Any]

InputConfig fields the reader fixes because the format defines them (scamper writes epoch seconds and rtt milliseconds); they replace the user's values for this file. Row policies are never fixed.

finish Callable[[RTTDataset], None] | None

Called on the normalized dataset, e.g. to add format-specific metadata.

path_keys list[str]

Key names (as in InputConfig.group_by) that tell the format's paths apart, for the warning about mixed input and jitterbug inspect; empty means source and destination.

Reader dataclass

A registered file format.

Attributes:

Name Type Description
name str

Format name, as passed to --format / file_format.

label str

Human-readable name for messages ("CSV").

read ReadFunction

read(path, input_config) -> RawData. Raises ValueError for unreadable content; lets ImportError (a missing codec) through.

extensions tuple[str, ...]

Lower-case suffixes that select this format ((".csv",)); a compression suffix after them is ignored.

sniff SniffFunction | None

Given the first non-empty line of a file with an unknown extension, whether it looks like this format. Readers are tried in registration order.

magic tuple[bytes, ...]

Byte prefixes that identify a binary format ((b"PAR1",)). A file whose content starts with one of them is this format whatever its extension, and is never decoded as text to sniff it.

register_reader(reader)

Add reader to the registry.

Parameters:

Name Type Description Default
reader Reader

The format to register.

required

Returns:

Type Description
Reader

reader, unchanged.

Raises:

Type Description
ValueError

If the name or one of the extensions is already registered.

available_formats()

Return the registered format names, in registration order.

Returns:

Type Description
list[str]

E.g. ["json", "scamper", "jsonl", "tsv", "csv"].

get_reader(name)

Return the reader registered as name.

Parameters:

Name Type Description Default
name str

Format name.

required

Returns:

Type Description
Reader

The reader.

Raises:

Type Description
ValueError

If no reader has that name.

first_line(path, max_lines=100)

Return the first non-empty line of a (possibly compressed) text file, stripped.

Parameters:

Name Type Description Default
path Path

File path.

required
max_lines int

Give up after this many blank lines.

100

Returns:

Type Description
str

The line, or "" if there is none.

infer_format(path)

Pick the format of path: by extension (ignoring a compression suffix), otherwise by the magic bytes of a binary format, otherwise by sniffing its first non-empty line.

Parameters:

Name Type Description Default
path str | Path

File path.

required

Returns:

Type Description
str

A registered format name.

Raises:

Type Description
ValueError

If the file cannot be read as text or no reader recognizes it.

ImportError

If the file is compressed with a codec that is not installed.

magic_format(path)

Return the binary format whose magic bytes start the content of path.

The raw bytes are checked first; for a compressed file, the decompressed ones too, so that data.gz holding Parquet is recognized (its reader then rejects the outer compression) instead of being decoded as text.

Parameters:

Name Type Description Default
path Path

File path.

required

Returns:

Type Description
str | None

A registered format name, or None if no reader's magic matches.

Raises:

Type Description
ImportError

If the file is compressed with a codec that is not installed.

jitterbug.io.sources.base

The source registry: one small module per database back end.

A back end runs a query and returns a raw pandas.DataFrame, nothing more, like a file reader. :func:fetch_raw wraps it: it reads the secret from the environment, runs the query, redacts any error, reads datetime columns as datetimes, applies the back end's default column names, and returns :class:~jitterbug.io.readers.RawData that then goes through the same series selection and normalization as a file.

QuerySource dataclass

A registered database back end.

Attributes:

Name Type Description
kind str

SourceConfig.kind value.

label str

Human-readable name for messages ("ClickHouse").

fetch FetchFunction

fetch(source, query, secret) -> DataFrame. Imports its client lazily (raising an ImportError that names the extra), closes the connection, and may raise anything else: :func:fetch_raw redacts it.

time_column str | None

Name the back end gives the sample time (_time for Flux, time for InfluxDB 3); used when input.time_column is the default epoch and the result has no such column.

rtt_column str | None

Column used as the RTT when input.rtt_column is unset and present (_value for Flux), before the usual synonyms.

path_keys tuple[str, ...]

Key names that tell paths apart in the back end's results (RawData.path_keys).

register_source(source)

Add a back end to the registry.

Parameters:

Name Type Description Default
source QuerySource

The back end.

required

Returns:

Type Description
QuerySource

source, unchanged.

Raises:

Type Description
ValueError

If the kind is already registered.

available_sources()

Return the registered source kinds.

Returns:

Type Description
list[str]

E.g. ["clickhouse", "influxdb2", "influxdb3", "duckdb"].

get_source(kind)

Return the back end registered as kind.

Parameters:

Name Type Description Default
kind str

Source kind.

required

Returns:

Type Description
QuerySource

The back end.

Raises:

Type Description
ValueError

If no back end has that kind.

import_client(module, extra, package)

Import a client library, or raise an ImportError naming the extra to install.

Parameters:

Name Type Description Default
module str

Import name (clickhouse_connect).

required
extra str

The jitterbug-inference extra that installs it.

required
package str

Its PyPI distribution, for the message.

required

Returns:

Type Description
ModuleType

The module.

Raises:

Type Description
ImportError

If it is not installed.

query_text(source)

The query to run: source.query, or the content of source.query_file.

Parameters:

Name Type Description Default
source SourceConfig

The source.

required

Returns:

Type Description
str

Query text, stripped.

Raises:

Type Description
ValueError

If neither is set, the query is empty, or the file cannot be read.

describe_source(source)

Connection details of source safe to record and display (never a secret).

Parameters:

Name Type Description Default
source SourceConfig

The source.

required

Returns:

Type Description
dict[str, Any]

kind plus the settings that apply to it and are set: host, port, secure, database, org, language or path, and query_file.

fetch_raw(source, config)

Run the query of source and return its rows as raw data.

Parameters:

Name Type Description Default
source SourceConfig

Back end, connection settings and query.

required
config InputConfig

Input settings: the default column names of the back end apply only where these are left at their defaults, and a datetime time column is read as datetimes.

required

Returns:

Type Description
RawData

frame with the result rows; metadata with source (the kind), source_details (:func:describe_source) and query; schema with the InputConfig fields the result decides (time column, time_unit: iso for datetime columns, the RTT column of a Flux result).

Raises:

Type Description
ValueError

If there is no query or it cannot be read.

ImportError

If the back end's client library is not installed.

SourceError

If the connection or the query fails; the message is redacted.

run_redacted(label, call, secrets)

Run a client call; any error but a missing library becomes a redacted SourceError.

Parameters:

Name Type Description Default
label str

Back end name for the message ("ClickHouse").

required
call Callable[[], DataFrame]

Connects, queries and closes.

required
secrets list[str | None]

Values to scrub from the message, besides the generic credential patterns.

required

Returns:

Type Description
DataFrame

What call returned.

Raises:

Type Description
ImportError

If the client library is missing (the message names the extra).

SourceError

For any other failure. The client's exception is not chained, since it may quote the secret.

raw_from_result(frame, config, backend, metadata)

Wrap a query result as raw data, with the schema the result decides.

Parameters:

Name Type Description Default
frame DataFrame

Result rows.

required
config InputConfig

Input settings.

required
backend QuerySource

The back end, for its default column names.

required
metadata dict[str, Any]

Recorded in the dataset metadata.

required

Returns:

Type Description
RawData

The rows, metadata, schema and path keys.

jitterbug.io.sources.uri

Source URIs: a database source written where a file path would go.

Forms (credentials are rejected; see docs/DATA_SOURCES.md):

  • clickhouse://[user@]host[:port][/database]; clickhouses:// connects over HTTPS;
  • influxdb2://host[:port]?org=ORG (Flux); influxdb2s:// over HTTPS;
  • influxdb3://host[:port]/database[?language=influxql] (SQL by default); influxdb3s:// over HTTPS;
  • duckdb: or duckdb:// (in-memory), duckdb:///absolute/path.db, duckdb:relative/path.db; ?read_only=false opens a file for writing.

SCHEMES = {'clickhouse': ('clickhouse', False), 'clickhouses': ('clickhouse', True), 'influxdb2': ('influxdb2', False), 'influxdb2s': ('influxdb2', True), 'influxdb3': ('influxdb3', False), 'influxdb3s': ('influxdb3', True), 'duckdb': ('duckdb', False)} module-attribute

URI scheme -> (source kind, secure).

uri_scheme(text)

The lower-case scheme of text if it is a source URI scheme, else None.

influxdb is reported too, so that it can be rejected with a helpful message.

Parameters:

Name Type Description Default
text str

A command-line input argument.

required

Returns:

Type Description
str | None

The scheme, or None for anything else (file paths included).

is_source_uri(text)

Whether text is written as a database source URI rather than a file path.

Parameters:

Name Type Description Default
text str

A command-line input argument.

required

Returns:

Type Description
bool

True for the schemes of :data:SCHEMES (and influxdb).

parse_source_uri(uri)

Turn a source URI into a SourceConfig without a query.

Parameters:

Name Type Description Default
uri str

A URI of one of the forms listed in this module's docstring.

required

Returns:

Type Description
SourceConfig

Connection settings; the query is set separately (--query).

Raises:

Type Description
ValueError

If the scheme is not a source scheme, the URI holds a password or token, or a part does not apply to the kind. Messages never repeat a secret.

jitterbug.io.sources.credentials

Secrets of database sources: read from the environment, kept out of every message.

Passwords and tokens are never part of a SourceConfig; :func:read_secret takes them from the environment when a query runs. Errors raised by the client libraries can quote connection strings or headers, so :func:redact scrubs the secret itself and the usual credential patterns from any text before it reaches a log, an exception or a report.

REDACTED = '***' module-attribute

What a secret is replaced with.

SourceError

Bases: RuntimeError

A database source could not be read. The message has been redacted, and the client library's exception is not chained (it may hold the secret).

RedactingFilter

Bases: Filter

A logging filter that redacts records before a handler writes them.

Client libraries log on their own (clickhouse-connect logs transport errors with their traceback); attached to a handler, this filter scrubs every secret read by :func:read_secret and the generic credential patterns of :func:redact from the message and the formatted traceback. jitterbug commands install it on the root handlers; library users can do the same.

filter(record)

Redact record in place; never drops it.

read_secret(source)

Read the password or token of source from its environment variable.

Parameters:

Name Type Description Default
source SourceConfig

The source; SourceConfig.secret_env names the variable.

required

Returns:

Type Description
str | None

The secret, or None when the back end takes none (DuckDB) or the variable is unset or empty.

redact(text, secrets=())

Remove secrets from text.

Parameters:

Name Type Description Default
text str

A message, typically from a client library's exception.

required
secrets Iterable[str | None]

Known secret values to replace wherever they appear; None and empty values are ignored.

()

Returns:

Type Description
str

text with each known secret, and anything that looks like a password or token (URL user information, password=, Authorization: headers...), replaced by ***.

install_redacting_filter(logger=None)

Add a :class:RedactingFilter to every handler of logger (the root by default, plus logging.lastResort) that does not have one yet.

Parameters:

Name Type Description Default
logger Logger | None

Logger whose handlers to filter.

None

jitterbug.io.readers.delimited

CSV-like readers: csv (comma, tab or semicolon, detected) and tsv (tab).

DELIMITERS = (',', '\t', ';') module-attribute

Separators detect_delimiter chooses from, in order of preference on ties.

detect_delimiter(header)

Pick the field separator of a header line.

Parameters:

Name Type Description Default
header str

First non-empty line of the file.

required

Returns:

Type Description
str

The one of ,, tab and ; that occurs most often (comma on ties); comma when none occurs (a one-column file).

read_csv(path, config)

Read a delimited file with a header row; the separator is config.delimiter or detected from the header (comma, tab or semicolon).

Parameters:

Name Type Description Default
path Path

File path (possibly compressed).

required
config InputConfig

Input settings; only delimiter is used here.

required

Returns:

Type Description
RawData

The raw frame; metadata["delimiter"] is the separator used.

read_tsv(path, config)

Read a tab-separated file with a header row (config.delimiter overrides the tab).

Parameters:

Name Type Description Default
path Path

File path (possibly compressed).

required
config InputConfig

Input settings; only delimiter is used here.

required

Returns:

Type Description
RawData

The raw frame; metadata["delimiter"] is the separator used.

jitterbug.io.readers.jsonl

JSON readers: scamper (scamper -O json output), jsonl (one flat object per line, mapped through InputConfig), and json, which looks at the records and picks one of those two or atlas (RIPE Atlas results, :mod:jitterbug.io.readers.atlas).

A file is either JSON lines or one JSON array of records (see :func:jitterbug.io.readers.json_records.parse_json_records). Telling the record kinds apart, in this order:

  1. scamper output when at least one record is a scamper ping ("type": "ping" with a responses field) or one of scamper's bookkeeping records ("type" list, cycle-def, cycle-start or cycle-stop);
  2. RIPE Atlas results when at least one record has the prb_id, msm_id and result fields every Atlas result carries;
  3. generic JSONL otherwise.

A type field alone is not enough: scamper and RIPE Atlas both write "type": "ping", and so may anything else.

SCAMPER_BOOKKEEPING_TYPES = frozenset({'list', 'cycle-def', 'cycle-start', 'cycle-stop'}) module-attribute

Record types scamper writes around its measurements.

SCAMPER_SCHEMA = {'time_column': 'epoch', 'time_unit': 's', 'rtt_column': 'rtt', 'rtt_unit': 'ms', 'source_column': 'source', 'destination_column': 'destination'} module-attribute

The frame the scamper reader builds is in this fixed schema, whatever the user's column and unit settings are.

is_scamper_record(record)

Return whether a parsed JSON line is a scamper record (see the module docstring).

Parameters:

Name Type Description Default
record Any

One parsed line.

required

Returns:

Type Description
bool

True for a scamper ping or bookkeeping record.

read_scamper(path, config)

Read scamper JSON output (scamper -O json, sc_warts2json).

Only ping records are used: each response with an rtt (milliseconds) and a tx time becomes a row, with src/dst as source and destination. Other records, timeouts and invalid JSON lines are skipped.

Parameters:

Name Type Description Default
path Path

File path (possibly compressed).

required
config InputConfig

Unused: the scamper schema is fixed (SCAMPER_SCHEMA).

required

Returns:

Type Description
RawData

The raw frame in SCAMPER_SCHEMA.

Raises:

Type Description
ValueError

If the file cannot be read or holds no usable response.

read_jsonl(path, config)

Read generic JSON lines: one flat object per line (or a JSON array of flat objects), fields mapped through InputConfig like CSV columns. Invalid JSON lines are skipped with a warning.

Parameters:

Name Type Description Default
path Path

File path (possibly compressed).

required
config InputConfig

Unused here; the mapping happens during normalization.

required

Returns:

Type Description
RawData

The raw frame.

Raises:

Type Description
ValueError

If the file cannot be read, a line is not a JSON object, or there is no record.

read_json(path, config)

Read JSON lines (or a JSON array of records) as scamper output, RIPE Atlas results or generic JSONL, decided by content (see the module docstring). A file with no records at all is treated as scamper output.

Parameters:

Name Type Description Default
path Path

File path (possibly compressed).

required
config InputConfig

Input settings.

required

Returns:

Type Description
RawData

The raw frame; metadata["format"] is scamper_warts, ripe_atlas or jsonl.

jitterbug.io.exporters

Result export utilities.

JSON and CSV outputs are compressed when the path ends in .zst, .gz, .bz2 or .xz (results.json.zst); see :mod:jitterbug.io.compression.

ResultExporter

Exporter for analysis results to various formats.

export_to_json(results, output_path, pretty=True)

Export results to JSON format.

Parameters:

Name Type Description Default
results CongestionInferenceResult

Analysis results to export.

required
output_path Union[str, Path]

Path to save JSON file; compressed if it ends in .zst, .gz, .bz2 or .xz.

required
pretty bool

Whether to format JSON with indentation.

True

export_to_csv(results, output_path)

Export results to CSV format.

Parameters:

Name Type Description Default
results CongestionInferenceResult

Analysis results to export.

required
output_path Union[str, Path]

Path to save CSV file; compressed if it ends in .zst, .gz, .bz2 or .xz.

required

export_to_parquet(results, output_path)

Export results to Parquet format.

Parameters:

Name Type Description Default
results CongestionInferenceResult

Analysis results to export.

required
output_path Union[str, Path]

Path to save Parquet file.

required

Raises:

Type Description
ValueError

If output_path has a compression suffix: Parquet compresses its own columns.

export_summary(results, output_path)

Export summary statistics to JSON format.

Parameters:

Name Type Description Default
results CongestionInferenceResult

Analysis results to export.

required
output_path Union[str, Path]

Path to save summary JSON file; compressed if it ends in .zst, .gz, .bz2 or .xz.

required

reject_compressed_parquet(output_path)

Raise ValueError for compressed (*.zst, *.gz, ...) Parquet output, which would compress twice.

jitterbug.io.compression

Transparent compression for input and output files.

A path whose last suffix is .zst, .gz, .bz2 or .xz (rtts.csv.gz, results.json.zst) is read and written through the matching codec; any other path is a plain file. gzip, bzip2 and xz use the standard library. The Zstandard codec is the standard library's compression.zstd on Python 3.14 and later, otherwise the zstandard package (the zstd extra).

COMPRESSION_SUFFIXES = {'.zst': 'zstd', '.gz': 'gzip', '.bz2': 'bzip2', '.xz': 'xz'} module-attribute

Compressed-file suffixes and the codec each one names.

is_zstd(path)

Return whether path names a Zstandard-compressed file (last suffix .zst).

Parameters:

Name Type Description Default
path str | Path

File path.

required

Returns:

Type Description
bool

True for *.zst, case-insensitive.

compression_of(path)

Return the codec named by the last suffix of path.

Parameters:

Name Type Description Default
path str | Path

File path.

required

Returns:

Type Description
str | None

"zstd", "gzip", "bzip2" or "xz" (case-insensitive suffix match); None for an uncompressed path.

is_compressed(path)

Return whether path names a compressed file (see COMPRESSION_SUFFIXES).

Parameters:

Name Type Description Default
path str | Path

File path.

required

Returns:

Type Description
bool

True for *.zst, *.gz, *.bz2 and *.xz, case-insensitive.

inner_suffix(path)

Return the suffix that describes the content, ignoring a compression suffix.

Parameters:

Name Type Description Default
path str | Path

File path.

required

Returns:

Type Description
str

Lower-case suffix, e.g. ".csv" for rtts.csv, rtts.csv.zst and rtts.csv.gz; empty when there is none.

open_text(path, mode='r', newline=None)

Open a text file, through a decompressing stream when path is compressed.

Parameters:

Name Type Description Default
path str | Path

File path.

required
mode str

"r" or "w".

'r'
newline str | None

Passed to the text layer, as in :func:open. Use "" when handing the stream to the csv module or pandas.

None

Returns:

Type Description
IO[str]

Text stream; use it as a context manager.

Raises:

Type Description
ValueError

If mode is not "r" or "w".

ImportError

If path ends in .zst and no Zstandard codec is available.

read_head(path, size=16)

Return the first bytes of a file's content, decompressed when path is compressed.

Parameters:

Name Type Description Default
path str | Path

File path.

required
size int

Number of bytes to read at most.

16

Returns:

Type Description
bytes

Up to size bytes; fewer for a shorter file.

Raises:

Type Description
ImportError

If path ends in .zst and no Zstandard codec is available.

Notes

Errors reading the file or decoding it with its codec propagate unchanged.