Fold a stream without inventing completion
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
- 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.
- 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.
- 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.
- 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.
- 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}
EXAMPLE 2
Input[{"seq":0,"type":"completed"}]
Output{"status":"completed","text":"","error":null}
Implement the function, then run the tests.
Ctrl / ⌘ + Enter to test · Shift + Tab leaves editor