#69 · Errors and security

Find the bug · #69 · Errors and security Medium Python

After a bad row, the file stays locked

After an import fails on a bad row, the file can’t be deleted or re-uploaded.

On this page

The report

Bug report

When an import file has a bad row, the import fails, which is expected. But afterwards the file can’t be deleted or replaced (“file in use”), and after enough failed imports the server runs out of file handles.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def import_rows(path, opener, parse):
    """Reads and parses every row of an import file."""
    f = opener(path)
    rows = [parse(line) for line in f]
    f.close()
    return rows

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
class FakeFile:
    """Stands in for an open file, and remembers whether it was closed."""
    def __init__(self, lines):
        self.lines, self.closed = lines, False
    def __iter__(self):
        return iter(self.lines)
    def __enter__(self):
        return self
    def __exit__(self, *exc):
        self.closed = True
    def close(self):
        self.closed = True

files = []
def opener(path):
    files.append(FakeFile(["1,Asha", "oops", "3,Meera"]))
    return files[-1]

def parse(line):
    num, name = line.split(",")
    return int(num), name

try:
    import_rows("users.csv", opener, parse)
except ValueError as e:
    print("import failed:", e)
print("file closed:", files[0].closed)

It prints

import failed: not enough values to unpack (expected 2, got 1)
file closed: False

It should print

import failed: not enough values to unpack (expected 2, got 1)
file closed: True
Show the answer: the bug, the fix, and how you’d find it

The bug (lines 3, 5)

Line 3 opens the file and line 5 closes it, but if parsing fails on line 4 the exception jumps straight out of the function and line 5 never runs. The file stays open, locked on some systems, and each failed import leaks one more file handle. A with block closes the file however the block ends.

The fix

1def import_rows(path, opener, parse):2    """Reads and parses every row of an import file."""3    f = opener(path)4    rows = [parse(line) for line in f]5    f.close()6    return rows3    with opener(path) as f:4        return [parse(line) for line in f]

How you’d find it

  1. Reproduce with a file that has a bad row, then check whether the file was closed: it wasn’t.
  2. With a good file it is closed, so the leak only happens on the error path. Follow it: the exception skips line 5.
  3. Any clean-up that sits after code that can fail has the same problem. Python’s answer is with (or try/finally).

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

class FakeFile:
    def __init__(self, lines):
        self.lines, self.closed = lines, False
    def __iter__(self):
        return iter(self.lines)
    def __enter__(self):
        return self
    def __exit__(self, *exc):
        self.closed = True
    def close(self):
        self.closed = True

opened = []
def opener(path):
    opened.append(FakeFile(["bad"]))
    return opened[-1]

try:
    import_rows("x.csv", opener, lambda line: int(line))
except ValueError:
    pass
assert opened[0].closed

Where else this bites

  • Database connections and locks released only on success.
  • Java’s try-with-resources and C#’s using exist for exactly this.
Your progress stays on this device.