engine.consensus

Compare corresponding byte positions across multiple dumps.

The result contains one variance value per aligned byte. Use high variance to select candidates for independent verification. The builders calculate variance with Welford’s online recurrence or a chunked two-pass calculation. Both avoid storing a matrix with one row per dump.

class ConsensusVector[source]

Bases: object

Per-byte variance vector across N dumps at the same phase.

__init__(thresholds=None)[source]
Parameters:

thresholds (VarianceThresholds | None)

property classifications: array

Per-byte classification codes (ByteClass IntEnum values).

build(dump_paths, *, force=False, budget=None)[source]

Compute per-byte variance across all dump files.

Streams position slabs from every file (core.slab_variance) with the same two-pass estimator as core.variance.compute_variance, so the result is bit-identical while only one slab per file is resident. The predicted peak is checked against the memory budget first (CapabilityError code memory_budget_exceeded unless force).

Parameters:
Return type:

None

build_from_sources(sources, normalize=False, *, force=False, budget=None, alignment=ALIGNMENT_AUTO, frames='all', propagate=False, propagation_depth=None, drop_heap_keys=None)[source]

Build a variance vector from at least two open dump sources.

By default, native Memory Slice captures use module offsets. Sources that support virtual-address alignment use virtual addresses. If every source exposes a mapping list and a common module has different bases, use module-relative offsets. Other sources use file offsets. Check alignment_report for the selected method and comparison coverage. An aligned build with no shared bytes returns an empty result.

Set alignment to file_offset, virtual_address, module_relative, or module_offset to require a method. An unsupported choice raises CapabilityError. The builder checks its peak memory estimate against budget. Set force to bypass that check.

Set frames="private" to exclude shared frames before alignment. This requires sources that can supply the frame classification. The alignment report records the frame counts separately from bytes discarded during alignment.

Set propagate to pair objects reached through corresponding pointers after virtual-address or module-relative alignment. The object rows take precedence over positional rows for the same bytes. Propagation reads the original sources, including when positional alignment uses private frames. It can compare freed objects but does not follow pointers from them. Check object_rows and the propagation report for details. propagation_depth bounds pointer hops and defaults to 5. drop_heap_keys can exclude positional heap keys from a module-relative build with propagation enabled.

Parameters:
  • sources (List)

  • normalize (bool)

  • force (bool)

  • budget (MemoryBudget | int | None)

  • alignment (str)

  • frames (str)

  • propagate (bool)

  • propagation_depth (int | None)

  • drop_heap_keys (bool | None)

Return type:

None

dump_index_for_path(dump_path)[source]

Return the index of a dump path in this build, or -1.

Use resolved paths so that relative paths and symbolic links can match the same dump.

Parameters:

dump_path (str)

Return type:

int

slab_to_va(dump_index, slab_offset)[source]

Absolute VA in dump_index of slab byte slab_offset, or -1.

THE INVERSE of what _va_index_for() / class_window_va() do. Returns -1 — never a plausible-looking address — for a raw build, an out-of-range dump_index, or a slab_offset past the end of the aligned slab. A wrong-but-plausible address is worse than no address here: it sends a viewer to real bytes that mean nothing.

Parameters:
  • dump_index (int)

  • slab_offset (int)

Return type:

int

project_va_window(anchor_index, va, length)[source]

Resolve [va, va+length) in dump anchor_index to segments+gaps.

The full answer behind class_window_va(): same classes, plus where each covered run lives in the slab and in every OTHER dump.

Parameters:
Return type:

WindowProjection

project_vas_window(anchor_index, vas_runs, vas_offset, length)[source]

Project a range in the dense VAS stream of the anchor dump.

A VAS offset counts captured bytes across virtual-address gaps. WindowProjection.start records that offset. Each matched segment stays within one layout row and has coordinates in every dump. The segments and gaps partition the requested range.

Parameters:
Return type:

WindowProjection

project_slab_window(slab_offset, length)[source]

Resolve [slab_offset, +length) into segments+gaps, per dump.

Anchored on the slab, so WindowProjection.anchor_index is -1 and WindowProjection.start is the slab offset.

Parameters:
  • slab_offset (int)

  • length (int)

Return type:

WindowProjection

class_window_va(dump_index, va, length)[source]

Per-byte ByteClass codes for [va, va+length) in a dump’s VA space.

Entries are ByteClass codes for aligned/captured bytes and -1 for VA gaps not present in the consensus (unmapped / not-captured-in-all-dumps).

Parameters:
Return type:

List[int]

va_overview(dump_index, bins=256)[source]

Down-sampled change/variance heatmap across a dump’s aligned VA span.

