A diagnostic black box preserves recent execution evidence so a failure can be investigated after it happens.
Combine bounded history, structured logging and careful failure reporting without replacing the original error.
A failed overnight run leaves only its final exception. The useful evidence may be the few events immediately before it. Combine a bounded event buffer with failure classification and cleanup, then rehearse repeated runs to ensure the recorder itself does not mix their histories.

Keep only the last few lines of a run
A list you trim by hand works; the standard library already has the exact
structure. A deque with a maxlen drops the oldest item the moment a new
one arrives:
from collections import deque
box = deque(["started"], maxlen=2)
box.append("line 0")
box.append("line 1")
box.appendleft("again")
print(list(box))For the black box that means appending on the right and never thinking about size again — the buffer always holds exactly the most recent stretch.
Preparing this topic’s interactive investigation…
Give the box everything, the console only what matters
In lesson 2 you wrote ListHandler, which kept every formatted line. The
black box is the same idea with a bounded memory — and because it's a
handler, the pipeline doesn't know it exists. The console gets WARNING
and up; the box gets everything:
The console showed one line; the box holds the last three records at every level. Nobody wants to read the DEBUG lines of a successful run — but after a failure, those are exactly the lines that say what was going on. A handler's level can only narrow what reaches it, never widen it:
import logging
log = logging.getLogger("quarry.bb2")
log.handlers.clear()
log.propagate = False
log.setLevel(logging.WARNING)
seen = []
class Keep(logging.Handler):
def emit(self, record):
seen.append(record.levelname)
log.addHandler(Keep(logging.DEBUG))
log.debug("line 0")
log.warning("line 0 skipped")
print(seen)That's why run_safely sets the quarry logger to DEBUG before attaching
the box, and relies on each handler's level to decide who hears what.
Sort a crash from an anticipated failure, in the right order
run_safely is the outer boundary that catches ordinary Exception subclasses, because it
doesn't swallow anything — it turns the exception into a report. The order
of the clauses still matters, the same rule as lesson 1:
A broken source is an anticipated failure, not a crash — but it's being reported as "crashed". Fix the handler so a QuarryError is "failed" and anything else is "crashed".
In run_safely you can use either shape: two clauses in the right order,
or one except Exception as exc: followed by isinstance(exc, QuarryError)
— the second keeps the report-building code in one place.
The report also names the function the exception was raised in, found by
walking the traceback: exc.__traceback__ starts at the frame that caught
it, and each tb_next steps one call deeper to the innermost frame:
The first name is <module>, where the try ran; the last is
summarise, where the division happened — run_safely wants only that
last one. The cause chain is the lesson-1 loop: follow __cause__, or
__context__ when it isn't suppressed, until nothing is left.
Read a report the way you'd read it at 09:00: status crashed, so it's a
bug, not bad data; raised in summarise; the recorder shows both rows were
skipped just before. The fix isn't in summarise's arithmetic — it's
deciding what a batch with no good rows should report.
Preserve the original failure when reporting also fails
The black box is a composition of several earlier contracts: a deque limits retained history, logger routing decides which records enter it, exception types select a policy, traceback frames locate the failure, and finally releases the handler. Test these responsibilities independently before trusting the combined report.
A bounded number of records is not necessarily bounded memory in bytes. Ten records each containing a megabyte-sized message still retain substantial data. Limit individual event size and avoid raw request bodies. Tracebacks can retain entire local object graphs while you hold references to them; extract the needed diagnostic facts and release those references when finished.
Reporting itself can fail: formatting a custom exception may call a broken __str__, a handler may fail to write, and a storage destination may be unavailable. A production boundary should have a minimal fallback that preserves the original exception type and a non-success outcome. It should never convert “could not build the crash report” into “pipeline succeeded”. The provided exercise uses simple exception classes to keep the focus on classification.
Failure rehearsal: run a successful batch, a known SourceError, and an unexpected programming error in the same process. After each, inspect the handler count and ensure later runs do not append to earlier reports. Then use a buffer of size two and produce four events: name exactly which two should remain and what context is lost. The recorder supports diagnosis; it cannot reconstruct events that were never logged or were already evicted.
For transfer, decide whether cancellation should be reported as failure or allowed to stop the supervisor. Do not catch BaseException merely to keep a report alive: KeyboardInterrupt, SystemExit and async cancellation have lifecycle meanings beyond an ordinary bad row.
References: logging behavior and traceback objects.
Traps worth knowing
Detach in finally. A return inside except still runs finally
first, so one cleanup line covers success, failure and crash alike.
Copy the buffer out — list(box.records) — because the deque itself
belongs to a handler that's about to be detached. Keep report construction small: even formatting or storing diagnostic
information can fail. Preserve the original failure and have a minimal
fallback rather than assuming the reporting path cannot raise. Check the happy path too: a clean run returns "ok" and an empty
dump — the box is only opened after an accident.
Quick practice
from collections import deque
log = deque(maxlen=2)
for word in ["open", "read", "parse", "close"]:
log.append(word)
print(list(log))class QuarryError(Exception): pass
def outcome(exc):
try:
if exc:
raise exc
except QuarryError:
return "failed"
except Exception:
return "crashed"
return "ok"
print(outcome(None), outcome(QuarryError("x")), outcome(KeyError("y")))The box should be marked detached whichever way run_once leaves — right now a failing run skips it entirely, because the return inside except exits before that line runs.
🎯 Your turn
Build run_safely(lines). The starter holds Quarry's errors and its
pipeline: run(lines) logs through quarry.yard and quarry.vault, skips
bad rows with a warning, and lets a SourceError, a bug or a failed summary
escape. Finish BlackBox.emit, cause_chain and innermost, then:
- Get the
quarrylogger, set it toDEBUG, and attach aBlackBox(BOX_SIZE)formatted withFORMAT. - Call
run(lines). On success return{"status": "ok", "result": <run's result>, "error": None, "chain": [], "where": None, "dump": []}. - If it raises, return
"failed"for aQuarryErroror"crashed"otherwise, with"result": None, the class name,cause_chain(exc),innermost(exc)andlist(box.records)as the dump. - Detach the box on every way out.
run_safely(["id=a;ms=100", "", "id=c;ms=3"])
# → {"status": "failed", "result": None, "error": "SourceError",
# "chain": ["SourceError"], "where": "load_row",
# "dump": ["INFO quarry.yard: run started: 3 lines",
# "DEBUG quarry.yard: line 0: 'id=a;ms=100'",
# "DEBUG quarry.yard: line 1: ''"]}Press ▶ Run and hit ✓ Check. When it's green, the black box is done: a crash at 03:12 leaves an answer, not a mystery. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write ring(items, size): feed items one by one into a buffer that holds at most size things, dropping the oldest when full, and return what's left as a list, oldest first.
The starter defines Quarry's error classes and lookup(name), which returns a Quarry class or a builtin exception class by name. Write policy(name): "skip" for a BadRowError, "retry" for a SourceTimeout, "stop" for any other SourceError, "abort" for any other QuarryError, and "crash" for anything else. Subclasses count.
A black box that records everything will record secrets too. Complete the Redact filter so every record's final message has the value after token= or password= (up to the next & or whitespace) replaced with ***. Then write redacted(events): log each [level, template, args] through the logger "quarry.fetch" at DEBUG, with a ListHandler that carries the filter, remove the handler afterwards, and return the captured lines.
Using Quarry's pipeline in the starter, write crash_report(lines): call run(lines); if it raises, return {"error": class name, "frames": [function names from run inward], "line": the value of run's local variable i, or None if it has none}. If nothing is raised, return {"error": None, "frames": [], "line": None}.
Write supervise(batches): batches maps a batch name to its lines. Attach the starter's Collect handler (it keeps WARNING and above) to the "quarry" logger set to DEBUG. Run every batch with run, in order, each in its own try: a QuarryError makes the batch "failed" and is logged by "quarry.supervisor" as error("batch %s failed: %s", name, exc); any other exception makes it "crashed", logged with exception("batch %s crashed", name); otherwise it is "ok". One bad batch never stops the rest. Remove the handler at the end and return {"results": {name: status}, "log": lines}.
The black box records DEBUG and above in memory, but Quarry's console shows only WARNING and above, and the box's contents are only written out when a run fails. Explain why that split makes sense, and what could go wrong if you simply logged everything at DEBUG to the console instead.