core.variance

Compute population variance across captures and classify each byte position.

class ByteClass[source]

Bases: IntEnum

Byte-position classification based on cross-run variance.

INVARIANT = 0
STRUCTURAL = 1
POINTER = 2
KEY_CANDIDATE = 3
__new__(value)
class VarianceThresholds[source]

Bases: NamedTuple

The three boundaries separating the four ByteClass bands.

A byte is INVARIANT at variance <= invariant_max, STRUCTURAL up to structural_max, POINTER up to pointer_max and KEY_CANDIDATE above it. The defaults are the module constants, so an omitted / None threshold set reproduces the historical hard-coded boundaries exactly.

There is no config-file path into this layer today (core.config_schema only covers dataset/logging/analysis/ui and is read solely by ui.state), so overrides travel as an explicit argument from the caller.

invariant_max: float

Alias for field number 0

structural_max: float

Alias for field number 1

pointer_max: float

Alias for field number 2

validate()[source]

Return self after checking the bands are non-negative and ordered.

Return type:

VarianceThresholds

static __new__(_cls, invariant_max=0.0, structural_max=200.0, pointer_max=3000.0)

Create new instance of VarianceThresholds(invariant_max, structural_max, pointer_max)

Parameters:
compute_variance(byte_buffers, min_size, chunk_bytes=CHUNK_BYTES)[source]

Compute per-byte-position variance across multiple byte buffers.

Uses a chunked two-pass estimator: the byte range [0, min_size) is divided into slabs of chunk_bytes bytes; each slab is stacked into an (N, chunk_len) float32 matrix and reduced via np.var(axis=0). Output is bit-identical to a single-call np.var over a fully-stacked matrix because the per-column reduction is column-local.

Parameters:
  • byte_buffers (List[bytes]) – List of raw byte sequences (each at least min_size long).

  • min_size (int) – Number of byte positions to analyze.

  • chunk_bytes (int) – Width of the per-slab reduction. Tests may override.

Returns:

numpy.ndarray (float32) of length min_size with per-byte variance.

Return type:

ndarray

class WelfordVariance[source]

Bases: object

Online (Welford’s recurrence) per-byte variance accumulator.

Maintains running mean and sum-of-squared-deviations vectors of length size that are updated one dump at a time. Intended for incremental / live-capture workflows where dumps arrive sequentially and the full set cannot be held in memory at once.

Computes population variance. The order of floating-point operations can give different rounding from NumPy’s batch calculation.

__init__(size)[source]
Parameters:

size (int)

Return type:

None

property num_dumps: int
property size: int
add_dump(buf)[source]

Fold one dump into the running accumulators.

Processed in position slabs so the transient float32 working set stays O(chunk) rather than O(size). The naive whole-array update allocates ~5 full-width temporaries (x, delta, delta/n, x-mean and the product); on a multi-GiB dump that peaks at tens of GiB. Welford’s recurrence is per-position independent, so slabbing by byte offset is bit-identical to the whole-array update.

Parameters:

buf (bytes)

Return type:

None

variance(out=None)[source]

Return current population variance (ddof=0). Zeros if n == 0.

out (a float32 vector of length size, e.g. a memmap) receives the result instead of a fresh array. m2 / n is already float32, so no astype copy is made; the values are identical to the historical (m2 / n).astype(np.float32).

Parameters:

out (ndarray | None)

Return type:

ndarray

variance_summary()[source]

(mean, max) of the current variance without a full-size temporary.

Walks m2 / n slab by slab. max is exact; mean is accumulated in float64 (it can differ in the last float32 digits from variance().mean(), which uses float32 pairwise summation).

Return type:

tuple[float, float]

reset()[source]
Return type:

None

state_arrays()[source]

Return (mean, m2, n) — used by the CLI to persist state to disk.

Return type:

tuple[ndarray, ndarray, int]

classmethod from_state(mean, m2, n)[source]

Rebuild from persisted arrays (CLI round-trip).

Parameters:
Return type:

WelfordVariance

classify_variance(variance, thresholds=None)[source]

Classify every byte position by its variance value.

Parameters:
  • variance (ndarray | array) – Per-byte variance values (numpy array or stdlib array).

  • thresholds (VarianceThresholds | None) – Optional band boundaries. None uses DEFAULT_THRESHOLDS (0.0 / 200.0 / 3000.0), which is what every caller got before the boundaries became overridable.

Return type:

ndarray

