#!/usr/bin/env python3
"""Bounded, read-only snapshot for a 64-bit CPython 3.9 health_web process.

Looks for the 96 MiB pymalloc arena table suggested by the incident's pmap.
Reports mapped arena capacity and samples live small blocks. This is not an
object graph, a native allocation profile, or a consistent stopped snapshot.
"""

import argparse
from bisect import bisect_right
from collections import Counter, namedtuple
from functools import lru_cache
import hashlib
import json
import os
from pathlib import Path
import random
import re
import struct
import sys


MIB = 1024 * 1024
GIB = MIB * 1024
ARENA_BYTES = 256 * 1024
POOL_BYTES = 4096
POOLS_PER_ARENA = ARENA_BYTES // POOL_BYTES
SLOTS = 1 << 21
ARENA = struct.Struct("<QQIIQQQ")
POOL = struct.Struct("<I4xQQQIIII")
PAIR = struct.Struct("<QQ")
TYPE_HEADER = struct.Struct("<QQ8xQq128xQ")
SAMPLE_ARENAS = 24
SAMPLES_PER_POOL = 6
READ_LIMIT = 112 * MIB
Map = namedtuple("Map", "start end perms name")
Table = namedtuple("Table", "chunk base")
TypeHeader = namedtuple("TypeHeader", "refs meta name basicsize flags")


class ProbeError(Exception):
    pass


class Memory:
    def __init__(self, proc, fd):
        self.fd = fd
        self.maps = []
        for line in (proc / "maps").read_text().splitlines():
            fields = line.split(maxsplit=5)
            start, end = (int(value, 16) for value in fields[0].split("-"))
            self.maps.append(Map(start, end, fields[1], fields[5] if len(fields) == 6 else ""))
        self.starts = [mapping.start for mapping in self.maps]
        self.bytes_read = 0

    def mapping(self, address, size):
        index = bisect_right(self.starts, address) - 1
        if index >= 0:
            mapping = self.maps[index]
            if address + size <= mapping.end and mapping.perms.startswith("r"):
                return mapping
        return None

    def read(self, address, size):
        if size <= 0 or self.mapping(address, size) is None:
            return None
        if self.bytes_read + size > READ_LIMIT:
            raise ProbeError("Read budget exceeded; no complete sample")
        self.bytes_read += size
        try:
            data = os.pread(self.fd, size, address)
        except OSError:
            return None
        return data if len(data) == size else None


def is_arena(record, page):
    address, frontier, free, total, _, _, _ = record
    return (
        address > 0
        and address % page == 0
        and address <= frontier <= address + ARENA_BYTES
        and (frontier - address) % POOL_BYTES == 0
        and total == POOLS_PER_ARENA
        and free <= total
    )