Returns per-bin fractions changing (class > INVARIANT) and high (class == KEY_CANDIDATE) plus the max level (0..3), for a whole-dump “what stays vs what changes” minimap. A page maps to the bin of its start VA (page << bin width), which is exact enough for the strip.

Parameters:
Return type:

Dict[str, Any]

build_incremental(size)[source]

Begin an incremental consensus build of size bytes per dump.

Use add_source to fold dumps in one at a time and finalize to materialize the variance vector and classifications.

Parameters:

size (int)

Return type:

None

add_source(source)[source]

Fold one dump into an incremental build. Returns live stats.

Accepts a raw bytes buffer or any DumpSource-like object exposing read_all(). The first dump seen is cached as reference_bytes for downstream consumers. Returns (num_dumps, mean_variance, max_variance).

Return type:

Tuple[int, float, float]

get_live_variance()[source]

Return the current variance vector.

During an incremental build this reflects the Welford state at the moment of the call; after finalize() it returns the materialized vector. Public accessor so API/UI layers do not reach into the private Welford accumulator.

Return type:

ndarray

welford_state()[source]

Return (mean, m2, n) — must be called BEFORE finalize().

finalize()[source]

Materialize variance and classifications from the Welford accumulator and release the incremental state.

Return type:

None

iter_regions(byte_class, *, min_length=1, max_length=0, after=-1)[source]

Yield matching regions in slab-offset order.

Compute each row’s variance and label as it is yielded. Set after to the last returned start offset to continue an unchanged query. The default value of -1 starts at the first matching region.

Parameters:
Return type:

Iterator[StaticRegion]

count_regions(byte_class, *, min_length=1, max_length=0)[source]

How many regions iter_regions() would yield from the start.

Run LENGTHS only — no variance reduction and no labelling — because a total is the one number a paginated caller needs on EVERY page, and paying a per-region .mean() for it would reintroduce exactly the whole-slab cost the lazy iterator exists to avoid.

No after: the total is the size of the whole result set, which is what a page counter (“201–400 of 8,412”) is stated against.

Parameters:
Return type:

int

rank_regions_by_length(byte_class, *, min_length=1, max_length=0, descending=True, offset=0, limit=200)[source]

Return a page of matching regions ordered by length.

Equal-length regions are ordered by ascending slab offset. The ranking retains up to offset + limit + 1 candidates. One extra row in the result signals that another page is available.

Parameters:
  • descending (bool) – Return longest regions first if true.

  • offset (int) – Number of ranked rows to skip.

  • limit (int) – Number of rows per page before looking one row ahead.

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

  • min_length (int)

  • max_length (int)

Return type:

List[StaticRegion]

get_regions(byte_class, *, min_length=1, max_length=0)[source]

Contiguous regions of one or more byte classes.

The single retrieval path over all four classes — STRUCTURAL and POINTER have no dedicated getter and were previously counted but unreachable.

Parameters:
  • byte_class (ByteClass | int | Iterable[ByteClass | int]) – A single ByteClass (or its integer code), or an iterable of them for a union query (see _class_runs).

  • min_length (int) – Shortest region to report, in bytes.

  • max_length (int) – Longest region to report; 0 means unbounded.

Returns:

StaticRegion rows in offset order, each carrying the region’s mean variance and the most volatile class it contains.

Return type:

List[StaticRegion]

Expressed as list(self.iter_regions(...)) so the eager and the lazy path cannot drift: there is ONE filter chain and ONE row builder.

get_static_regions(min_length=32)[source]

Find contiguous static (invariant) byte regions.

Parameters:

min_length (int)

Return type:

List[StaticRegion]

get_volatile_regions(min_length=16)[source]

Find contiguous high-variance (key_candidate) regions.

Parameters:

min_length (int)

Return type:

List[StaticRegion]

get_aligned_candidates(block_size=32, alignment=16, density_threshold=0.75, min_length=16)[source]

Find alignment-filtered KEY_CANDIDATE regions.

Like get_volatile_regions but with additional alignment filtering: only keeps candidate blocks that are dense and aligned.

Parameters:
  • block_size (int)

  • alignment (int)

  • density_threshold (float)

  • min_length (int)

Return type:

List[StaticRegion]

classification_counts()[source]

Count bytes in each classification category.

Return type:

Dict[str, int]

ConsensusMatrix

alias of ConsensusVector

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.

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:
invariant_max: float

Alias for field number 0

pointer_max: float

Alias for field number 2

structural_max: float

Alias for field number 1

validate()[source]

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

Return type:

VarianceThresholds

class ByteClass[source]

