Paginated Chat Transcript Loading and Token-Budget Eviction

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement two core components of an LLM chat backend's transcript manager:

  1. Part 1 — Cursor-Based Transcript Fetching (iter_history and load_history): Stream and materialize a conversation stored behind a paginated fetch_page(cursor) callback.
  2. Part 2 — Token-Budget Sliding Buffer (History): Maintain an in-memory prompt buffer that automatically evicts the oldest non-system turns whenever appending a new turn pushes the running token total past token_limit.

Use the following types, exceptions, and signatures:

from typing import Callable, Iterator, List, Optional, Tuple
from dataclasses import dataclass
import time


@dataclass(frozen=True)
class Message:
    id: str
    role: str
    text: str
    tokens: int


FetchPage = Callable[[Optional[str]], Tuple[List[Message], Optional[str]]]


class TransientFetchError(Exception):
    """Temporary upstream failure that should be retried with backoff."""


class RepeatedCursorError(Exception):
    """Upstream returned a cursor that was already seen earlier in the traversal."""


def iter_history(
    fetch_page: FetchPage,
    max_attempts: int = 3,
    base_delay: float = 0.1,
    sleep: Callable[[float], None] = time.sleep,
) -> Iterator[Message]: ...


def load_history(
    fetch_page: FetchPage,
    newest_first: bool = False,
    max_attempts: int = 3,
    base_delay: float = 0.1,
    sleep: Callable[[float], None] = time.sleep,
) -> List[Message]: ...


class History:
    total_tokens: int

    def __init__(self, token_limit: int, system_message: Optional[Message] = None): ...
    def add(self, message: Message) -> List[Message]: ...
    def messages(self) -> List[Message]: ...
    def __len__(self) -> int: ...

Detailed Rules

Part 1: iter_history and load_history

  • Cursor progression and termination: Request the first page with cursor=None. Each call returns (page_messages, next_cursor). Continue requesting next_cursor until fetch_page returns next_cursor=None, which marks the final page. An empty page_messages list paired with a non-None next_cursor does not terminate pagination.
  • Lazy streaming (iter_history): Yield messages one at a time in the order returned by fetch_page. Do not fetch the first page until iteration begins, and do not fetch the next page until the caller consumes every item from the current page.
  • Cycle protection: Track every non-None cursor returned during a traversal. If fetch_page returns a cursor that has already appeared earlier (either back-to-back like "c1" -> "c1" or via a multi-page loop like "p1" -> "p2" -> "p1"), raise RepeatedCursorError immediately without requesting that cursor again.
  • Retry with exponential backoff: Validate max_attempts >= 1 and base_delay >= 0, raising ValueError otherwise. Whenever fetch_page(cursor) raises TransientFetchError, retry that same cursor up to max_attempts total calls for that page. After failed attempt k (1 <= k < max_attempts), call sleep(base_delay * (2 ** (k - 1))) (base_delay, 2 * base_delay, 4 * base_delay, ...). If attempt max_attempts still raises TransientFetchError, propagate it without calling sleep again. Do not retry any other exception type.
  • Eager chronological loading (load_history): Collect the entire conversation into a list[Message] ordered oldest-to-newest. When newest_first=False, the source already serves pages and intra-page items oldest-first. When newest_first=True, the source serves pages newest-first and items within each page newest-first, so reverse the collected stream before returning.

Part 2: History

  • Initialization and validation: Raise ValueError if token_limit <= 0. If system_message is provided, raise ValueError if system_message.tokens < 0 or system_message.tokens > token_limit. Initialize self.total_tokens to system_message.tokens if present, or 0 otherwise.
  • Pinned system prompt: When system_message is set, it stays permanently at index 0 of messages(), is never evicted by add, and is not counted by len(history), though its tokens always count toward self.total_tokens.
  • Adding turns and evicting (add): Raise ValueError if message.tokens < 0. Append message as the newest turn, then repeatedly evict the oldest retained non-system message while self.total_tokens > token_limit (a total exactly equal to token_limit fits without eviction). Return the evicted Message objects in eviction order (oldest first). If message alone exceeds the remaining non-system budget (token_limit - system_tokens), all prior non-system messages and message itself are evicted and returned.
  • Inspection (messages and __len__): messages() returns a fresh list containing system_message (if any) followed by all retained non-system messages from oldest to newest. len(history) returns the number of retained non-system messages.

Examples

Example 1

