KatInterview

Debug Three Injected Defects in an Open-Source Template Engine

System DesignModel answer
HardModel answerSystem Designdebuggingastpython

Last updated

Track down and fix three bugs in a Python template library: a silent AST visitor gap, a directory/file confusion in template lookup, and comment-only blocks that generate invalid Python.

You are handed a fork of a Python template library — one that compiles templates into Python modules and renders them by calling generated functions. Three defects have been deliberately introduced. Your job is to find each one, apply the smallest correct fix, and add a regression test. Narrate your reasoning as you go.

Library Primer

  • Compilation model. Each template is translated into a Python source file. Rendering means importing that module and calling a function in it.
  • Control lines. A line whose first non-whitespace character is % becomes a Python statement: % if, % for, % elif, % else, % endif, % endfor, etc.
  • Template comments. A line whose first non-whitespace characters are ## is erased at compile time and produces nothing — no Python output, no rendered output.
  • Embedded Python. ${expr} interpolates an expression. Tag attributes such as <%def name="greet(name, punct='!')"> declare callables whose signatures are real Python syntax. The library parses those signatures with the standard ast module and walks the resulting trees with ast.NodeVisitor subclasses.
  • Template lookup. A TemplateLookup is initialised with an ordered list of directories. Given a template name like /emails/welcome.txt it searches each directory in turn, resolves the path, checks that a file exists there, and returns it.

Constraints

  • There are exactly three defects, one per Part below.
  • Each fix should be minimal and local — match the surrounding code style and do not alter any behavior that is currently correct.
  • Part 1 names the missing code and asks you to explain consequences. Parts 2 and 3 describe a symptom and ask you to trace it to its cause.
  • When all three fixes are applied the full existing test suite must pass.

Useful Clarifying Questions to Consider

  • Do existing failing tests map one-to-one onto the defects, or must some be discovered from symptoms?
  • Which Python versions must be supported? AST node types change across releases (e.g., ast.arg was introduced in Python 3; keyword-only args, positional-only args, and type annotations each add their own nodes).
  • When one lookup directory contains a folder named emails and a later directory contains a file named emails, which one should win — and what should happen when neither directory contains a file?
  • Should a control block whose entire body consists of comment lines behave identically to a genuinely empty block, for every control form (if, else, elif, for, while, nested blocks)?

Part 1 — Silent gap in the AST argument visitor

One ast.NodeVisitor subclass in the library is missing its visit_arg method.

  1. Explain exactly which Python constructs cause the ast module to emit ast.arg nodes.
  2. Describe how ast.NodeVisitor dispatches: what it does when it encounters a node type for which no visit_* method exists, and why this particular gap does not raise an exception.
  3. Explain the concrete job this visitor is doing (e.g., collecting names, checking for conflicts) and how that job goes wrong when argument nodes are silently skipped.
  4. Restore the missing method and write at least one test that would have caught the removal — both a unit test against the visitor directly and a template-level integration test.

Focus areas: visitor dispatch mechanics, every parameter kind that produces ast.arg nodes (positional, default, keyword-only, *args, **kwargs, positional-only, annotated), the silent failure mode, and test design.


Part 2 — Directory path mistaken for a template file

When a template name resolves to a directory rather than a file inside one of the lookup directories, the library raises a low-level OS error (something like IsADirectoryError or a permission error, depending on platform) instead of its own "template not found" error.

  1. Find the predicate that decides whether a resolved path is a valid template file, and show exactly what it currently checks vs. what it should check.
  2. Trace the behavior across multiple lookup directories: a directory that should be skipped, a later directory that contains the real file, and the case where no directory contains a matching file.
  3. Describe at least one alternative fix and explain why your chosen fix is preferable (think: clarity, portability, behavior on edge cases).
  4. Write tests that construct a temporary directory tree, place a folder and a file at the relevant paths, and assert the correct outcome for each scenario.

Focus areas: os.path predicates, lookup ordering, the library's own "not found" exception type, and temporary-directory test setup.


Part 3 — Control block whose body is only comments fails to compile

The following template is semantically valid — the comment is intentional and the block should simply produce no output — but compiling it raises a SyntaxError inside the generated Python module:

% if show_banner:
    ## banner removed until the redesign ships
% endif
Welcome
  1. Show what Python source the code generator emits for this template, and explain why it is syntactically invalid.
  2. Find the place in the generator where it decides to insert a pass statement into an otherwise-empty block, and identify which node types it already treats as "producing no content" and which type it is missing.
  3. Identify every other control form that the same omission breaks: % else branches with only comments, % elif branches, % for loops, nested % if blocks, etc.
  4. Fix the generator and add template-level tests that compile and render each affected control form.

Focus areas: Python block syntax requirements, how the template compiler represents comment nodes vs. text nodes vs. statement nodes, and the precise condition that gates pass insertion.

Hints

Hint 1

For Part 1, print out what ast.parse produces for a function signature like `def f(a, b=1, *args, kw_only=2, **kwargs)` and trace each node type the visitor would encounter. Then check what generic_visit does — and what it doesn't do — to see why nothing blows up.

Hint 2

For Part 2, `os.path.isfile` is the key predicate: it returns False for directories and for paths that don't exist, so replacing an existence check with `isfile` simultaneously handles the directory case and the missing-file case in one go.

Hint 3

For Part 3, look at the generated Python source directly (most template libraries expose a way to dump it) for a block containing only a comment line. A Python `if` body cannot be empty — it needs at least one statement — so look for the `pass`-insertion logic and check which internal node types it counts as 'empty'.