Skip to content

Commit fe44b3a

Browse files
committed
feat(catalog): add Stream Reassembler
1 parent 1b13bcb commit fe44b3a

6 files changed

Lines changed: 323 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# yaml-language-server: $schema=../../schemas/meta.schema.json
2+
id: "0261"
3+
slug: stream-reassembler
4+
title: Stream Reassembler
5+
status: ready
6+
difficulty: medium
7+
track: practical
8+
kind: design
9+
patterns: [arrays-hashing]
10+
domains: [ai-llm]
11+
job_roles: [ai-engineer]
12+
scope: function
13+
languages: [python, typescript]
14+
signature:
15+
class:
16+
name: StreamReassembler
17+
constructor: {params: []}
18+
methods:
19+
- {name: delta, params: [{name: sequence, type: int}, {name: fragment, type: string}], returns: {type: string}}
20+
- {name: finish, params: [{name: lastSequence, type: int}], returns: {type: bool}}
21+
- {name: close, params: [], returns: {type: void}}
22+
- {name: status, params: [], returns: {type: string}}
23+
- {name: text, params: [], returns: {type: string}}
24+
- {name: missing, params: [], returns: {type: "int[]"}}
25+
comparator: {type: ops}
26+
approaches:
27+
- {id: release-contiguous, name: Release the contiguous prefix and hold everything above the first gap, role: optimal, time: "O(1 + r) per delta, O(g) per missing, O(s) per text", space: "O(s)", time_class: "n^2", space_class: "n"}
28+
estimate_minutes: 30
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Stream Reassembler
2+
3+
## Statement
4+
5+
A chat product shows a model's answer as it is written, one small fragment of text at a time. The fragments come through a relay that can deliver them out of order, deliver them twice, or drop the connection partway. The screen must show the text in the right order as soon as it can, and the product must never store a cut-off answer as if it were whole.
6+
7+
The stream has three invented kinds of event. Each fragment carries a `sequence`, counted from 0. A `finish` event says which sequence is the last one. And the connection can close at any moment, whether or not the stream was done. Implement `StreamReassembler`:
8+
9+
- `delta(sequence, fragment)`: a fragment has arrived. It returns the text that this call **releases**. Text is released in sequence order, as soon as every earlier fragment has arrived, so the call returns the fragment followed by any held fragments that it unblocks, or `""` when it unblocks nothing. It is ignored, and returns `""`, in each of these cases:
10+
- that sequence has already arrived, whatever its text: the first text wins,
11+
- a `finish` has been recorded and `sequence` is above its last sequence,
12+
- the connection has closed.
13+
- `finish(lastSequence)`: records that `lastSequence` is the stream's last fragment. It returns `true`, or `false` and changes nothing, when the connection has closed, a `finish` was already recorded, or a fragment above `lastSequence` has already arrived. A stream with no fragments at all finishes with `lastSequence` of `-1`.
14+
- `close()`: the connection is gone, and nothing arrives after this.
15+
- `status()`: `"complete"` when a `finish` has been recorded and every fragment through its last sequence has arrived, whether or not the connection has closed. Otherwise `"truncated"` if the connection has closed, and otherwise `"streaming"`.
16+
- `text()`: all the text released so far. On a truncated stream this is what you may show, labelled as cut off: the text up to the first gap, and nothing beyond it.
17+
- `missing()`: in ascending order, the sequences that have not arrived, from 0 up to the last sequence when a `finish` has been recorded, and otherwise up to the highest sequence that has arrived.
18+
19+
A fragment may be the empty string, which is a real fragment: it fills its place like any other.
20+
21+
## Input
22+
23+
- `sequence`: the fragment's place in the stream, counted from 0.
24+
- `fragment`: the text. It is kept exactly as it came, with its spaces and line breaks.
25+
- `lastSequence`: the sequence of the stream's last fragment, or `-1` when there are none.
26+
27+
Each test is a sequence of calls: the constructor first, then the other calls in order.
28+
29+
## Output
30+
31+
One result per call: `null` for the constructor and for `close`, a string for `delta`, `status` and `text`, a boolean for `finish`, and an integer array for `missing`.
32+
33+
## Examples
34+
35+
### Example 1
36+
37+
<!-- case: ex1 -->
38+
39+
Fragment 1 arrives first and has to wait, so its call releases nothing. Fragment 0 then releases itself and fragment 1 together. Fragment 2 goes straight out. After `finish(2)` the stream is complete.
40+
41+
### Example 2
42+
43+
<!-- case: ex2 -->
44+
45+
`finish` arrives before the fragments are all in, which is allowed: fragment 2 still gets held, and the stream stays `"streaming"` with sequence 1 missing. The second copy of fragment 0 is ignored, even though it has different text. Fragment 1 then releases both.
46+
47+
### Example 3
48+
49+
<!-- case: ex3 -->
50+
51+
Nothing is out of order and nothing is known to be missing, but `finish` never came. The connection closed in the middle of the stream, and the answer may simply stop halfway through a sentence. So this is `"truncated"`.
52+
53+
### Example 4
54+
55+
<!-- case: ex4 -->
56+
57+
A gap at sequence 1 holds fragment 2 back, so the text stops at `"a"`. `finish(3)` makes sequence 3 known too, so both are missing when the connection closes.
58+
59+
## Constraints
60+
61+
- `0 <= sequence < 10^4` and `-1 <= lastSequence < 10^4`.
62+
- A fragment is at most 1000 characters long.
63+
- At most `10^4` calls.
64+
65+
## Follow-ups
66+
67+
- Bound the memory: what should happen when the fragments held behind a gap pass a limit?
68+
- A retry can ask the relay to resend from a given sequence. How does `missing()` become that request, and when is it worth it over starting again?
69+
- A stream can carry several blocks at once, such as text and the arguments of a tool call. Add a block id. Which state is per block, and which is per stream?
70+
- When a tool call's arguments are fragments of JSON, when is it safe to parse them?
71+
72+
## Hints
73+
74+
### Hint 1
75+
76+
Keep the released fragments in a list, and the next sequence to release is that list's length.
77+
78+
### Hint 2
79+
80+
Ask whether a fragment **is there**, not whether its text is truthy.
81+
82+
### Hint 3
83+
84+
`status` has an order. Work out what a closed stream with every fragment and a `finish` should say.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Stream Reassembler: Explanation
2+
3+
## Overview
4+
5+
| Approach | Role | Time | Space | Use when |
6+
|----------|------|------|-------|----------|
7+
| release-contiguous | optimal | O(1 + r) per delta, O(g) per missing, O(s) per text | O(s) | default answer |
8+
9+
`r` is the number of fragments a delta releases, `g` the distance from the first gap to the highest known sequence, and `s` the size of the stream so far.
10+
11+
## Approach: release-contiguous (Release the contiguous prefix and hold everything above the first gap)
12+
13+
### Intuition
14+
15+
Think of the sequence numbers as seats. Text can be shown only from the front row back, with no empty seat between, so all the state you need is where the first empty seat is, and what has already sat down behind it. The moment that seat fills, everything behind it up to the next empty seat goes out together.
16+
17+
Then there are two separate questions, and many streaming bugs come from answering only one of them. "What may I show now?" is the contiguous prefix. "Is it whole?" needs positive evidence: a `finish` event and every fragment through it. A connection closing is not that evidence. An answer that stops mid-sentence looks a lot like a short answer, and if you store it as complete nobody will notice until a user does.
18+
19+
### Algorithm
20+
21+
1. Keep a list of released fragments, whose length is the next sequence to release, and a map of held fragments above the gap.
22+
2. `delta`: ignore it if the connection has closed, if it is above a recorded last sequence, or if the sequence has arrived already. Otherwise hold it, then move fragments from the map to the list as long as the next sequence is in the map, and return what moved.
23+
3. `finish`: refuse it if the connection has closed, a `finish` is already recorded, or a higher fragment has already arrived. Otherwise record it.
24+
4. `status`: complete when a `finish` is recorded and the list has reached its last sequence. Otherwise it depends on whether the connection has closed.
25+
5. `missing`: from the length of the list up to the last known sequence, every sequence not in the map.
26+
27+
### Correctness
28+
29+
A fragment reaches the list only when its sequence equals the list's length, so `released[i]` is always fragment `i`, and the list is contiguous from 0 by construction. A sequence below the length or in the map has arrived, so the duplicate check needs nothing more and the first text stays. The loop runs until the next sequence is not in the map, so no fragment is ever held while everything before it has arrived. `status` says `"complete"` exactly when the list holds every fragment through the last sequence. `finish` cannot name a last sequence below one that has arrived, so every fragment in the list or map stays in range, and `missing` lists exactly the absent sequences in range: everything below the list's length has arrived.
30+
31+
### Complexity
32+
33+
- Time: O(1 + r) per delta, O(g) per missing, O(s) per text — a delta does map operations and moves `r` fragments, and `missing` walks from the first gap to the end. `finish`, `close` and `status` are O(1).
34+
- Space: O(s) — the fragments, released or held.
35+
36+
### Trade-offs
37+
38+
Sorting all fragments when the stream ends is shorter, but it shows nothing until then, which is the point of streaming, and it gives you no way to say what is safe to show. A min-heap of held fragments would also work, at O(log n) per fragment, and it needs a separate duplicate check, while a map answers both questions at once.
39+
40+
Accepting a `finish` that comes early costs a little state, and the alternative, treating `finish` as the end of everything, silently drops whatever is still in flight on a channel that reorders.
41+
42+
Holding fragments costs memory the sender controls. A real implementation bounds it, and gives up on a stream whose gap does not close in time, which is what the follow-ups ask about.
43+
44+
### Pitfalls and edge cases
45+
46+
- **Appending in arrival order.** It works in every test until the first reorder (`ex1`, `h1`).
47+
- **Treating a closed connection as the end.** A stream that closes with no `finish` is truncated even with no gap at all (`ex3`, `h7`). This is the bug that stores half an answer as a whole one.
48+
- **Treating `finish` as the end.** Fragments can still arrive after it (`ex2`, `h2`).
49+
- **An empty fragment is falsy.** `while held.get(next):` stops at `""`, so the stream sticks forever and the text behind it never comes out (`h3`). Test for presence.
50+
- **Zero and -1 are real values.** `if last_sequence:` skips a stream of one fragment (`h9`), and a stream with no fragments finishes with `-1` (`h10`).
51+
- **Overwriting a held fragment.** A map write makes the last copy win, but only while the fragment is held, so the behaviour depends on timing (`h4`).
52+
- **Assuming the stream starts where the first fragment does.** If fragment 0 never arrives, nothing may be released (`h5`).
53+
- **Showing text beyond a gap.** The text of a truncated stream stops at the first gap (`ex4`, `h6`).
54+
- **Letting events revive a closed stream.** A delta after `close` is ignored, even one that would fill the gap, and a `finish` after `close` is refused (`h8`).
55+
- **`complete` and closing.** A complete stream stays complete when the connection closes (`h11`).
56+
- **Contradicting a `finish`.** A fragment above the last sequence is ignored, a second `finish` is refused, and a `finish` below an arrived fragment is refused (`h12`, `h13`, `h14`).
57+
- **What `missing` can know.** Without a `finish` it can only see gaps below the highest arrival, and it says nothing about what may come after it (`ex3`, `h15`).
58+
- **Editing the text.** Fragments are kept exactly: stripping one loses the space between two words (`h16`).
59+
60+
### Language notes
61+
62+
- Python: `len(self._released) in self._held` is the presence check, and `dict.pop` moves a fragment in one step. `"".join` builds the result without repeated copying.
63+
- TypeScript: `Map.has` is the presence check. `map.get(key)` returns `undefined` for an absent key, which a truthiness test would confuse with `""` in the same way. Strings are UTF-16 here and fragments are joined whole, so a character split across two fragments would still come out right, as long as the relay hands over text and not bytes.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class StreamReassembler:
2+
def __init__(self) -> None:
3+
# released[i] is fragment i, so the next sequence to release is len(released).
4+
self._released: list[str] = []
5+
self._held: dict[int, str] = {}
6+
self._highest_arrived = -1
7+
self._last_sequence: int | None = None
8+
self._closed = False
9+
10+
def delta(self, sequence: int, fragment: str) -> str:
11+
if self._closed or self._is_past_the_end(sequence) or self._has_arrived(sequence):
12+
return ""
13+
self._held[sequence] = fragment
14+
self._highest_arrived = max(self._highest_arrived, sequence)
15+
newly_released = []
16+
while len(self._released) in self._held:
17+
piece = self._held.pop(len(self._released))
18+
self._released.append(piece)
19+
newly_released.append(piece)
20+
return "".join(newly_released)
21+
22+
def finish(self, last_sequence: int) -> bool:
23+
if self._closed or self._last_sequence is not None:
24+
return False
25+
if last_sequence < self._highest_arrived:
26+
return False
27+
self._last_sequence = last_sequence
28+
return True
29+
30+
def close(self) -> None:
31+
self._closed = True
32+
33+
def status(self) -> str:
34+
if self._last_sequence is not None and len(self._released) == self._last_sequence + 1:
35+
return "complete"
36+
return "truncated" if self._closed else "streaming"
37+
38+
def text(self) -> str:
39+
return "".join(self._released)
40+
41+
def missing(self) -> list[int]:
42+
end = self._highest_arrived if self._last_sequence is None else self._last_sequence
43+
return [
44+
sequence
45+
for sequence in range(len(self._released), end + 1)
46+
if sequence not in self._held
47+
]
48+
49+
def _is_past_the_end(self, sequence: int) -> bool:
50+
return self._last_sequence is not None and sequence > self._last_sequence
51+
52+
def _has_arrived(self, sequence: int) -> bool:
53+
return sequence < len(self._released) or sequence in self._held
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
export class StreamReassembler {
2+
// released[i] is fragment i, so the next sequence to release is released.length.
3+
private readonly released: string[] = [];
4+
private readonly held = new Map<number, string>();
5+
private highestArrived = -1;
6+
private lastSequence: number | null = null;
7+
private closed = false;
8+
9+
delta(sequence: number, fragment: string): string {
10+
if (this.closed || this.isPastTheEnd(sequence) || this.hasArrived(sequence)) {
11+
return "";
12+
}
13+
this.held.set(sequence, fragment);
14+
this.highestArrived = Math.max(this.highestArrived, sequence);
15+
let newlyReleased = "";
16+
while (this.held.has(this.released.length)) {
17+
const piece = this.held.get(this.released.length)!;
18+
this.held.delete(this.released.length);
19+
this.released.push(piece);
20+
newlyReleased += piece;
21+
}
22+
return newlyReleased;
23+
}
24+
25+
finish(lastSequence: number): boolean {
26+
if (this.closed || this.lastSequence !== null || lastSequence < this.highestArrived) {
27+
return false;
28+
}
29+
this.lastSequence = lastSequence;
30+
return true;
31+
}
32+
33+
close(): void {
34+
this.closed = true;
35+
}
36+
37+
status(): string {
38+
if (this.lastSequence !== null && this.released.length === this.lastSequence + 1) {
39+
return "complete";
40+
}
41+
return this.closed ? "truncated" : "streaming";
42+
}
43+
44+
text(): string {
45+
return this.released.join("");
46+
}
47+
48+
missing(): number[] {
49+
const end = this.lastSequence ?? this.highestArrived;
50+
const absent: number[] = [];
51+
for (let sequence = this.released.length; sequence <= end; sequence += 1) {
52+
if (!this.held.has(sequence)) {
53+
absent.push(sequence);
54+
}
55+
}
56+
return absent;
57+
}
58+
59+
private isPastTheEnd(sequence: number): boolean {
60+
return this.lastSequence !== null && sequence > this.lastSequence;
61+
}
62+
63+
private hasArrived(sequence: number): boolean {
64+
return sequence < this.released.length || this.held.has(sequence);
65+
}
66+
}

0 commit comments

Comments
 (0)