"""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.
"""
import logging
from dataclasses import dataclass
from typing import Dict, List, Tuple
from .models import DumpFile, RunDirectory
logger = logging.getLogger("memdiver.phase_normalizer")
CANONICAL_PHASE_ORDER: List[str] = [
"pre_key_update", "post_key_update",
"pre_handshake_end", "post_handshake_end",
"pre_second_event", "post_second_event",
"pre_cleanup", "post_cleanup",
]
_GENERIC_SUFFIXES: List[str] = ["handshake_end", "second_event"]
#: 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.
UNPARSED_TIMESTAMP: Tuple[int, int, int] = (-1, -1, -1)
[docs]
def parse_phase_timestamp(timestamp: str) -> Tuple[int, int, int]:
r"""Convert a three-part timestamp to a numeric sort key.
rCompare each field as an integer so variable-width fractions retain
rchronological order. Return :data:`UNPARSED_TIMESTAMP` for invalid
rinput.
r"""
parts = timestamp.split("_")
if len(parts) != 3:
return UNPARSED_TIMESTAMP
try:
return int(parts[0]), int(parts[1]), int(parts[2])
except ValueError:
return UNPARSED_TIMESTAMP
[docs]
@dataclass
class PhaseMapping:
"""Maps a raw dump phase to its canonical lifecycle stage."""
raw_phase: str
canonical_phase: str
timestamp: str
dump_file: DumpFile
def _group_into_pairs(
sorted_dumps: List[DumpFile],
) -> List[Tuple[str, List[DumpFile]]]:
"""Group captures by phase name in order of first occurrence."""
groups: Dict[str, List[DumpFile]] = {}
for dump in sorted_dumps:
groups.setdefault(dump.phase_name, []).append(dump)
return list(groups.items())
def _generic_suffix(index: int) -> str:
"""Return the canonical suffix for the *index*-th generic pair."""
if index < len(_GENERIC_SUFFIXES):
return _GENERIC_SUFFIXES[index]
return f"event_{index + 1}"
def _emit_mappings(
dumps: List[DumpFile],
suffix: str,
result: Dict[str, PhaseMapping],
) -> None:
"""Map each capture's full phase to its prefix and the selected suffix."""
for dump in dumps:
result[dump.full_phase] = PhaseMapping(
raw_phase=dump.full_phase,
canonical_phase=f"{dump.phase_prefix}_{suffix}",
timestamp=dump.timestamp,
dump_file=dump,
)
[docs]
class PhaseNormalizer:
"""Map capture phase names to canonical lifecycle stages."""
KEY_UPDATE_NAMES = {"server_key_update", "client_key_update"}
CLEANUP_NAMES = {"cleanup"}
[docs]
def normalize_run(self, run: RunDirectory) -> Dict[str, PhaseMapping]:
"""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.
"""
if not run.dumps:
return {}
sorted_dumps = sorted(run.dumps, key=lambda d: parse_phase_timestamp(d.timestamp))
pairs = _group_into_pairs(sorted_dumps)
return self._classify_pairs(pairs)
[docs]
def available_canonical_phases(self, runs: List[RunDirectory]) -> List[str]:
"""Return known canonical phases present in the runs, in display order."""
seen: set = set()
for run in runs:
for mapping in self.normalize_run(run).values():
seen.add(mapping.canonical_phase)
return [phase for phase in CANONICAL_PHASE_ORDER if phase in seen]
[docs]
@staticmethod
def get_canonical_display(canonical: str) -> str:
"""Return a human-readable label (e.g. 'Pre Handshake End')."""
return canonical.replace("_", " ").title()
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
def _classify_pairs(
self,
pairs: List[Tuple[str, List[DumpFile]]],
) -> Dict[str, PhaseMapping]:
"""Classify grouped phase pairs into canonical categories."""
result: Dict[str, PhaseMapping] = {}
generic_pairs: List[Tuple[str, List[DumpFile]]] = []
last_cleanup_dumps = None
for phase_name, dumps in pairs:
if phase_name in self.KEY_UPDATE_NAMES:
_emit_mappings(dumps, "key_update", result)
elif phase_name in self.CLEANUP_NAMES:
last_cleanup_dumps = dumps
else:
generic_pairs.append((phase_name, dumps))
for idx, (_phase_name, dumps) in enumerate(generic_pairs):
_emit_mappings(dumps, _generic_suffix(idx), result)
if last_cleanup_dumps is not None:
_emit_mappings(last_cleanup_dumps, "cleanup", result)
return result