788. Profile a slow LLM endpoint: longest call from sampled stacks
Your LLM serving endpoint is slow and you attach a sampling profiler (py-spy style). It does not see every call: every few milliseconds it records the current call stack of the worker, and you rebuild the calls from those snapshots to find which call ran the longest.
Write longest_call(samples). samples is a list of (t, stack) pairs with strictly increasing times t (ms). stack lists function names from the outermost call to the innermost one. An empty stack [] means the worker was idle.
Rules for rebuilding calls:
- A call at depth d is the same call across consecutive samples as long as the first d + 1 names of the stack stay exactly the same.
- It starts at the first sample where it appears and ends at the last consecutive sample where it is still there. Duration = end - start, so a call seen in only one sample lasts 0.
- If the stack changes at depth d, every call at depth d or deeper ends, even if a function with the same name shows up again later. Two requests handled one after another are two separate calls of handle, not one long call.
- Recursion is allowed: the same name can appear at several depths.
Return (name, duration) for the longest call. Break ties by the earlier start time, then by the smaller depth. Return None for an empty list.
def longest_call(samples)Example 1
Input: samples = [(0, ['main']), (1, ['main', 'load']), (2, ['main', 'train']), (3, ['main', 'train', 'step']), (4, ['main', 'train']), (5, ['main'])]
Output: ('main', 5)
Explanation: The longest inner call is train, from 2 to 4.
Example 2
Input: samples = [(0, ['a', 'b']), (2, ['a', 'c']), (3, ['a', 'b']), (9, ['x'])]
Output: ('a', 3)
Explanation: The two b calls are separate calls, each of duration 0.
Constraints
- At most 10,000 samples.
- Times are strictly increasing integers.
- Stacks may be empty.
Hint 1
Compute the longest common prefix of the previous and current stack.
Hint 2
Close deeper calls at the previous sample time, not the current one.
Hint 3
Use a tuple key for the tie-break rules.
Common mistakes
- Merging two calls just because the same name appears at the same depth again after a parent changed.
- Ending a call at the time of the sample where it vanished, which adds time it did not run.
- Forgetting to close the calls still open after the last sample.
Understand the idea
Sampled profiles are approximations: you only know a call was running at the moments you looked. Rebuilding calls means matching the common prefix of consecutive stacks. A deeper frame cannot outlive its parent, and the same name reappearing after a change in a parent frame is a new call. Inclusive time (time with the function anywhere on the stack) answers which code path is slow; this exercise finds the single longest call.