Suppose fetch_page serves three pages for u1 (5 tokens), a1 (4 tokens), and u2 (6 tokens):

  • cursor=None returns ([u1, a1], "cur_1")
  • cursor="cur_1" returns ([], "cur_2") (an empty intermediate page)
  • cursor="cur_2" raises TransientFetchError on its first call, then returns ([u2], None) on its second call

Input:

load_history(fetch_page, max_attempts=3, base_delay=0.05, sleep=recorder)

Output:

[u1, a1, u2]

Walk-through: iter_history requests None and yields u1, a1. Seeing "cur_1", it fetches the empty middle page and keeps going because next_cursor="cur_2" is non-None. On "cur_2", the first attempt fails with TransientFetchError, so recorder records one backoff delay of 0.05 seconds before the retry succeeds with ([u2], None) and ends pagination.

Example 2

Track five turns arriving into History(token_limit=12) with no system message: t1 (5 tokens), t2 (4 tokens), t3 (3 tokens), t4 (4 tokens), and t5 (6 tokens).

Input:

history = History(token_limit=12)
d1 = history.add(t1)  # 5 tokens
d2 = history.add(t2)  # 4 tokens
d3 = history.add(t3)  # 3 tokens
d4 = history.add(t4)  # 4 tokens
d5 = history.add(t5)  # 6 tokens

Output:

d1 == []
d2 == []
d3 == []
d4 == [t1]
d5 == [t2, t3]
history.messages() == [t4, t5]
history.total_tokens == 10
len(history) == 2

Walk-through: After t1, t2, and t3, the total reaches 5 + 4 + 3 = 12, which equals token_limit and keeps all three turns. Appending t4 (4) raises the sum to 16 > 12, evicting t1 (5) to reach 11 <= 12. Appending t5 (6) raises the sum to 17 > 12; popping t2 (4) leaves 13 > 12, so t3 (3) is also popped, bringing total_tokens to 10 <= 12 with [t4, t5] retained.

Example 3

Pin sys_msg (3 tokens) inside History(token_limit=10, system_message=sys_msg) and add m1 (4 tokens), m2 (4 tokens), and an oversized turn huge (9 tokens).

Input:

history = History(token_limit=10, system_message=sys_msg)
e1 = history.add(m1)    # 4 tokens
e2 = history.add(m2)    # 4 tokens
e3 = history.add(huge)  # 9 tokens

Output:

e1 == []
e2 == [m1]
e3 == [m2, huge]
history.messages() == [sys_msg]
history.total_tokens == 3
len(history) == 0

Walk-through: sys_msg permanently reserves 3 of the 10 tokens, leaving 7 tokens for conversation turns. m1 (4) fits at 7 <= 10. Adding m2 (4) reaches 11 > 10 and evicts m1, leaving [sys_msg, m2] at 7 tokens. Adding huge (9) reaches 16 > 10, evicting m2 (12 > 10) and then huge itself (3 <= 10), leaving sys_msg intact.

Constraints

  • token_limit >= 1 for valid History configurations; raise ValueError when token_limit <= 0.
  • Every valid Message has tokens >= 0 (tokens == 0 is allowed); raise ValueError for negative tokens or when system_message.tokens > token_limit.
  • max_attempts >= 1 and base_delay >= 0.0; raise ValueError otherwise.
  • History.add may be invoked 3 * 10^5 or more times sequentially and must run in amortized O(1) time per message (len(history) in O(1) time).

