core.variance
Compute population variance across captures and classify each byte position.
- class ByteClass[source]
Bases:
IntEnumByte-position classification based on cross-run variance.
- INVARIANT = 0
- STRUCTURAL = 1
- POINTER = 2
- KEY_CANDIDATE = 3
- __new__(value)
- class VarianceThresholds[source]
Bases:
NamedTupleThe three boundaries separating the four
ByteClassbands.A byte is INVARIANT at
variance <= invariant_max, STRUCTURAL up tostructural_max, POINTER up topointer_maxand KEY_CANDIDATE above it. The defaults are the module constants, so an omitted /Nonethreshold set reproduces the historical hard-coded boundaries exactly.There is no config-file path into this layer today (
core.config_schemaonly covers dataset/logging/analysis/ui and is read solely byui.state), so overrides travel as an explicit argument from the caller.
- 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-callnp.varover a fully-stacked matrix because the per-column reduction is column-local.- Parameters:
- Returns:
numpy.ndarray (float32) of length min_size with per-byte variance.
- Return type:
- class WelfordVariance[source]
Bases:
objectOnline (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.
- 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-meanand 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 lengthsize, e.g. a memmap) receives the result instead of a fresh array.m2 / nis already float32, so noastypecopy is made; the values are identical to the historical(m2 / n).astype(np.float32).
- variance_summary()[source]
(mean, max)of the current variance without a full-size temporary.Walks
m2 / nslab by slab.maxis exact;meanis accumulated in float64 (it can differ in the last float32 digits fromvariance().mean(), which uses float32 pairwise summation).
- 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.
NoneusesDEFAULT_THRESHOLDS(0.0 / 200.0 / 3000.0), which is what every caller got before the boundaries became overridable.
- Return type:
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:
thresholds (VarianceThresholds | None)
- Return type:
- 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.
- class_mask(classifications, classes)[source]
Bool mask marking every byte belonging to any of classes.
- find_contiguous_runs(classifications, target)[source]
Return half-open ranges of consecutive positions in the target class.
- count_classifications(classifications)[source]
Count occurrences of each classification label.
Returns dict with human-readable string keys for backward compatibility.
- pairwise_leaves_sum(size, leaf_sum, max_leaf=PAIRWISE_LEAF)[source]
Reproduce
np.add.reduceof 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) % 8and the halves are summed recursively. Every node of that tree is itselfnp.add.reduceof its sub-range, so recursing with the same split rule down to leaves of at mostmax_leafelements and lettingleaf_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_leafmust be >= 128 so leaves sit on tree nodes. Returns the total in the leaf sums’ dtype.
- class RunningTopK[source]
Bases:
objectBounded running selection of the
klargest 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
klocal candidates, so working memory is O(slab) for the partition plus O(k) for the running set.
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_TIMESTAMPfor invalid rinput. r
- class PhaseNormalizer[source]
Bases:
objectMap 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:
- available_canonical_phases(runs)[source]
Return known canonical phases present in the runs, in display order.
- Parameters:
runs (List[RunDirectory])
- Return type: