Workspace/Coding labs
Loading progress

Fold a stream without inventing completion

Intermediate60 min

Implement fold_stream(events, max_chars), a deterministic reducer for a normalized single-text application stream. Preserve partial text and distinguish completed, failed, and incomplete runs.

Your task

  1. Accept a list of event dictionaries with contiguous exact integer seq values starting at zero. This is a teaching application envelope, not the provider’s raw wire format.
  2. Support exactly text_delta with keys seq,type,text; completed with keys seq,type; and error with keys seq,type,message. Require text and message to be strings.
  3. Append text fragments in order, rejecting any fragment that would make accumulated text longer than max_chars. max_chars must be a nonnegative exact integer.
  4. Return status completed on a completed event, failed on error, or incomplete if no terminal event arrives. Always return text and error, with error None except for failed status.
  5. Reject unknown types, malformed shapes, sequence gaps, and any event after a terminal event with ValueError.

Examples

EXAMPLE 1

Input[{"seq":0,"type":"text_delta","text":"Hi"}]

Output{"status":"incomplete","text":"Hi","error":null}

Text alone is not terminal evidence.
EXAMPLE 2

Input[{"seq":0,"type":"completed"}]

Output{"status":"completed","text":"","error":null}

Lifecycle completion and nonempty answer quality are separate checks.
solution.pyPython 3.12