The setup

A research application on an always-on machine. SQLite in write-ahead log mode, one file. A web process that serves the API and the pages. A handful of scheduled jobs, written as separate Python scripts, that open the same file: an hourly sync, a nightly reconcile, a few batch back-fills. This arrangement ran for most of a year without a complaint, which is the first thing to know about both bugs. Nothing was wrong until something crossed a line.

Bug one: the connection that never closed

The symptom. A batch job died with OSError: [Errno 24] Too many open files inside a directory listing, and a few lines earlier, unable to open database file from SQLite. Two messages, one cause: the process had run out of file descriptors, SQLite noticed first, and the directory listing noticed second.

The trap. Python's sqlite3 connection is a context manager, and with conn: looks like it cleans up. It does not. On exit it commits or rolls back the transaction and leaves the connection open. The object then survives on a reference cycle until the cyclic garbage collector gets around to it. In write-ahead log mode every live connection holds two descriptors, one for the database and one for the -wal file. I measured it: one read left seven descriptors open, fifty reads left 105, and a forced gc.collect() dropped the count back to four. The machine's per-process limit was 256, so about 125 reads in one pass would exhaust it.

Why it appeared with no code change. The script had not been touched in a month. The data had grown. One scan finally crossed 125 reads, and the job that had always worked stopped working. When a stable program fails, ask what threshold moved before asking what code changed.

Why the web process never showed it. A long-running server allocates constantly, so the cyclic collector runs all the time and mops up the leaked connections before they pile up. A short batch script that does 125 reads and exits never triggers a collection. Same bug in the same library; only the batch job dies.

The fix. A connection subclass whose exit closes, installed through the factory argument, so every one of the 120 with blocks in the codebase got the behaviour without editing any of them.

import sqlite3

class _Conn(sqlite3.Connection):
    """A connection whose `with` block really closes it."""

    def __exit__(self, exc_type, exc, tb):
        try:
            return super().__exit__(exc_type, exc, tb)   # commit or roll back
        finally:
            self.close()

def get_conn(path):
    return sqlite3.connect(path, factory=_Conn)

This is safe only if no caller uses the connection after its with block ends. I verified that across the codebase before shipping, by parsing each enclosing function rather than grepping a window of lines around each call. A windowed grep had earlier told me ten more sites leaked, and it was wrong: their closes sat further down than the window reached. Read the whole function.

The diagnostic. Count len(os.listdir("/dev/fd")) before and after a loop, then call gc.collect() and count again. If the number collapses, the descriptors belonged to unreachable garbage, not to anything legitimately open.

Bug two: the second process that never let go

The symptom. One evening the uptime watchdog started mailing DOWN and RECOVERED every few minutes. The web process had not restarted. Its health endpoint was taking eighteen seconds and returning a 500 about half the time. Eighteen is three queries multiplied by Python's default five-second busy timeout, which told me the database was locked before I looked at anything else.

The cause. The hourly job opened the same write-ahead log database from a second process and had been sitting for two hours in the shared-memory lock, in a state the process table shows as U, an uninterruptible wait. Worse, the web process itself had a thread permanently retrying the same lock since an unclean restart the day before, and had written nothing to its own log for thirty-six hours. Nobody noticed, because a quiet log looks exactly like a healthy one.

The diagnosis. Two commands. ps -o pid,stat,command to find a Python process touching the database with state U, and a stack sample of that process showing walTryBeginRead and unixLockSharedMemory at the top. Killing the stuck job dropped the health endpoint from eighteen seconds to forty milliseconds instantly. A clean restart of the web process took four attempts because the next hourly run, on the old code, grabbed the lock again in between. Kill, restart, and only then fix.

The fix. One process owns the file. The hourly job no longer spawns its own Python against the database; it calls an endpoint on the web process, which runs the same sync in-process with a long timeout. The remaining out-of-process readers opened with an explicit timeout= and a wall-clock guard, so a lock they cannot get becomes an error in a log instead of a two-hour wait. Write-ahead log mode is excellent for one process with many threads. It is merely tolerable for many processes on one file, and on an external volume after an unclean shutdown it is fragile. The documentation says as much; the incident made me read it.

The second lesson. Silence is a symptom. The watchdog checked whether the health endpoint answered. It did not check whether the application had logged anything in the last hour, and that would have caught the degraded state a day earlier. The check on the log file's modification time took ten minutes to add.

What they have in common

  • Every test passed. Both failures needed production time and production volume.
  • Neither fix was more than a few lines. Both diagnoses took an evening.
  • Each had a cheap, decisive measurement: count descriptors and force a collection; read the process state and sample the stack.
  • Each was in a library behaviour that is documented and easy to assume the other way: with does not close, and one file does not want two writers.
  • Each left a monitoring gap behind it that was worth more than the fix: watch the threshold, and watch the silence.