Chunk-Safe Tokenizer for Fenced Code Blocks
StringsModel answerLast updated
Design a stateful tokenizer that turns arbitrarily chunked Markdown into text and code-block events, correctly handling fences split across chunk boundaries.
Chunk-Safe Tokenizer for Fenced Code Blocks
A chat interface receives an assistant's reply in small pieces and wants to render fenced code blocks (with a language label) as early as possible. It must not flicker or misread a fence whose characters arrive in separate chunks.
Implement StreamingCodeFenceParser. It accepts text chunks of any size, from a single character to a whole document, and returns lists of event dictionaries.
Fence rules
Opening fence
- It begins at the very start of the stream or immediately after a
\n. - It may be indented by 0 to 3 spaces, which are ignored.
- It is a run of 3 or more identical characters, all backticks or all tildes. The two cannot be mixed.
- The rest of that line, trimmed of surrounding whitespace, is the info string (the language). It is
""if empty. - For a backtick fence, the info string must not contain a backtick. If it does, the line is ordinary text.
Code body
- Everything after the opening line's newline, up to the closing fence.
Closing fence
- It begins a line, with 0 to 3 leading spaces.
- It uses the same character as the opener, repeated at least as many times.
- Only spaces may follow it before
\nor the end of the stream. Any other trailing text makes the line code content.
Plain text
- Everything outside a code block.
Interface
class StreamingCodeFenceParser:
def __init__(self): ...
def feed(self, chunk: str) -> list[dict]: ...
def flush(self) -> list[dict]: ... # end of stream
Events
{"type": "text", "content": str}: non-code text, emitted once it can no longer be part of a fence.{"type": "code_start", "language": str}: the opening line is fully resolved.{"type": "code_chunk", "content": str}: code body content.{"type": "code_end"}: a valid closing fence is confirmed.
Requirements
- The concatenated result must not depend on how the input is split into chunks.
- A fence of the other character never closes a block (
~~~does not close a backtick block). - Emit as early as possible, but never commit to something a later character could change. A line-initial
`or```must wait for more input. - A fence line consumes its newline, so that newline appears in no event.
- At
flush(), a pending line that is already a complete fence is treated as if a newline had arrived. If a block is still open afterwards, emit a finalcode_end.
Examples
p = StreamingCodeFenceParser()
p.feed("Here is code:\n```py")
# [{"type": "text", "content": "Here is code:\n"}]
p.feed("thon\nprint(1)\n```\nDone")
# [{"type": "code_start", "language": "python"},
# {"type": "code_chunk", "content": "print(1)\n"},
# {"type": "code_end"},
# {"type": "text", "content": "Done"}]
p = StreamingCodeFenceParser()
p.feed("``") # []
p.feed("`\nhello\n```")
# [{"type": "code_start", "language": ""},
# {"type": "code_chunk", "content": "hello\n"}]
p.flush() # [{"type": "code_end"}]
Explain your design, state its complexity, and give working code.
Hints
Hint 1
Fences only matter at the start of a line, so make one decision per line: can this line still become a fence? Once the answer is no, stop buffering and pass the rest of the line straight through.
Hint 2
Keep a small scanner for the buffered line with three phases: indentation (at most 3 spaces), the run of fence characters, and the tail (the info string for an opener, spaces only for a closer). Reject the line the moment any rule is broken and release the buffer as text or code depending on the mode.
Hint 3
Store all scanner state on the object so chunk boundaries cannot matter. In flush(), check whether the buffered line is already a complete fence (run long enough) and, if so, commit it as if a newline had arrived. Merge adjacent content events so the output does not depend on chunking.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Fences are line-oriented. A backtick in the middle of a line is never a fence, so the parser asks one question per line: can this line still be a fence?
- If no, release the buffered prefix immediately as
textorcode_chunk(depending on the mode). Then stream the rest of the line through without buffering, using a bulkfind("\n")and a slice. - If yes, keep buffering. At
\n(or at flush) the line becomes a structural event.
State
- Mode: outside or inside a block. Inside, remember the opener's character and run length.
- Candidate buffer: the characters of the current line so far.
Nonemeans the line is already known not to be a fence. - Scanner phase for the candidate:
indent: up to 3 spaces. A 4th space rejects the line.run: repeated fence characters. Outside a block the first one may be`or~. Inside a block it must be the opener's character.tail: entered once the run ends with enough characters (3 for an opener, at least the opener's length for a closer). For an opener, any character is allowed except a backtick in a backtick fence. For a closer, only spaces are allowed.
A run that ends too short, a wrong character, an illegal tail character, or a newline before the fence is complete all reject the line.
On \n in the tail, an opener produces code_start with the trimmed info string, and a closer produces code_end. The newline is consumed.
On rejection, emit the buffer plus the offending character. If that character was \n, a fresh candidate line starts immediately.
Flush
- If the pending line is already a complete fence (phase
tail, or phaserunwith a long enough run), commit it as though\nhad arrived. This is what closes Example 2. - Otherwise release the buffer as ordinary content.
- If a block is still open, emit a synthetic
code_end. A complete opener at end of stream therefore yieldscode_startthencode_end. - Reset the state so the parser can be reused.
Why it is correct
- No lost or reordered characters. Everything buffered is a viable fence prefix. When viability ends, it is released verbatim before any newer character.
- Chunk independence. Each character's handling depends only on the state built from earlier characters, and that state persists across
feedcalls. - Closing rules. Inside a block the only accepted run character is the opener's, and the minimum length is the opener's length. So
~~~cannot close a backtick block, a shorter run is code, a longer run closes, and trailing text makes the line code. - Earliest emission.
Doneis released atD. A lone`or```at line start stays buffered because the next character decides its meaning.
Code
class StreamingCodeFenceParser:
def __init__(self):
self._in_code = False
self._fence_char = ""
self._fence_len = 0
self._events = []
self._acc = []
self._acc_type = None
self._start_line()
# ----- line scanner -----
def _start_line(self):
self._cand = [] # None => not a fence candidate
self._phase = "indent"
self._indent = 0
self._run_char = ""
self._run_len = 0
self._info = []
def _min_run(self):
return self._fence_len if self._in_code else 3
def _allowed(self):
return self._fence_char if self._in_code else "`~"
# ----- emission (adjacent content is merged) -----
def _emit_content(self, s):
if not s:
return
t = "code_chunk" if self._in_code else "text"
if self._acc_type != t:
self._flush_acc()
self._acc_type = t
self._acc.append(s)
def _flush_acc(self):
if self._acc:
self._events.append(
{"type": self._acc_type, "content": "".join(self._acc)})
self._acc, self._acc_type = [], None
def _emit_event(self, ev):
self._flush_acc()
self._events.append(ev)
def _take(self):
self._flush_acc()
out, self._events = self._events, []
return out
# ----- fence resolution -----
def _reject(self, ch):
self._emit_content("".join(self._cand) + ch)
if ch == "\n":
self._start_line()
else:
self._cand = None
def _commit(self):
if self._in_code:
self._emit_event({"type": "code_end"})
self._in_code = False
else:
lang = "".join(self._info).strip()
self._emit_event({"type": "code_start", "language": lang})
self._in_code = True
self._fence_char = self._run_char
self._fence_len = self._run_len
self._start_line()
def _step(self, ch):
p = self._phase
if p == "indent":
if ch == " ":
if self._indent == 3:
return self._reject(ch)
self._indent += 1
self._cand.append(ch)
elif ch in self._allowed():
self._phase = "run"
self._run_char = ch
self._run_len = 1
self._cand.append(ch)
else:
self._reject(ch)
elif p == "run":
if ch == self._run_char:
self._run_len += 1
self._cand.append(ch)
elif self._run_len < self._min_run():
self._reject(ch)
else:
self._phase = "tail"
self._step(ch)
else: # tail
if ch == "\n":
self._commit()
elif self._in_code:
if ch == " ":
self._cand.append(ch)
else:
self._reject(ch)
elif ch == "`" and self._run_char == "`":
self._reject(ch)
else:
self._info.append(ch)
self._cand.append(ch)
# ----- public API -----
def feed(self, chunk):
i, n = 0, len(chunk)
while i < n:
if self._cand is None:
j = chunk.find("\n", i)
if j == -1:
self._emit_content(chunk[i:])
i = n
else:
self._emit_content(chunk[i:j + 1])
self._start_line()
i = j + 1
else:
self._step(chunk[i])
i += 1
return self._take()
def flush(self):
if self._cand:
complete = self._phase == "tail" or (
self._phase == "run" and self._run_len >= self._min_run())
if complete:
self._commit()
else:
self._emit_content("".join(self._cand))
if self._in_code:
self._emit_event({"type": "code_end"})
out = self._take()
self.__init__()
return out
Complexity
- Time: O(n) over the whole stream. Non-candidate lines are handled with
findand slicing, and only candidate-line characters go through_step, each exactly once. - Space: O(L), where L is the length of the current candidate line. Output is built with list joins.
Edge cases and common mistakes
- Splitting a fence at every possible position, such as
`,,``` ``,\n. Test by feeding one character at a time and comparing with a single large feed. - 3 leading spaces are accepted. 4 are not.
- Mixed
`~is rejected. - A backtick in a backtick info string rejects the line. In a tilde info string it is allowed.
- Closers: a shorter run is code, a longer run closes, trailing spaces are fine, trailing text makes it code, and a different character makes it code.
- Closer at end of stream without a newline (Example 2).
- Unclosed block at end of stream, and two blocks back to back.
- Common mistakes: examining backticks mid-line, forgetting to emit buffered characters on rejection, emitting the fence's newline as text, and returning unmerged one-character events whose shape depends on the chunking.