Process tree memory rollup
From a process listing of pid, parent pid, resident memory and command, total the memory of every subtree and return the k largest, coping with orphans and rejecting cycles.
Statement
A host is short of memory and the process listing is thousands of lines long. The useful question is rarely which single process is biggest; it is which service, counted with everything it started, is biggest. rows holds one (pid, ppid, rss_kb, command) per process, the columns that ps -eo pid,ppid,rss,comm prints: the process id, its parent's id, its resident memory in kilobytes and its command name.
Write subtree_memory(rows), which returns {pid: total_kb} where the total is the process's own rss_kb plus that of all its descendants, and top_subtrees(rows, k), which returns the k largest as (pid, command, total_kb), largest first, with equal totals in ascending pid order.
Listings are imperfect. A process whose parent is not in rows is the top of its own tree: pid 1 has parent 0, which is never listed, and a listing filtered to one user loses parents too. A repeated pid, or parents that form a cycle, cannot come from a real kernel, so raise ValueError rather than loop or return a partial answer.
Examples
rows = [(1, 0, 9000, "systemd"),
(400, 1, 3000, "sshd"),
(812, 400, 5200, "bash"),
(900, 1, 150000, "postgres"),
(901, 900, 42000, "postgres"),
(902, 900, 38000, "postgres")]
subtree_memory(rows)
→ {1: 247200, 400: 8200, 812: 5200, 900: 230000, 901: 42000, 902: 38000}
top_subtrees(rows, 3)
→ [(1, "systemd", 247200), (900, "postgres", 230000), (901, "postgres", 42000)]
# 6999 is not listed, so 7001 is the top of its own tree
subtree_memory([(1, 0, 9000, "systemd"), (7001, 6999, 2500, "worker"), (7002, 7001, 1500, "worker")])
→ {1: 9000, 7001: 4000, 7002: 1500}Constraints
Up to 10⁵ rows in any order; a child may be listed before its parent. pids are positive integers and rss_kb is a non-negative integer. k may be 0 or larger than the number of rows.
The tree can be a single chain thousands of processes deep, so do not depend on the recursion limit. Handle each row a constant number of times.