33From stack samples to a trace

mediumpython
45:00

33 From stack samples to a trace

Anthropic software engineer candidates report a coding question about profiler samples: given snapshots of the call stack taken over time, produce the events where each function call starts and ends (q-ant-034, q-ant-093, q-ant-156, and a curated interview write-up, q-ant-027). Another candidate names the question only as Stack Trace (1 report). A Staff candidate was asked to find the slowest part of the code from profiler samples with start and end events (1 report), and a prep guide lists finding the longest-running function from stack trace samples (1 source). Exclusive Time of Functions, which totals each function's own time from start and end logs with a stack, is on Anthropic's LeetCode tag list (1 source). This is practice in that shape, not a leaked question or LeetCode's version.

Set a 45-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/33_stack_samples -k level1. Earlier levels must keep passing.

The samples. A sampling profiler stops a program every so often and records its call stack. One sample is a pair (time, stack). stack is a list of function names, outermost call first and innermost last, the same order a Python traceback prints. An empty stack means nothing was running. Samples come in order of time, and times only go up. A sampler sees nothing between two samples, so each sample stands for the time from it to the next one.

Level 1. Write trace(samples) -> list[tuple] that returns events (time, kind, name), where kind is "start" or "end".

  • A frame in one sample is the same call as the frame at the same depth in the next sample only when the two stacks agree at that depth and at every depth below it. If anything below it changed, it's a new call, even with the same name.
  • At each sample, the calls from the previous sample that aren't still running end, then the calls that are new start, all at this sample's time. Ends go innermost first and starts go outermost first, the order they really happened in.
  • The first sample starts every call in it. The last sample ends every call still open, at the last sample's time, innermost first. No samples means no events.
(0,  ["main"])                        (0,  "start", "main")
(10, ["main", "load"])                (10, "start", "load")
(20, ["main", "load", "parse"])       (20, "start", "parse")
(30, ["main", "load", "parse"])       (40, "end",   "parse")
(40, ["main", "save"])          ->    (40, "end",   "load")
(50, ["main", "save"])                (40, "start", "save")
(60, ["main", "save"])                (70, "end",   "save")
(70, ["main"])                        (70, "end",   "main")

Level 2. Turn events into time. events is a list in the shape trace returns. A call lasts from its start to its end.

  • function_times(events, include_callees) -> dict. With include_callees=True, a function's time is the total length of its calls, with the time spent in the functions they call. With include_callees=False, it's only the time the function itself was the innermost call, its self time. Every function that appears in events is a key, even when its time is 0. No events gives {}.
  • The events must nest like brackets. An end whose name isn't the innermost open call, an end with no call open, and calls still open after the last event each raise ValueError.
  • slowest(events) -> str | None returns the function with the most self time. Total time can't answer this question, because the outermost function always has the most of it. Ties go to the name that sorts first, and no events returns None.

On the events above, self time is {"main": 10, "load": 10, "parse": 20, "save": 30}, total time is {"main": 70, "load": 30, "parse": 20, "save": 30}, and the slowest function is "save".

Level 3. What makes it hard on real programs.

  • The same function at two depths. A recursive function shows up more than once in one stack. trace gives each depth its own start and end. For include_callees=True, count each moment once per function: a function's total time is how long at least one of its calls was open, so f calling itself for 10 seconds is 10 seconds of f, not 20. Self time needs no change.
  • A call that ends and starts again between two samples. With names alone, f returning and being called again between two samples looks like one long call. Some samplers tag each frame with a call id. Write trace_calls(samples), the same as trace except that each frame is a pair (name, call_id), and two frames are the same call only when both the name and the id match, along with everything below them. Events still give just the name.

Things to get right: the frames two samples share, counted from the bottom; the order of events within one time; a function name at a new depth or under a new caller; and a recursive function's total time.

Be ready for what comes next: what a sampler misses between samples, why sampling can't count calls, how to stream millions of samples in memory bounded by the stack's depth, and samples from several threads.

solution.py
Run the tests to see which pass.