Bases: IntEnum

Byte-position classification based on cross-run variance.

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

Bases: object

How a consensus vector’s N dumps were aligned, and what that cost.

Every consensus carries one, so no surface has to guess which path ran. bytes_compared is the length of the byte stream every dump contributed to; bytes_discarded is the total input bytes that never took part, summed over all dumps, so that:

sum(input sizes) == bytes_compared * n_sources + bytes_discarded

warnings is non-empty exactly when the result is questionable: the flat fallback ran on dumps of different sizes, or an aligned path kept too little to be representative. Equal-sized dumps on the flat path — the normal case for a phase-series capture of one process — stay silent.

method: str = 'file_offset'
bytes_compared: int = 0
bytes_discarded: int = 0
sizes_differed: bool = False
n_sources: int = 0
warnings: Tuple[str, ...] = ()
diagnostics: Tuple[Any, ...] = ()

Structured core.service_result.Diagnostic notes with a stable code (e.g. classification_basis_mixed), so a surface can localize or act on them instead of echoing warnings prose. Kept separate from warnings so existing string banners are unchanged.

propagation: Dict[str, Any] | None = None

Pointer-propagation report (engine.pointer_alignment.propagate’s report dict plus the build’s row counts) when the build ran with propagate=True; None otherwise, and then absent from to_dict() so every other build serializes byte-identically.

property diagnostic_dicts: List[Dict[str, Any]]

diagnostics in their JSON-ready {code, message, ...} form.

to_dict()[source]

JSON-ready form for the CLI / API / MCP surfaces.

Return type:

Dict[str, Any]

__init__(method='file_offset', bytes_compared=0, bytes_discarded=0, sizes_differed=False, n_sources=0, warnings=(), diagnostics=(), propagation=None)
Parameters:
Return type:

None

class AlignedSegment[source]

Bases: object

One maximal run of a window that the consensus put into correspondence.

window_offset/length index the REQUESTED window, not any dump. vas[d] is the absolute virtual address, in dump d, of the byte at window_offset – parallel to ConsensusVector.dump_paths.

window_offset: int
length: int
slab_offset: int
layout_row: int
vas: Tuple[int, ...]
to_dict()[source]

JSON-ready form for the CLI / API / MCP surfaces.

Return type:

Dict[str, Any]

__init__(window_offset, length, slab_offset, layout_row, vas)
Parameters:
Return type:

None

class WindowProjection[source]

Bases: object

A requested window resolved into aligned segments and gaps.

segments and gaps partition [0, length): ascending, disjoint, and summing to length. That invariant is what lets a caller paint the window without doing any coordinate arithmetic of its own – which is where the two shipped overlay bugs came from.

anchor_index is the dump whose virtual address start is, or -1 when the window was anchored on the slab (then start is a slab offset).

anchor_index: int
start: int
length: int
segments: Tuple[AlignedSegment, ...]
gaps: Tuple[Tuple[int, int], ...]
classes: Tuple[int, ...]
property covered: int

Bytes of the window that are in cross-dump correspondence.

to_dict()[source]

JSON-ready form for the CLI / API / MCP surfaces.

Return type:

Dict[str, Any]

__init__(anchor_index, start, length, segments, gaps, classes)
Parameters:
Return type:

None

ALIGNMENT_AUTO = 'auto'

alignment= choices of ConsensusVector.build_from_sources() and consensus_service.build_consensus: the automatic choice, an explicit VA regime for VA-capable sources, or (R3, align_by on the surfaces) an explicit module_offset (native .msl only) / file_offset (any).

validate_alignment_choice(alignment)[source]

Reject an alignment= value outside ALIGNMENT_CHOICES.

Parameters:

alignment (str)

Return type:

None

MAX_CONSENSUS_WINDOW = 16384

Hard ceiling on the byte length of ONE consensus/hex window, in bytes.

The same 16 KiB literal was written out three times — twice in api/routers/analysis.py (/consensus/range, /consensus/va-range) and once in app/tools_inspect.py (read_hex_raw_result) — which meant the cap a window request was actually held to depended on which door it came through. It lives here, next to the coordinate math every windowed read is expressed in, and every call site imports it.

flat_alignment_report(sizes, bytes_compared)[source]

Report for a flat-offset build, from the N input sizes.

Public because the aligned-window producer’s NO-CONSENSUS path (app.tools_consensus) has to publish the same coverage and warning report from sizes alone — it reads no bytes and builds no vector, but the client still has to be told that byte 0 was compared to byte 0 without ASLR correction. Reproducing that wording there would let the two drift.

Parameters:
Return type:

AlignmentReport