KatInterview

Extend a Python Abstract Pipeline with a Concrete File Processor

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designabstract-base-classfile-io

Last updated

Implement a concrete subclass inside a pre-built abstract framework that streams CSV input, transforms rows to JSON, and self-registers with a CLI factory.

The Setup

You have been handed a Python codebase you did not write. It defines an abstract pipeline framework with three pieces already in place:

  1. DataProcessor (abstract base class) — declares three abstract hooks: load(self), transform(self, record), and save(self, records). It also owns a concrete run() method that wires those hooks together. You cannot modify this class.
  2. A registry/factory — maps string names to processor classes. The CLI calls something like create_processor("csv_to_json", config).run() to kick off a job.
  3. A CLI entry point — reads a config dict, asks the registry for the right processor by name, and calls run(). You cannot modify the CLI either.

A simplified version of the base class looks like this:

from abc import ABC, abstractmethod

class DataProcessor(ABC):
    def __init__(self, config: dict):
        self.config = config

    def run(self):
        records = (self.transform(r) for r in self.load())
        self.save(records)

    @abstractmethod
    def load(self): ...

    @abstractmethod
    def transform(self, record): ...

    @abstractmethod
    def save(self, records): ...

Your Task

Without touching the base class, the registry implementation, or the CLI, write a concrete CsvToJsonProcessor class that:

  1. Streams the input CSV in fixed-size chunks rather than reading the whole file into memory.
  2. Transforms each row into a normalized JSON object, coercing types and enforcing any required fields listed in the config.
  3. Writes the output as line-delimited JSON (JSONL) to the path specified in the config.
  4. Handles bad rows with a two-pass retry strategy (strict parse, then a lenient fallback), logging rejected rows to a dead-letter file instead of crashing the pipeline.
  5. Registers itself with the factory under the name "csv_to_json" so the CLI can find it with no other changes.

What to Provide

  • The full class implementation (or a thorough outline with all key methods filled in).
  • A clear explanation of how control flows from run() through your hooks, and why the pipeline stays memory-bounded.
  • Your error-handling strategy: what counts as a retryable failure, what goes to the dead-letter file, and what should abort the entire job.

Config Contract

Your constructor should accept at minimum:

KeyTypeDescription
input_pathstrPath to the source CSV
output_pathstrPath to write the JSONL file
chunk_sizeintRows per chunk (default 10 000)
required_fieldslist[str]Fields that must be non-null
max_bad_ratiofloatAbort threshold for bad-row fraction (default 0.05)
dead_letter_pathstrWhere to write rejected rows

Constraints and Edge Cases

  • The input file may be larger than available RAM; never load it all at once.
  • The header row may use inconsistent casing or surrounding whitespace — normalize keys before using them.
  • A row with the wrong column count, an uncoercible value, or a missing required field is a bad row, not a crash.
  • If the bad-row fraction exceeds max_bad_ratio, raise an exception and stop — partial output is worse than no output in this context.
  • The output file should be written atomically (write to a temp file, then rename) so a failed run does not leave a corrupt JSONL file behind.

Hints

Hint 1

Before writing a single line of your subclass, trace what run() actually does. It builds a generator expression over load() and passes it to save(). That means load() must be a generator — if it returns a list, you break the memory-bounded guarantee without any error message to tell you why.

Hint 2

Separate two distinct failure modes: structural CSV errors (broken quoting, NUL bytes) surface inside load() when the csv reader raises csv.Error, while semantic errors (wrong type, missing required field) surface inside transform(). Handle each at the layer where it appears, and keep the generator alive in both cases.

Hint 3

Registration happens at import time. If the module containing your class is never imported, the CLI will raise a KeyError no matter how correctly you wrote the decorator. Make sure the package's __init__.py (or equivalent) imports your module, and mention this when you explain your solution.