Fetch Cursor-Paginated Conversation History and Compact It to a Token Budget
Company: Sierra
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
This is a 45-minute hands-on coding exercise in an existing codebase built around conversation history. A few API classes return conversations and their content, and one of them returns results a page at a time together with a `next_cursor`. Before extending anything, you need to work out how these classes relate to each other. You then extend the code in two parts: fetch the complete history, then compact it to fit a token budget.
The classes themselves were not reported. For practice, assume an interface like the one below, and treat everything under Clarifying Questions as something to confirm by reading the code or asking the interviewer:
```python
from dataclasses import dataclass, field
@dataclass
class Message:
id: str
role: str # for example "system", "user", "assistant"
content: str
metadata: dict = field(default_factory=dict) # token_count may live in here
@dataclass
class Page:
messages: list[Message]
next_cursor: str | None
class ConversationClient:
def get_page(self, conversation_id: str, cursor: str | None = None) -> Page:
"""Returns one page of a conversation's messages. May raise a retryable error."""
```
### Clarifying Questions
- Which class and method fetch one page, and what does a page contain? How do you know you have reached the end: `next_cursor` is missing, it is an empty value, or a page comes back with no messages?
- What exactly is returned: a list of conversations, all the messages of one conversation, or both? In what order?
- Where is `token_count`: a number on each message, or inside a string or nested metadata that must be parsed?
- What does compacting mean here: deleting messages, merging them, or replacing older ones with a summary? What is the token limit?
- Which messages must never be touched, such as the system instruction or the most recent user turn?
### Part 1 — Fetch the complete history by following the cursor
Using the existing API, retrieve the full history: request a page, pass its `next_cursor` to request the next one, and continue until there are no more pages, returning every message in order. The result must be complete and ordered, contain no duplicates, and not lose the last page. The code must also cope with transient errors, with a cursor that repeats, and with pagination that never ends.
```hint Define the end first
Write down exactly what "no more pages" looks like in this API before writing the loop, then trace your loop on a final page that has messages but no cursor.
```
```hint Three different failures
A transient error, a repeated cursor and pagination that never ends need different responses. Decide what state the loop must remember to tell them apart.
```
#### What This Part Should Cover
- Reusing the existing classes and their cursor convention rather than rewriting the client
- Termination that keeps the final page, with order preserved and duplicates removed
- Bounded retries with backoff, for retryable errors only
- Guards against repeated cursors and endless pagination, and what the caller receives when they trigger
### Part 2 — Compact the conversation to a token budget
Parse each message's `token_count` and compact the conversation so that its total fits within a token budget. The budget and the compaction rules are not given in advance; agree them with the interviewer.
```hint Protected messages first
Work out which messages cannot be removed and what they cost before choosing anything else, including what should happen if they alone exceed the budget.
```
```hint Bad counts
Decide what a missing or unparseable token count should mean before it silently becomes zero.
```
#### What This Part Should Cover
- Robust parsing of token counts wherever and however they are stored
- An explicit, agreed policy: protected messages, which messages go first, and order preservation
- Correct behavior at the boundaries: exactly at the budget, protected messages over budget, an empty history
- How a summary, if used, is placed and counted
### What a Strong Answer Covers
- Time spent understanding the existing classes before changing them, and clarifying questions that settle the open policies
- Pagination that is complete, ordered, free of duplicates, and safe against retries, cursor loops and endless pages
- A compaction function whose result is guaranteed to fit the budget and to keep every protected message
- Clean, testable code with injected dependencies, and a concrete testing plan
### Follow-up Questions
- If the history is too large to fit in memory, how would you change the fetch so compaction can run over a stream of pages?
- If removed messages are replaced with a summary, how do you account for the summary's own tokens?
- If the API rate-limits you or fails partway through, how do you resume instead of starting over?
- How would you test the compaction rules?
Overview: A hands-on coding exercise in an existing conversation-history codebase: follow next_cursor to fetch every page of a conversation reliably, then compact the messages to fit a token budget using each message's token_count. It tests reading unfamiliar code, pagination edge cases, retries, and a correct, testable compaction policy.
Read the full Sierra Software Engineer interview experience this question came from