KatInterview

Chunk-Safe Tokenizer for Fenced Code Blocks

StringsModel answer
HardModel answerStringsstreamingstate-machinestring-parsing

Last 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 \n or 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 final code_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.