KatInterview

Audited Lazy File Streaming with Generators, Decorators and with

Data Structure DesignModel answer
MediumModel answerData Structure Designpythongeneratorsdecorators

Last updated

Build a decorator that audits a chunked file-reading generator's lifecycle, with deterministic file cleanup on completion, early exit, errors and garbage collection.

Background

A service that scans very large log dumps must neither load them whole into memory nor leak open file descriptors. Python offers three tools that cover this between them:

  • Generators produce values on demand and can be stopped early with close() or throw().
  • Context managers (__enter__ / __exit__, or the with statement) guarantee that cleanup code runs.
  • Decorators wrap a callable to add behaviour without editing its body.

Task

Write a small, audited streaming reader that uses all three.

1. track_stream(metrics: dict)

A decorator factory for generator functions. The wrapped function must still behave as a lazy generator (never collect results into a list), and it must update the shared metrics dictionary as follows:

  • metrics['active_streams'] goes up by one as soon as the generator object is created, before any next() call.
  • metrics['active_streams'] goes down by one when the stream ends, whether through normal exhaustion, early close by the consumer, or an exception.
  • metrics['total_yields'] goes up by one for each item delivered.
  • metrics['exceptions'] goes up by one when an unhandled exception ends the stream. GeneratorExit (an ordinary early exit) must not be counted.

2. stream_chunks(file_path: str, chunk_size: int = 1024)

A generator decorated with @track_stream(metrics) that yields successive pieces of the file, each at most chunk_size characters long. The file must be closed promptly however the generator ends: exhaustion, break, close(), an error, or garbage collection.

from typing import Callable, Generator

def track_stream(metrics: dict) -> Callable: ...
def stream_chunks(file_path: str, chunk_size: int = 1024) -> Generator[str, None, None]: ...

Example

metrics = {'active_streams': 0, 'total_yields': 0, 'exceptions': 0}

# 'access.log' holds 2500 characters
g = stream_chunks('access.log', chunk_size=1000)
assert metrics['active_streams'] == 1      # counted before iteration starts

first = next(g)
assert len(first) == 1000
assert metrics['total_yields'] == 1

g.close()                                  # early exit
assert metrics['active_streams'] == 0

Constraints and edge cases

  • Never read the whole file into memory at once.
  • A consumer break must be handled cleanly and must not be recorded as an exception.
  • The file must be closed even if an error occurs mid-stream.
  • Several consumers may run at the same time, and the counters must stay accurate.

What to deliver

Explain your design, justify how each termination path is handled, state complexity, list the edge cases you considered, and give working code.

Hints

Hint 1

Write the naive version first: a wrapper that is itself a generator function with try/finally. Then check what happens when you create it and call close() without ever calling next(). When does its body first run?

Hint 2

To count at creation time you must return an object immediately, not a generator that has not started. Consider a small class that subclasses collections.abc.Generator, holds the real generator, and forwards send, throw and close to it.

Hint 3

Make the 'finish' step idempotent and protect counter updates with a lock. Put the file inside a with block in the inner generator so every unwinding path (return, exception, GeneratorExit) closes it. Remember that an exception in a consumer's for-loop body is invisible to the generator.