Step-by-step walkthrough

  1. Restate the problem and pin down the contract

    We are building two connected pieces of a conversation agent's memory layer:

    • Part 1 — Pagination (iter_history and load_history): Given a function fetch_page(cursor) that takes an opaque cursor (a bookmark token handed back by the server to tell it where the next page begins) and returns (page_messages, next_cursor), assemble the conversation in chronological order (oldest message first). The first call passes cursor=None, and next_cursor=None marks the final page.
    • Part 2 — Token-limit compaction (History): Maintain a live conversation buffer with a positive token_limit. Every add(message) appends the newest message and evicts the oldest messages until the total token count is <= token_limit, returning any evicted messages in oldest-first order.

    Because real-world specs leave room for clarification, state the concrete rules our contract enforces: - By default, pages arrive oldest-first and messages within each page are oldest-first; newest_first=True handles an API whose stream is newest-first end-to-end. - A total equal to token_limit fits (total_tokens <= token_limit). - TransientFetchError (such as a network timeout or HTTP 503) is retried per page up to max_attempts total calls using exponential backoff (doubling the wait time after each failure: base_delay, 2 * base_delay, 4 * base_delay, ...). Non-transient errors (like ValueError) fail immediately. - An optional system_message is pinned at the front: it counts toward token_limit and is never evicted. - If a single new message is larger than the remaining budget, all older non-system messages and the oversized message itself are evicted and returned by add.

  2. Why the obvious first drafts break or crawl

    In Part 1, beginners commonly write a loop that checks if not page: break or while cursor::

    Bug 1: while cursor: ...             -> cursor starts at None, so page 1 is NEVER fetched!
    Bug 2: if not page: break            -> stops early when a page is empty (e.g., deleted messages
                                            filtered out server-side) even though next_cursor = "c2"!
    Bug 3: no cursor tracking            -> if a buggy server returns A -> B -> A, the client loops forever!
    Bug 4: prepending page[::-1] + msgs  -> copies all loaded messages on every page: O(N * P) instead of O(N).
    

    In Part 2, the obvious compaction loop calls sum(m.tokens for m in msgs) and msgs.pop(0) after every add: - sum(...) re-reads all N kept messages on every turn: O(N). - list.pop(0) on a Python list shifts every remaining element one slot to the left in memory: also O(N).

    Running an O(N) step across N messages costs O(N^2) total time. On 300,000 messages with a 150,000-token window, O(N^2) re-summing takes minutes and list.pop(0) takes seconds, whereas maintaining a running integer sum and a double-ended queue finishes in a few tens of milliseconds.

  3. Retry transient page failures with exponential backoff

    Isolate retry logic into a small helper fetch_with_retry that fetches one page. Retrying at the single-page level is much cleaner than restarting load_history from scratch: if page 47 times out, pages 1 through 46 stay intact.

    We also accept sleep as an injected function parameter (defaulting to time.sleep) so unit tests can pass a fake recorder and verify exact backoff delays in microseconds without actually sleeping.

    def fetch_with_retry(fetch_page: FetchPage, cursor: Optional[str], max_attempts: int,
                         base_delay: float, sleep: Callable[[float], None]) -> Tuple[List[Message], Optional[str]]:
        """Call fetch_page(cursor), retrying TransientFetchError with exponential backoff."""
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        if base_delay < 0:
            raise ValueError("base_delay cannot be negative")
    
        # attempt counts 1-indexed calls for this single page (1, 2, ..., max_attempts).
        attempt = 1
        while True:
            try:
                return fetch_page(cursor)
            except TransientFetchError:
                # Stop retrying once we have used all allowed attempts so we do not sleep in vain.
                if attempt >= max_attempts:
                    raise
                # Exponential backoff: base_delay, 2 * base_delay, 4 * base_delay, ...
                delay = base_delay * (2 ** (attempt - 1))
                sleep(delay)
                attempt += 1
    

    Notice if attempt >= max_attempts: raise runs before sleep(delay): if max_attempts = 3 and all 3 tries fail, we sleep only twice (0.1s, 0.2s) and surface the 3rd exception immediately.

  4. Paginate lazily with a generator, and detect cursor cycles

    Write the core pagination loop as a Python generator (a function using yield that produces items on demand and pauses between them). That gives us lazy loading for free: iter_history fetches the next page only when the caller reads past the end of the current page, keeping memory at a single page if the caller stops early.

    Trace how cursor and seen_cursors advance on Example 1's stream (including an empty middle page) versus a broken cyclic stream:

    Normal stream (Example 1, with an empty middle page):
      call 1: cursor=None     -> ([u1, a1], "cur_1")   yield u1, a1; seen={"cur_1"}
      call 2: cursor="cur_1"  -> ([],       "cur_2")   empty page, NOT the end! seen={"cur_1", "cur_2"}
      call 3: cursor="cur_2"  -> ([u2],     None)      yield u2; next_cursor is None -> STOP.
    
    Broken cyclic stream:
      call 1: cursor=None     -> ([u1], "p1")          seen={"p1"}
      call 2: cursor="p1"     -> ([a1], "p2")          seen={"p1", "p2"}
      call 3: cursor="p2"     -> ([u2], "p1")          "p1" is already in seen -> raise RepeatedCursorError!
    

    Look closely at the order of the two checks at the bottom of the loop: 1. Check if next_cursor is None: return first, because None means "stream finished", not "go back to page 1". 2. Then check if next_cursor in seen_cursors:, which catches both direct self-loops ("c1" -> "c1") and multi-page cycles ("p1" -> "p2" -> "p1").

    load_history is the eager wrapper: it drains iter_history into a list and, if newest_first=True, reverses the list once at the end in O(N) time.

    def iter_history(fetch_page: FetchPage, max_attempts: int = 3, base_delay: float = 0.1,
                     sleep: Callable[[float], None] = time.sleep) -> Iterator[Message]:
        """Lazily yield every message in the order the source serves them."""
        # First page is always requested with cursor=None.
        cursor = None
        # seen_cursors: set of non-None cursor strings already returned, e.g. {"c1", "c2"}.
        seen_cursors = set()
    
        while True:
            page, next_cursor = fetch_with_retry(fetch_page, cursor, max_attempts, base_delay, sleep)
            for message in page:
                yield message
    
            # Check next_cursor is None FIRST: an empty page with a non-None cursor must keep going,
            # and None marks normal end-of-stream rather than a repeated cursor back to page 1.
            if next_cursor is None:
                return
            if next_cursor in seen_cursors:
                raise RepeatedCursorError(f"cursor {next_cursor!r} was returned twice")
    
            seen_cursors.add(next_cursor)
            cursor = next_cursor
    
    
    def load_history(fetch_page: FetchPage, newest_first: bool = False, max_attempts: int = 3,
                     base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> List[Message]:
        """Eagerly load the whole conversation, oldest message first."""
        messages = []
        for message in iter_history(fetch_page, max_attempts, base_delay, sleep):
            messages.append(message)
    
        # Reverse once at the end in O(N) time instead of prepending each page in O(N * P) time.
        if newest_first:
            messages.reverse()
        return messages
    
  5. Compact in amortized O(1) time with a running sum and a deque

    Two simple data-structure choices eliminate all O(N) work per message:

    1. Running token counter (self.total_tokens): Add message.tokens when appending, and subtract oldest.tokens when evicting. Checking whether we exceed token_limit takes O(1) time.
    2. Double-ended queue (collections.deque): Unlike a Python list, a deque (pronounced "deck") stores elements in linked fixed-size blocks so both append(x) on the right and popleft() on the left run in O(1) time with zero element shifting.
    Pinned slot               Sliding deque self._messages (oldest -> newest)
    +-----------------+       +----------+----------+
    | sys_msg (3 tok) |   +   | m1:4 tok | m2:4 tok |   total_tokens = 3 + 4 + 4 = 11 > 10
    +-----------------+       +----------+----------+
      (never popped)               ^              ^
                                   | popleft()    | append(m2) in O(1)
                              evicts m1:4 -> total_tokens = 7 <= 10
    

    Why is add amortized O(1) (meaning the average cost per operation over any sequence of N operations is bounded by a constant, even if one call occasionally does more work)? One add might pop several small messages at once, taking O(k) time for k pops. However, every message can enter self._messages once and leave self._messages at most once. Across N calls to add, total appends are N and total popleft calls are <= N, so total work is O(N) — O(1) amortized per message!

    Why can self._messages.popleft() never crash on an empty deque? In __init__, we enforce 0 <= system_message.tokens <= token_limit. Even if a huge message arrives and forces every item in self._messages (including the new message itself!) to be popped, self.total_tokens returns to system_message.tokens (or 0), which is <= token_limit, terminating while self.total_tokens > self.token_limit: cleanly.

  6. Code the `History` class

    Let's assemble History with full input validation (token_limit <= 0, negative tokens on either system_message or added messages, and system_message.tokens > token_limit):

    class History:
        """Conversation history that keeps its token total at or below token_limit
        by dropping the oldest messages. An optional system message is always kept
        and counts toward the limit.
        """
    
        def __init__(self, token_limit: int, system_message: Optional[Message] = None):
            if token_limit <= 0:
                raise ValueError("token_limit must be positive")
            if system_message is not None:
                if system_message.tokens < 0:
                    raise ValueError("token counts cannot be negative")
                if system_message.tokens > token_limit:
                    raise ValueError("the system message alone exceeds the token limit")
    
            self.token_limit = token_limit
            self.system_message = system_message
            # self._messages: deque of kept non-system Message objects, [oldest, ..., newest].
            self._messages = deque()
            # Running sum of tokens across system_message (if any) plus all items in self._messages.
            self.total_tokens = 0
            if system_message is not None:
                self.total_tokens = system_message.tokens
    
        def add(self, message: Message) -> List[Message]:
            """Append message, then drop the oldest messages until total_tokens <= token_limit."""
            if message.tokens < 0:
                raise ValueError("token counts cannot be negative")
    
            # Phase 1: append the newest message on the right in O(1) and update the running sum.
            self._messages.append(message)
            self.total_tokens += message.tokens
    
            # dropped: evicted Message objects in eviction order [oldest_dropped, ...].
            dropped = []
    
            # Phase 2: use strict '>' because total_tokens == token_limit still fits.
            # Since system_message.tokens <= token_limit, popping all of self._messages (including
            # an oversized new message) brings total_tokens <= token_limit before the deque is empty.
            while self.total_tokens > self.token_limit:
                oldest = self._messages.popleft()
                self.total_tokens -= oldest.tokens
                dropped.append(oldest)
    
            return dropped
    
        def messages(self) -> List[Message]:
            """Return [system_message] (if present) followed by kept messages oldest first."""
            result = []
            if self.system_message is not None:
                result.append(self.system_message)
            result.extend(self._messages)
            return result
    
        def __len__(self) -> int:
            """Number of kept non-system messages."""
            return len(self._messages)
    
  7. Trace normal compaction, oversized messages, and agent loop timing

    Walk through Example 2 (History(token_limit=12)) as turns t1:5, t2:4, t3:3, t4:4, t5:6 arrive:

    call      after append (total)     evicted (oldest first)   kept deque         final total
    -------   ----------------------   ----------------------   ----------------   -----------
    add(t1)   [t1]             (5)     []                       [t1]               5
    add(t2)   [t1, t2]         (9)     []                       [t1, t2]           9
    add(t3)   [t1, t2, t3]     (12)    []                       [t1, t2, t3]       12  (== limit fits!)
    add(t4)   [t1, t2, t3, t4] (16)    [t1]                     [t2, t3, t4]       11
    add(t5)   [t2, t3, t4, t5] (17)    [t2, t3]                 [t4, t5]           10
    

    Now trace Example 3's oversized turn huge:9 added to History(token_limit=10, system_message=sys_msg:3) currently holding [m2:4] (total_tokens = 7): 1. Append huge:9 -> deque [m2, huge], total_tokens = 3 + 4 + 9 = 16 > 10. 2. Pop m2:4 -> total_tokens = 12 > 10; pop huge:9 -> total_tokens = 3 <= 10. 3. add(huge) returns [m2, huge], history.messages() stays [sys_msg], len(history) is 0, and subsequent turns that fit within the remaining 7-token non-system budget can still be added normally.

    Where does compaction sit relative to LLM calls? Because add() compacts eagerly on every insertion, history.messages() is guaranteed within budget before every model call:

    1. User sends turn     -> history.add(user_msg)        (compacts immediately)
    2. Call LLM API        -> send history.messages()      (guaranteed <= token_limit)
    3. Receive LLM reply   -> history.add(assistant_msg)   (compacts immediately)
    

    In production, set token_limit to model_context_window - max_output_tokens - tool_schema_tokens, not the raw context window, so the model always has room to generate its reply.

  8. Complete solution

    from typing import Callable, Iterator, List, Optional, Tuple
    from collections import deque
    from dataclasses import dataclass
    import time
    
    
    @dataclass(frozen=True)
    class Message:
        id: str
        role: str    # for example "user" or "assistant"
        text: str
        tokens: int  # token count of this message
    
    
    FetchPage = Callable[[Optional[str]], Tuple[List[Message], Optional[str]]]
    
    
    class TransientFetchError(Exception):
        """A fetch failure worth retrying, such as a timeout or a 503."""
    
    
    class RepeatedCursorError(Exception):
        """The source returned a cursor it had already returned, so the pages would loop forever."""
    
    
    # ---------------------------------------------------------------- Part 1: pagination
    
    def fetch_with_retry(fetch_page: FetchPage, cursor: Optional[str], max_attempts: int,
                         base_delay: float, sleep: Callable[[float], None]) -> Tuple[List[Message], Optional[str]]:
        """Call fetch_page(cursor), retrying TransientFetchError with exponential backoff."""
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")
        if base_delay < 0:
            raise ValueError("base_delay cannot be negative")
    
        # attempt counts 1-indexed calls for this single page (1, 2, ..., max_attempts).
        attempt = 1
        while True:
            try:
                return fetch_page(cursor)
            except TransientFetchError:
                # Stop retrying once we have used all allowed attempts so we do not sleep in vain.
                if attempt >= max_attempts:
                    raise
                # Exponential backoff: base_delay, 2 * base_delay, 4 * base_delay, ...
                delay = base_delay * (2 ** (attempt - 1))
                sleep(delay)
                attempt += 1
    
    
    def iter_history(fetch_page: FetchPage, max_attempts: int = 3, base_delay: float = 0.1,
                     sleep: Callable[[float], None] = time.sleep) -> Iterator[Message]:
        """Lazily yield every message in the order the source serves them."""
        # First page is always requested with cursor=None.
        cursor = None
        # seen_cursors: set of non-None cursor strings already returned, e.g. {"c1", "c2"}.
        seen_cursors = set()
    
        while True:
            page, next_cursor = fetch_with_retry(fetch_page, cursor, max_attempts, base_delay, sleep)
            for message in page:
                yield message
    
            # Check next_cursor is None FIRST: an empty page with a non-None cursor must keep going,
            # and None marks normal end-of-stream rather than a repeated cursor back to page 1.
            if next_cursor is None:
                return
            if next_cursor in seen_cursors:
                raise RepeatedCursorError(f"cursor {next_cursor!r} was returned twice")
    
            seen_cursors.add(next_cursor)
            cursor = next_cursor
    
    
    def load_history(fetch_page: FetchPage, newest_first: bool = False, max_attempts: int = 3,
                     base_delay: float = 0.1, sleep: Callable[[float], None] = time.sleep) -> List[Message]:
        """Eagerly load the whole conversation, oldest message first."""
        messages = []
        for message in iter_history(fetch_page, max_attempts, base_delay, sleep):
            messages.append(message)
    
        # Reverse once at the end in O(N) time instead of prepending each page in O(N * P) time.
        if newest_first:
            messages.reverse()
        return messages
    
    
    # ---------------------------------------------------------------- Part 2: compaction
    
    class History:
        """Conversation history that keeps its token total at or below token_limit
        by dropping the oldest messages. An optional system message is always kept
        and counts toward the limit.
        """
    
        def __init__(self, token_limit: int, system_message: Optional[Message] = None):
            if token_limit <= 0:
                raise ValueError("token_limit must be positive")
            if system_message is not None:
                if system_message.tokens < 0:
                    raise ValueError("token counts cannot be negative")
                if system_message.tokens > token_limit:
                    raise ValueError("the system message alone exceeds the token limit")
    
            self.token_limit = token_limit
            self.system_message = system_message
            # self._messages: deque of kept non-system Message objects, [oldest, ..., newest].
            self._messages = deque()
            # Running sum of tokens across system_message (if any) plus all items in self._messages.
            self.total_tokens = 0
            if system_message is not None:
                self.total_tokens = system_message.tokens
    
        def add(self, message: Message) -> List[Message]:
            """Append message, then drop the oldest messages until total_tokens <= token_limit."""
            if message.tokens < 0:
                raise ValueError("token counts cannot be negative")
    
            # Phase 1: append the newest message on the right in O(1) and update the running sum.
            self._messages.append(message)
            self.total_tokens += message.tokens
    
            # dropped: evicted Message objects in eviction order [oldest_dropped, ...].
            dropped = []
    
            # Phase 2: use strict '>' because total_tokens == token_limit still fits.
            # Since system_message.tokens <= token_limit, popping all of self._messages (including
            # an oversized new message) brings total_tokens <= token_limit before the deque is empty.
            while self.total_tokens > self.token_limit:
                oldest = self._messages.popleft()
                self.total_tokens -= oldest.tokens
                dropped.append(oldest)
    
            return dropped
    
        def messages(self) -> List[Message]:
            """Return [system_message] (if present) followed by kept messages oldest first."""
            result = []
            if self.system_message is not None:
                result.append(self.system_message)
            result.extend(self._messages)
            return result
    
        def __len__(self) -> int:
            """Number of kept non-system messages."""
            return len(self._messages)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine assembling a flipbook delivered one envelope (page) at a time, where each envelope contains a slip of paper — a cursor (an opaque server bookmark naming the next page) — until the final envelope arrives with None. Once you have the cards, you place them onto a conveyor belt sitting on a weight scale (token_limit): every new message goes onto the right end of the belt, and whenever the scale reads strictly above token_limit, the oldest cards drop off the left end one by one until the belt fits again. Storing the belt in a deque (double-ended queue, a container supporting O(1) appends on the right and O(1) pops from the left without shifting memory) alongside a running total_tokens integer makes keeping only the most recent fitting conversation suffix effortless.

Why do the naive approaches fail? For pagination, stopping as soon as a page list is empty (if not page: break) prematurely truncates conversations when the server filters deleted messages out of a middle page, and failing to record previously seen cursors turns a buggy server loop ("A" -> "B" -> "A") into an infinite hang. For compaction, calling sum(m.tokens for m in history) and list.pop(0) after every message scans and shifts all K kept messages on each turn, turning N turns into slow O(N * K) (O(N^2) worst-case) work.

Let's trace Examples 1 and 2 — paginating across an empty middle page and feeding turns into History(token_limit=12):

Pagination (Example 1):
  fetch_page(None)     -> ([u1:5, a1:4], next_cursor="cur_1")   seen_cursors = {"cur_1"}
  fetch_page("cur_1")  -> ([],           next_cursor="cur_2")   empty page, keep going! seen = {"cur_1", "cur_2"}
  fetch_page("cur_2")  -> ([u2:6],       next_cursor=None)      None -> stop! Loaded [u1, a1, u2]

Compaction (Example 2, token_limit = 12):
  add(t1:5), add(t2:4), add(t3:3) -> deque = [t1:5, t2:4, t3:3], total_tokens = 12 (<= 12, fits!)
  add(t4:4)                       -> append t4:4 -> total_tokens = 16 > 12
                                  -> popleft() evicts t1:5 -> deque = [t2:4, t3:3, t4:4], total_tokens = 11
  add(t5:6)                       -> append t5:6 -> total_tokens = 17 > 12
                                  -> popleft() evicts t2:4 (13 > 12), then t3:3 (10 <= 12) -> returns [t2, t3]

Complexity

Let N be the total number of messages fetched across P pages, and let K be the number of messages currently kept inside History.

  • iter_history and load_history:
    • Time: O(N + P) (without retries). We fetch each of the P pages once, check and insert its cursor in a hash set in O(1) average time, and yield each of the N messages once (load_history optionally reverses the N-item list once at the end in O(N) time). With transient failures, each page makes at most max_attempts calls.
    • Space: O(P + B) for iter_history (where B is one page's size) and O(N + P) for load_history. seen_cursors stores up to P cursor strings, iter_history holds only the current page in memory at a time, and load_history materializes all N messages into a list.
  • History.add(message):
    • Time: O(1) amortized (O(1 + D) worst-case when D old messages are evicted on that call). Appending to the right of deque and updating self.total_tokens take O(1) time, and across M total add calls each message is appended once and popped via popleft() at most once, so total evictions across all M calls never exceed M.
    • Space: O(K) persistent (plus O(D) returned for the D messages evicted by that call), since self._messages retains only the messages that currently fit within token_limit.
  • History.messages() and len(history):
    • messages() takes O(K) time and O(K) space to copy the optional system message and the K kept messages into a fresh list for the caller; len(history) takes O(1) time and O(1) space.

Edge cases

  • Empty conversation ([([], None)]): fetch_page(None) yields zero items and returns next_cursor = None, so load_history cleanly returns [].
  • Empty middle pages ([([m1], "c1"), ([], "c2"), ([m2], None)]): Because only next_cursor is None terminates the loop, "c1"'s empty page is crossed without losing m2.
  • Direct or multi-hop cursor cycles ("x" -> "x" or "A" -> "B" -> "A"): Storing all seen cursors in a set catches cycles of any length immediately with RepeatedCursorError (whereas comparing only next_cursor == cursor would miss "A" -> "B" -> "A").
  • Exact budget match (total_tokens == token_limit): The loop condition while self.total_tokens > self.token_limit: uses strict >, keeping histories that hit the limit on the nose.
  • Single oversized message (message.tokens > remaining_budget): Every older non-system message and the new message itself are popped in FIFO order and returned by add, leaving self._messages empty (and system_message intact if present).
  • Zero-token messages (tokens == 0): Appended without evicting anything, and still evicted in chronological order whenever a later large message pushes older messages out.
  • Invalid configuration or negative token counts: token_limit <= 0, system_message.tokens > token_limit, negative tokens on either system_message or add(message), and max_attempts < 1 all raise ValueError immediately.

Common mistakes

  • Writing while cursor: for pagination: Since the first request uses cursor = None, while cursor: never executes even once. Use while True: and exit when next_cursor is None.
  • Checking seen_cursors before if next_cursor is None: return while initializing seen_cursors = {None}: That misclassifies the normal end-of-stream None cursor on the final page as a repeated cursor! Always return on next_cursor is None first.
  • Retrying every exception or sleeping after the final failed attempt: Catching Exception instead of TransientFetchError wastes backoff delays on permanent 400 Bad Request or ValueError bugs, and sleeping before checking attempt >= max_attempts adds a pointless delay right before crashing.
  • Prepending reversed pages (messages = page[::-1] + messages) for newest_first=True: Copying the growing list on every page turns O(N) loading into O(N * P). Also ask in interviews whether a "newest-first" endpoint reverses messages within each page or only page order while keeping each page oldest-first.
  • Using list.pop(0) or sum(...) inside History.add: Both turn fast amortized O(1) updates into O(K) work per turn.
  • Forgetting to validate system_message.tokens: Allowing system_message.tokens > token_limit would make while self.total_tokens > self.token_limit: pop from an empty deque (IndexError), and allowing system_message.tokens < 0 would silently inflate the budget past token_limit.

Alternative approaches

  • Append-only log with prefix sums + binary search (O(log N) query, O(N) memory): Keep every message ever added plus an array of prefix sums (cumulative token totals prefix[i] = sum of first i messages). Finding the longest suffix whose tokens fit budget means finding the smallest i with prefix[N] - prefix[i] <= budget via bisect_left in O(log N) time. This uses O(N) memory instead of O(K), which is helpful when you also want an in-memory audit log of dropped turns.
  • Lazy newest-first pagination with early stop: When initializing History at startup from a huge stored thread, if the backend supports serving messages newest-first, iterate lazily with iter_history and stop fetching pages as soon as accumulated tokens reach token_limit - system_tokens. For a 10,000-message thread where only the latest 250 messages fit, that fetches ~3 pages instead of 100.

Follow-up questions

  • Suppose evicted turns must be condensed into a running summary rather than deleted outright—how would you redesign eviction and reserve space for the summary itself? Pin a rolling summary_message slot right after system_message and carve out a dedicated token reserve R for it so the live turn budget becomes token_limit - system_tokens - R (enforced via max_tokens=R on the summarizer request, then recording the actual returned summary token count). Because invoking an LLM summarizer on every turn is slow and costly, batch compaction using hysteresis (high/low watermarks): when live turns cross 100% of their budget, pop oldest turns down to ~70% of that budget and fold those popped turns (which add already returns!) together with the prior summary into an updated summary. For example, with token_limit = 8,000, system = 500, and R = 500, crossing 7,000 turn tokens trims the deque to ~4,900 tokens so summarization only fires once every ~2,100 new tokens.
  • How would you adapt the sliding buffer so an assistant's function invocation and its corresponding output are always retained or evicted as an indivisible unit? Store atomic turn groups (group_messages, group_tokens) inside self._messages instead of bare Message objects — for instance, [assistant_tool_call, tool_output_1, tool_output_2] paired with their combined token sum. Each popleft() then removes the entire group together so the prompt never contains an orphaned tool output without its call or a dangling tool call missing its outputs (both of which LLM chat APIs reject with 400 validation errors). While tool executions are still running asynchronously, stage the open group in a pending buffer outside the deque and append the sealed group once every tool output returns.
  • If live turns keep arriving while a client is still walking backward through historical pages, how do you prevent missing or duplicated entries? Avoid offset pagination (OFFSET 20 LIMIT 20 on a newest-first feed), where inserting one live turn shifts every older item's index by +1 and duplicates the boundary turn across consecutive pages (while a deletion shifts indices by -1 and skips a turn). Instead, anchor cursors with keyset pagination on an immutable sort key such as (created_at, message_id) < cursor_key so live inserts at the newest end never move historical page boundaries. On the client, open the real-time event subscription before requesting page 1, buffer incoming live turns during pagination, and deduplicate by message.id where the historical backfill meets the live buffer.
  • How can you verify retry timing, cursor-cycle guards, and lazy page loading in unit tests without hitting a real backend? Inject fetch_page and sleep as callable parameters rather than hard-coding HTTP clients and time.sleep, just as our implementation does. Pair them in tests with an in-memory fake source mapping each cursor to (page, next_cursor) plus scripted per-cursor failure queues and a maximum call-count assertion so an infinite loop fails in milliseconds instead of hanging CI. That lets fast unit tests deterministically assert empty middle pages, "c1" -> "c1" and "p1" -> "p2" -> "p1" cycle detection, exact backoff schedules like [0.1, 0.2], non-retryable exception propagation, and lazy page-fetch counts alongside a single recorded-fixture test verifying backend wire schemas.

Follow-up questions

Similar questions

More Sierra interview questions

All 6 Sierra questions →