def read_candidate(memory, chunk, chunk_bytes, page):
    header = memory.read(chunk, PAIR.size)
    if not header or PAIR.unpack(header) != (0, chunk_bytes | 2):
        return None
    base = chunk + PAIR.size
    matches = 0
    for slot in (0, SLOTS // 8, SLOTS // 4, SLOTS // 2, 3 * SLOTS // 4):
        data = memory.read(base + slot * ARENA.size, 32 * ARENA.size)
        if data is None:
            return None
        for index, entry in enumerate(ARENA.iter_unpack(data), slot):
            if entry[0] == 0:
                continue
            if not is_arena(entry, page) or not memory.mapping(entry[0], ARENA_BYTES):
                return None
            if entry[1] > entry[0]:
                pool = memory.read(entry[0], POOL.size)
                if pool is None or POOL.unpack(pool)[4] != index:
                    return None
                matches += 1
    return Table(chunk, base) if matches >= 4 else None


def locate_table(memory, page):
    chunk_bytes = ((SLOTS * ARENA.size + PAIR.size + page - 1) // page) * page
    candidates = set()
    for mapping in memory.maps:
        if mapping.perms != "rw-p" or mapping.name:
            continue
        if mapping.end - mapping.start >= chunk_bytes:
            candidates.add(mapping.start)
            candidates.add(mapping.end - chunk_bytes)
    # Only examine mapping edges; do not scan the contents of large mappings.
    for chunk in sorted(candidates):
        table = read_candidate(memory, chunk, chunk_bytes, page)
        if table is not None:
            return table, chunk_bytes
    raise ProbeError("Could not verify the expected mmap-backed 96 MiB arena table")


def scan_table(memory, table, page, rng):
    current = free_pools = suspect = 0
    sample = []
    batch_slots = 8192
    for first in range(0, SLOTS, batch_slots):
        data = memory.read(table.base + first * ARENA.size, batch_slots * ARENA.size)
        if data is None:
            raise ProbeError("Arena table changed or became unreadable")
        for offset, entry in enumerate(ARENA.iter_unpack(data)):
            if entry[0] == 0:
                continue
            if not is_arena(entry, page):
                suspect += 1
                continue
            current += 1
            free_pools += entry[2]
            if len(sample) < SAMPLE_ARENAS:
                sample.append((first + offset, entry))
            else:
                index = rng.randrange(current)
                if index < SAMPLE_ARENAS:
                    sample[index] = (first + offset, entry)

    if current < 4 or suspect > max(4, current // 1000):
        raise ProbeError("Arena table layout did not match CPython 3.9")
    return current, free_pools, suspect, sample


def type_reader(memory):
    @lru_cache(maxsize=4096)
    def header(address):
        if address < 4096 or address % 8:
            return None
        data = memory.read(address, TYPE_HEADER.size)
        if data is None:
            return None
        result = TypeHeader(*TYPE_HEADER.unpack(data))
        if not (0 < result.refs < 1 << 48 and result.flags & (1 << 12)):
            return None
        return result

    @lru_cache(maxsize=4096)
    def type_name(address):
        mapping = memory.mapping(address, 1)
        if mapping is None:
            return None
        data = memory.read(address, min(96, mapping.end - address))
        if data is None or b"\0" not in data:
            return None
        name = data.split(b"\0", 1)[0]
        if re.fullmatch(rb"[\w.<>\-]+", name):
            return name.decode("ascii")
        return None

    @lru_cache(maxsize=4096)
    def type_info(address):
        info = header(address)
        if not info or not 16 <= info.basicsize:
            return None
        meta = header(info.meta)
        if meta is None or not meta.flags & (1 << 31):
            return None
        root_address = meta.meta
        root = header(root_address)
        if root is None or root.meta != root_address or type_name(root.name) != "type":
            return None
        name = type_name(info.name)
        if not name:
            return None
        # Compact ASCII strings can use only the smaller PyASCIIObject header.
        minimum = 48 if name == "str" else info.basicsize
        return name, minimum, bool(info.flags & (1 << 14))

    def identify(page, offset, size):
        for gc_prefix in (0, 16):
            if size < gc_prefix + PAIR.size:
                continue
            refs, address = PAIR.unpack_from(page, offset + gc_prefix)
            if not 0 < refs < 1 << 48:
                continue
            info = type_info(address)
            if info and info[1] + gc_prefix <= size and info[2] == bool(gc_prefix):
                return info[0], gc_prefix
        return "<unidentified>", 0

    return identify, type_info


_HEADER_NAMES = frozenset(
    b"accept accept-encoding accept-language allow cache-control connection content-encoding "
    b"content-length content-type date etag expires forwarded host if-modified-since "
    b"if-none-match last-modified location origin pragma range referer server transfer-encoding "
    b"upgrade user-agent vary via x-forwarded-for x-forwarded-host x-forwarded-proto x-real-ip".split()
)
_HTTP_TOKENS = _HEADER_NAMES | frozenset(
    b"get head post http/1.0 http/1.1 keep-alive close text/plain".split()
)
_CONFIGURED_VALUES = {
    b"cache.health.example.test": "configured upstream-check host",
    b"node.monitor.example.test": "configured monitor host",
    b"http://node.monitor.example.test/probe/health": "configured LVS probe URL",
}
_STRING_TYPES = ("str", "multidict._multidict.istr")
_STRING_SAMPLE_BYTES = 128


def string_data(data):
    if len(data) < 48:
        return None
    length = struct.unpack_from("<q", data, 16)[0]
    if not 0 <= length < 1 << 31:
        return None
    # CPython 3.9 LP64 PyASCIIObject. Compact ASCII data starts at byte 48.
    flags = struct.unpack_from("<I", data, 32)[0]
    if (flags & 0xfc) == 0xe4:
        end = 48 + length
        if end < len(data) and data[end] == 0:
            raw = data[48:end]
            if all(byte < 128 for byte in raw):
                return length, raw, "ascii"
        return length, None, "ascii-outside-sample"
    return length, None, "unicode-or-noncompact"


def string_kind(raw):
    lower = raw.lower()
    if lower in _HTTP_TOKENS:
        return "http:" + lower.decode("ascii")
    if lower == b"no vip":
        return "configured probe response"
    if raw.startswith(b"/probe/"):
        return "probe path"
    if raw.startswith((b"http://", b"https://", b"//")):
        return "URL"
    if raw.lstrip().startswith(b'File "'):
        return "formatted stack frame"
    if raw.endswith(b".py"):
        return "Python filename"
    if re.fullmatch(rb"(?:[0-9]{1,3}\.){3}[0-9]{1,3}", raw):
        return "IPv4-like"
    if re.match(rb"^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d\d ", raw) and raw.endswith(b" GMT"):
        return "HTTP date"
    if raw.isdigit():
        return "decimal"
    if re.fullmatch(rb"(?:[a-zA-Z0-9_-]+\.)+[a-zA-Z0-9_-]+", raw):
        return "dotted name"
    if not raw:
        return "empty"
    return "other ASCII"


def standard_header_name(value):
    if value is None:
        return None
    lower = value.lower()
    return lower.decode("ascii") if lower in _HEADER_NAMES else None


class ObjectShapes:
    def __init__(self, memory, type_info):
        self.memory = memory
        self.type_info = type_info
        self.lengths = Counter()
        self.string_kinds = Counter()
        self.repeats = Counter()
        self.containers = Counter()
        self.container_strings = Counter()
        self.configured_values = Counter()
        self.header_pairs = Counter()
        self.list_pair_prefixes = Counter()
        self.extra_bytes = 0
        self.limited = False
        self.digest_key = os.urandom(16)

    def observe(self, name, data):
        if name == "str":
            observation = string_data(data)
            if observation is None:
                return
            length, raw, fallback = observation
            self.lengths[length] += 1
            kind = string_kind(raw) if raw is not None else fallback
            self.string_kinds[kind] += 1
            if raw is not None:
                digest = hashlib.blake2b(raw, digest_size=12, key=self.digest_key).digest()
                self.repeats[kind, length, digest] += 1
                configured = _CONFIGURED_VALUES.get(raw)
                if configured:
                    self.configured_values[configured] += 1
        elif name in ("tuple", "list"):
            if self.extra_bytes >= MIB or self.memory.bytes_read + 8192 > READ_LIMIT:
                self.limited = True
                return
            before = self.memory.bytes_read
            self.container(name, data)
            self.extra_bytes += self.memory.bytes_read - before

    def container(self, name, data):
        if len(data) < 24:
            return
        length = struct.unpack_from("<q", data, 16)[0]
        if not 0 <= length < 1 << 31:
            return
        sample_size = min(length, 4) * 8
        if name == "tuple":
            if 24 + length * 8 > len(data):
                return
            items = data[24:24 + sample_size]
        else:
            if len(data) < 40:
                return
            base, capacity = struct.unpack_from("<Qq", data, 24)
            if length > capacity:
                return
            items = self.memory.read(base, sample_size) if sample_size else b""
            if items is None:
                return

        addresses = [address for address, in struct.iter_unpack("<Q", items)]
        children = [self.describe_child(address) for address in addresses]
        names = [name for name, _, _ in children]
        for _, category, _ in children:
            if category is not None:
                self.container_strings[name, category] += 1
        signature = "{}[{}]({}{})".format(
            name, length, ", ".join(names), ", ..." if length > len(names) else ""
        )
        self.containers[signature] += 1
        if name == "tuple" and length == 2:
            (_, _, key), (_, category, value) = children
            header = standard_header_name(key)
            if header and category is not None:
                self.header_pairs[header, _CONFIGURED_VALUES.get(value, category)] += 1
        elif name == "list" and names and all(child == "tuple" for child in names):
            prefix = tuple(self.pair_label(address) for address in addresses)
            self.list_pair_prefixes[length, prefix] += 1

    def pair_label(self, address):
        data = self.memory.read(address, 24 + PAIR.size)
        if data is None or struct.unpack_from("<q", data, 16)[0] != 2:
            return "tuple of other size"
        key, value = PAIR.unpack_from(data, 24)
        key_type, _, key_text = self.describe_child(key)
        value_type, _, _ = self.describe_child(value, read_string=False)
        header = standard_header_name(key_text)
        return header if header and value_type in _STRING_TYPES else "{} + {}".format(
            key_type, value_type
        )

    def describe_child(self, address, read_string=True):
        if address < 4096 or address % 8:
            return "<unidentified>", None, None
        head = self.memory.read(address, PAIR.size)
        if head is None:
            return "<unidentified>", None, None
        refs, type_address = PAIR.unpack(head)
        info = self.type_info(type_address) if 0 < refs < 1 << 48 else None
        if info is None:
            return "<unidentified>", None, None
        name = info[0]
        if not read_string or name not in _STRING_TYPES:
            return name, None, None

        # Keep arbitrary values in memory only, and read at most a short ASCII string.
        mapping = self.memory.mapping(address, 48)
        size = min(48 + _STRING_SAMPLE_BYTES + 1, mapping.end - address) if mapping else 0
        data = self.memory.read(address, size) if size else None
        observation = string_data(data) if data is not None else None
        if observation is None:
            return name, "unavailable", None
        length, value, fallback = observation
        if name == _STRING_TYPES[1] and value is None and length <= _STRING_SAMPLE_BYTES:
            # A ready, noncompact ASCII PyUnicodeObject uses data.any at LP64 byte 72.
            flags = struct.unpack_from("<I", data, 32)[0]
            if len(data) >= 80 and (flags & 0xfc) == 0xc4:
                base, = struct.unpack_from("<Q", data, 72)
                raw = self.memory.read(base, length + 1)
                if raw is not None and raw[-1] == 0 and all(byte < 128 for byte in raw):
                    value = raw[:-1]
        return name, string_kind(value) if value is not None else fallback, value

    def report(self):
        return {
            "string_length_then_count": self.lengths.most_common(16),
            "string_category_then_count": self.string_kinds.most_common(16),
            "repeated_ascii_category_length_and_count": [
                (kind, length, count)
                for (kind, length, _), count in self.repeats.most_common(12)
                if count > 1
            ],
            "container_shape_then_count": self.containers.most_common(16),
            "container_and_child_string_category_then_count": [
                (name, kind, count)
                for (name, kind), count in self.container_strings.most_common(16)
            ],
            "configured_probe_value_then_count": self.configured_values.most_common(),
            "header_pair_key_value_category_then_count": [
                (key, category, count)
                for (key, category), count in self.header_pairs.most_common(24)
            ],
            "list_length_and_first_pair_keys_or_types_then_count": [
                (length, prefix, count)
                for (length, prefix), count in self.list_pair_prefixes.most_common(16)
            ],
            "detail_read_limit_reached": self.limited,
        }



def pool_blocks(data, offset, address, arena_index):
    count, free, _, _, arena, size_index, next_block, max_offset = POOL.unpack_from(data, offset)
    if arena != arena_index or count > (POOL_BYTES - POOL.size) // 16:
        return None
    if count == 0:
        return 0, []
    if size_index >= 32:
        return None
    size = (size_index + 1) * 16
    exposed = (next_block - POOL.size) // size
    if (
        max_offset != POOL_BYTES - size
        or next_block < POOL.size
        or (next_block - POOL.size) % size
        or not count <= exposed <= (POOL_BYTES - POOL.size) // size
    ):
        return None

    vacant = set()
    while free:
        index, remainder = divmod(free - address - POOL.size, size)
        if remainder or index < 0 or index >= exposed or index in vacant:
            return None
        vacant.add(index)
        free = struct.unpack_from("<Q", data, offset + POOL.size + index * size)[0]
    if count != exposed - len(vacant):
        return None
    return size, [offset + POOL.size + i * size for i in range(exposed) if i not in vacant]


def sample_blocks(memory, table, sample, rng, details):
    identify, type_info = type_reader(memory)
    shapes = ObjectShapes(memory, type_info) if details else None
    by_size = Counter()
    by_type = Counter()
    accepted = checked_objects = 0
    for slot, entry in sample:
        address, frontier, free, total, *_ = entry
        length = frontier - address
        data = memory.read(address, length)
        if data is None:
            continue
        raw = memory.read(table.base + slot * ARENA.size, ARENA.size)
        if raw is None or ARENA.unpack(raw)[:4] != entry[:4]:
            continue
        pools = [
            pool_blocks(data, offset, address + offset, slot)
            for offset in range(0, length, POOL_BYTES)
        ]
        if any(pool is None for pool in pools) or sum(bool(pool[1]) for pool in pools) != total - free:
            continue
        accepted += 1
        for size, offsets in pools:
            if not offsets:
                continue
            block_bytes = len(offsets) * size
            by_size[size] += block_bytes
            inspected = rng.sample(offsets, min(len(offsets), SAMPLES_PER_POOL))
            checked_objects += len(inspected)
            for index, offset in enumerate(inspected):
                name, prefix = identify(data, offset, size)
                by_type[name] += block_bytes / len(inspected)
                if shapes is not None and index < 2:
                    shapes.observe(name, data[offset + prefix:offset + size])
    return accepted, checked_objects, by_size, by_type, shapes


def start_time(proc):
    return (proc / "stat").read_text().rsplit(")", 1)[1].split()[19]


def run(pid, details=False):
    proc = Path("/proc") / str(pid)
    page = os.sysconf("SC_PAGE_SIZE")
    if page not in (4096, 65536) or sys.byteorder != "little" or struct.calcsize("P") != 8:
        raise ProbeError("Expected a little-endian 64-bit Linux system with a 4 or 64 KiB base page")
    if (proc / "comm").read_text().strip() != "health_web":
        raise ProbeError("PID is not health_web")
    identity = start_time(proc)
    with (proc / "exe").open("rb") as binary:
        header = binary.read(20)
    if header[:6] != b"\x7fELF\x02\x01" or struct.unpack_from("<H", header, 18)[0] not in (62, 183):
        raise ProbeError("Expected an amd64 or arm64 executable")

    with (proc / "mem").open("rb", buffering=0) as source:
        memory = Memory(proc, source.fileno())
        if not any("/libpython3.9.so" in mapping.name for mapping in memory.maps):
            raise ProbeError("Expected a mapped CPython 3.9 shared library")
        rss = {}
        for line in (proc / "status").read_text().splitlines():
            field, _, value = line.partition(":")
            if field in ("VmRSS", "RssAnon"):
                rss[field] = int(value.split()[0])
        table, chunk_bytes = locate_table(memory, page)
        rng = random.Random(39)
        current, free, suspect, entries = scan_table(memory, table, page, rng)
        accepted, checked, sizes, types, shapes = sample_blocks(memory, table, entries, rng, details)
        if (
            memory.read(table.chunk, PAIR.size) != PAIR.pack(0, chunk_bytes | 2)
            or start_time(proc) != identity
        ):
            raise ProbeError("Target or arena table changed during collection")

    live_bytes = sum(sizes.values())
    result = {
        "pid": pid,
        "rss_GiB": round(rss["VmRSS"] / (1024 * 1024), 2) if "VmRSS" in rss else None,
        "anonymous_rss_GiB": round(rss["RssAnon"] / (1024 * 1024), 2) if "RssAnon" in rss else None,
        "arena_table_address": hex(table.base),
        "arena_slots": SLOTS,
        "arenas_mapped": current,
        "arena_mapping_GiB": round(current * ARENA_BYTES / GIB, 2),
        "free_pools_GiB_inside_arenas": round(free * POOL_BYTES / GIB, 2),
        "unclassified_arena_records": suspect,
        "sampled_arenas": accepted,
        "sampled_live_block_percent": round(100 * live_bytes / (accepted * ARENA_BYTES), 1) if accepted else None,
        "object_headers_sampled": checked,
        "block_size_bytes_then_live_KiB_in_sample": [
            [size, round(value / 1024, 1)] for size, value in sizes.most_common(8)
        ],
        "type_then_estimated_live_KiB_in_sample": [
            [name, round(value / 1024, 1)] for name, value in types.most_common(12)
        ],
        "target_MiB_read": round(memory.bytes_read / MIB, 2),
    }
    if shapes is not None:
        result["object_details"] = shapes.report()
        result["mapped_http_extensions"] = sorted({
            mapping.name
            for mapping in memory.maps
            if ".so" in mapping.name
            and any("/" + package + "/" in mapping.name for package in ("aiohttp", "multidict", "yarl"))
        })
    return result


def health_web_pids(proc=Path("/proc")):
    pids = []
    for task in proc.iterdir():
        if not task.name.isdecimal():
            continue
        try:
            if (task / "comm").read_text().strip() == "health_web":
                os.readlink(str(task / "exe"))
                pids.append(int(task.name))
        except (FileNotFoundError, ProcessLookupError, PermissionError):
            continue
    return sorted(pids)


def format_pids(pids):
    return ", ".join(str(pid) for pid in pids) or "none"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "pid", type=int, nargs="?",
        help="PID of health_web (default: the sole health_web process on this host)",
    )
    parser.add_argument("--details", action="store_true",
                        help="sample string categories and container element types")
    args = parser.parse_args()
    pid = args.pid
    if pid is not None and pid < 1:
        parser.error("PID must be positive")
    try:
        if pid is None:
            candidates = health_web_pids()
            if len(candidates) != 1:
                raise ProbeError(
                    "Expected a single local health_web process. Current PIDs: {}. "
                    "Provide a PID from this host.".format(format_pids(candidates))
                )
            pid = candidates[0]
        print(json.dumps(run(pid, details=args.details), indent=2))
    except (FileNotFoundError, ProcessLookupError):
        print(
            "Heap sample unavailable: PID {} is unavailable on {}. "
            "Current health_web PIDs: {}.".format(pid, os.uname().nodename,
                                                 format_pids(health_web_pids())),
            file=sys.stderr,
        )
        return 1
    except (OSError, ProbeError) as error:
        print("Heap sample unavailable: {}".format(error), file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())