Positions are classified in CLASSIFY_SLAB_POSITIONS-wide slabs, so scratch memory beyond the uint8 result stays bounded.

Returns:

numpy.ndarray (uint8) of ByteClass integer codes.

Parameters:
Return type:

ndarray

normalize_byte_classes(byte_class)[source]

Coerce a class query into a de-duplicated, ordered ByteClass tuple.

Accepts a single ByteClass (or its integer code) as well as any iterable of them, so a caller can ask for one class or several without switching call shape.

Parameters:

byte_class (ByteClass | int | Iterable[ByteClass | int])

Return type:

Tuple[ByteClass, …]

class_mask(classifications, classes)[source]

Bool mask marking every byte belonging to any of classes.

Parameters:
Return type:

ndarray

find_contiguous_runs(classifications, target)[source]

Return half-open ranges of consecutive positions in the target class.

Parameters:
Return type:

List[Tuple[int, int]]

count_classifications(classifications)[source]

Count occurrences of each classification label.

Returns dict with human-readable string keys for backward compatibility.

Return type:

Dict[str, int]

pairwise_leaves_sum(size, leaf_sum, max_leaf=PAIRWISE_LEAF)[source]

Reproduce np.add.reduce of a contiguous float vector slab by slab.

numpy reduces a contiguous float vector with pairwise summation: blocks larger than 128 elements are split at n2 = n // 2 - (n // 2) % 8 and the halves are summed recursively. Every node of that tree is itself np.add.reduce of its sub-range, so recursing with the same split rule down to leaves of at most max_leaf elements and letting leaf_sum(start, end) reduce each leaf gives a bit-identical total without ever materialising the whole vector. Leaves are visited in ascending offset order. max_leaf must be >= 128 so leaves sit on tree nodes. Returns the total in the leaf sums’ dtype.

Parameters:
class RunningTopK[source]

Bases: object

Bounded running selection of the k largest values of a vector fed slab by slab in ascending offset order.

Ordering is deterministic: descending value, ties broken by ascending offset. Each slab contributes at most k local candidates, so working memory is O(slab) for the partition plus O(k) for the running set.

__init__(k)[source]
Parameters:

k (int)

Return type:

None

add_slab(slab, base_offset)[source]

Merge the candidates of slab (positions base_offset + i).

Parameters:
Return type:

None

result()[source]

[(offset, value), ...] in descending value / ascending offset.

Return type:

List[Tuple[int, float]]

Assign canonical lifecycle stages to capture phases.

Recognize key-update and cleanup names directly. Assign generic phases by when each raw phase name first occurs in the run.

UNPARSED_TIMESTAMP: Tuple[int, int, int] = (-1, -1, -1)

Sort key for a dump filename carrying no parseable timestamp (the non-phased dataset dumps: gcore.core, gdb_raw.bin …). All-negative so those sort FIRST, which is where the previous plain-string ordering put their empty timestamp too.

parse_phase_timestamp(timestamp)[source]

Convert a three-part timestamp to a numeric sort key.

rCompare each field as an integer so variable-width fractions retain rchronological order. Return UNPARSED_TIMESTAMP for invalid rinput. r

Parameters:

timestamp (str)

Return type:

Tuple[int, int, int]

class PhaseMapping[source]

Bases: object

Maps a raw dump phase to its canonical lifecycle stage.

raw_phase: str
canonical_phase: str
timestamp: str
dump_file: DumpFile
__init__(raw_phase, canonical_phase, timestamp, dump_file)
Parameters:
Return type:

None

class PhaseNormalizer[source]

Bases: object

Map capture phase names to canonical lifecycle stages.

KEY_UPDATE_NAMES = {'client_key_update', 'server_key_update'}
CLEANUP_NAMES = {'cleanup'}
normalize_run(run)[source]

Return canonical mappings by full phase name.

Sort by timestamp before grouping by raw phase name. Use explicit names for key updates and cleanup. Map the first generic name to handshake end and the second to second event. Later names receive numbered event stages.

Parameters:

run (RunDirectory)

Return type:

Dict[str, PhaseMapping]

available_canonical_phases(runs)[source]

Return known canonical phases present in the runs, in display order.

Parameters:

runs (List[RunDirectory])

Return type:

List[str]

static get_canonical_display(canonical)[source]

Return a human-readable label (e.g. ‘Pre Handshake End’).

Parameters:

canonical (str)

Return type:

str