You raise the coverage gate to 85%, CI turns green, and two weeks later production fails in the exact branch nobody ever exercised. That gap between “the number looks good” and “the code actually ran” is where most teams develop a complicated relationship with coverage tooling. coverage.py is the de-facto standard behind nearly every Python quality gate, which means its judgment is quietly inherited by your merge checks. The main branch we read for this tour (7.18.0a1.dev at the time of writing, per coverage/version.py) keeps that responsibility in a compact package: 46 files at the top level of coverage/ plus a nine-file C extension under coverage/ctracer/.
Most developers meet the tool as coverage run -m pytest or through the pytest-cov plugin and never look inside. Inside is a genuinely interesting systems problem: intercept every line and branch execution of a live Python process, filter events down to only your code, survive threads, greenlets, and subprocesses, persist measurements in a format that can be merged across parallel CI shards, and finally join runtime truth against static analysis to produce a percentage. Each stage owns a dedicated module with a narrow contract, and the seams between them are unusually legible for a tool this battle-tested.
We read the actual repository tree and traced one full pass: command line to trace function, trace events to SQLite rows, rows to percentages. Every symbol and line number below was verified against the real files, so you can click any reference and see the claim in context.
Overview: the Coverage object mediates between the CLI and config, installs one of three tracer cores through the Collector, filters files with InOrOut, persists arcs and line bitmaps to SQLite, and feeds static analysis into the reporters.
Reading the overview from left to right:
Coverage.start, L679 — the switch that turns measurement on; before it runs,Coverage._initlazily resolves config, plugins, and the tracer core._collectors, L59 — a class-level stack of active collectors, so nested starts (a coverage session inside another session) pause and resume cleanly instead of fighting over the trace function.InOrOut.should_trace, L362 — the per-file verdict function that honorssource,include, andomitmatchers before any line is recorded.Core, L47 — selects one tracer class before anything executes: sys.monitoring, the C extension, or pure Python.CTracer_handle_line, L672 — the C hot path: per-frame data in a preallocated stack, arc pairs recorded with minimal per-event allocation.SysMonitor.sysmon_branch_either, L476 — the sys.monitoring branch callback that makes branch tracing cheap on modern interpreters.CoverageData.add_arcs, L601 — executed arcs land in SQLite keyed by file and context, deduplicated by the schema itself.numbits_union, L68 — merged reports union packed line bitmaps rather than iterating line numbers one by one.
Detail: the full module graph, including the three interchangeable tracer cores, the disposition and path-alias helpers, the SQLite layer with its numbits aggregate, and the five report formats hanging off the shared analysis core.
The Coverage Object: One Start, Many Collectors
Everything user-facing funnels through Coverage in coverage/control.py (the class definition is at L97). Its start() method does not immediately attach a trace function; it runs _init_for_start first, which resolves the data file suffix, patches multiprocessing when requested, and only then builds a Collector. The collector design in coverage/collector.py is the piece most tools get wrong: _collectors is a stack, and start() at L279 pauses the previous top-of-stack collector before pushing itself, so tools that nest coverage sessions behave deterministically. At L312 it calls threading.settrace(self._installation_trace), which routes every new thread through a gate that decides whether the thread’s frames are worth tracing at all.
The collect() context manager (control.py L730) offers scoped measurement for library authors, and combine() (L876) merges the .coverage.<hostname>.<pid>.<random> shards that parallel CI jobs produce into one database. This is the contract that pytest-cov builds on: pytest starts one session-wide Coverage object, and coverage.py handles the messy parts underneath — subprocess startup through process_startup (control.py L1459), thread gates, and the final merge.
Three Tracer Cores, One Contract
Coverage.py must intercept execution, and CPython offers two official hooks for that: the classic sys.settrace protocol and the newer sys.monitoring API. coverage/core.py (class Core, L47) is the policy layer that picks one. It builds a reason_no_sysmon string while checking the requirements (L75–81): the interpreter must expose sys.monitoring, the version must be able to measure branches, dynamic contexts must be supported, and the configured concurrency must be compatible. On CPython 3.14 or newer, env.SYSMON_DEFAULT (env.py L58: CPYTHON and PYVERSION >= (3, 14)) makes sys.monitoring the default core outright. Otherwise the C extension wins if it can be imported (core.py L124), with a warning slug no-ctracer at L108 when it cannot; the pure-Python PyTracer (pytracer.py L61) is the final fallback.
All three implement the same interface, which is why the choice is invisible to callers. PyTracer._trace (pytracer.py L149) is a readable reference implementation of the event loop. The C version, coverage/ctracer/tracer.c, is where the performance lives: CTracer_record_pair (L180) appends a from/to arc pair to per-frame data managed by datastack.c, and CTracer_handle_line (L672) updates the current line and records (last_line, this_line) transitions. The clever detail is the negative line trick at L593: when a frame starts, last_line is seeded to -co_firstlineno, so a return from a function records an arc to a negative number encoding the function’s def line — that is how exits are attributed to the right function without extra bookkeeping.
From Trace Events to SQLite Blobs
The measurement sink is CoverageData in coverage/sqldata.py (L146). Despite the legacy name suggesting a JSON file, modern coverage.py writes a SQLite database; the schema constant sits at L50 as SCHEMA_VERSION = 7, and the inline DDL (L62–121) defines seven tables: coverage_schema, meta, file, context, line_bits, arc, and tracer. Branch mode writes one row per (file_id, context_id, fromno, tono) transition in the arc table (L105–114) with a unique constraint doing the dedup work. Line mode is more surprising: the line_bits table (L94–103) stores every line number for a file/context pair packed into a single numbits blob rather than one row per line.
That blob encoding is its own module, coverage/numbits.py: nums_to_numbits (L27) packs integers into bytes, and register_sqlite_functions (L131) teaches SQLite itself the format by creating the numbits_union_agg aggregate (L166). The payoff shows up during update() (sqldata.py L734) when shards merge: the SQL at L922 unions bitmaps with numbits_union_agg(other_line_bits.numbits) inside the database instead of shipping every line number through Python. sqlitedb.py wraps the connections with transaction handling, and context.py supplies dynamic contexts — the test-name labels you see when running under pytest with contexts enabled — routed through switch_context (control.py L778).
From Hand-Counted Lines to Schema v7
The format history explains several odd-looking constants. Coverage.py predates its SQLite era; early versions wrote JSON, and the migration to a relational store forced the team to version the file format explicitly. Today any schema change must increment SCHEMA_VERSION and update the migration logic in one place — the comment at sqldata.py L47–50 says exactly that, and doc/dbschema.rst generates its documentation from the same constant so the spec cannot drift from the code. The arc model itself was the bigger conceptual jump: from “a set of executed line numbers” to “a set of executed transitions,” where a transition to -(co_firstlineno) means “returned out of this function.” That single convention is what lets the reporters say which branch at the end of a function was missed rather than merely that some line never ran.
Two build facts worth copying. First, the tool measures itself: coverage/numbits.py opens with the pragma # enforce 100% coverage at L17, part of a self-hosting discipline where the coverage of coverage.py is a tested invariant. Second, the codebase is fully type-annotated and ships a py.typed marker (coverage/py.typed), and the repo maintains dedicated requirements/mypy.txt pins — mypy is part of the CI contract, not an afterthought. Recent work follows the same engineering rhythm: a news fragment dated 2026-11-27 records a performance fix making line coverage reports faster when many measurement contexts cover the same file, implemented precisely by keeping those bitmap unions cheap.
Reports, Percentages, and the fail_under Ratchet
Reporting is where runtime data meets static analysis. Analysis (results.py L79) joins the executed sets from CoverageData against the statements and arcs parsed by coverage/parser.py and coverage/bytecode.py, then computes missing_branch_arcs (L151) — the human-readable “line 12 → didn’t jump to 15” explanations — and branch_stats (L184). The aggregate Numbers class (L300) carries pc_covered (L344), the percentage every README badge displays, with statement and branch ratios kept separately so the two can be reported independently.
On top of that sit five output formats: SummaryReporter (report.py L35) renders terminal tables and markdown (report_text L64, report_markdown L129), while Coverage.html_report (control.py L1223), xml_report (L1282), json_report (L1316), and lcov_report (L1354) dispatch to the dedicated modules in the detail diagram. Configuration feeding all of this is resolved by config_files_to_try (config.py L645): an explicit file or COVERAGE_RCFILE (L659) wins, otherwise the search order is .coveragerc, .coveragerc.toml, setup.cfg, tox.ini, and pyproject.toml (L667–673), with TOML tables read through tomlconfig.py. The fail_under setting then turns a passive percentage into an active gate — should_fail_under (results.py L495) handles the precision dance so a 99.5% run against fail_under: 100 fails honestly.
Honest Limits
- sys.monitoring support is version-gated, not universal. The reasons enumerated in
core.py(L75–81) — no branch measurement on some versions, dynamic contexts unsupported — mean a request forcore=sysmoncan downgrade to another core with ano-sysmonwarning rather than silently mis-measuring. - No C extension, no free lunch. When
tracer.ccannot be imported on your platform, theno-ctracerwarning (core.py L108) tells you the pure-Python loop is serving your data, and large suites will feel it. - Concurrency has core-specific ceilings.
Collectorraises aConfigErrorwhen the selected tracer cannot support the requested concurrency like greenlet (collector.py L147–150); threads plus one concurrency plugin is not always a valid combination. - The percentage measures execution, not assertion quality. Covered lines can still assert nothing; mutation testing remains a complementary discipline.
- Merging runs with different settings reconciles what the schema allows:
update()(sqldata.py L734) handles line-versus-arc mismatches, but configurations that disagree about contexts or tracers can still produce combined data that understates what each run knew.
None of these limits diminish the core achievement: a nine-file C extension, three interchangeable tracer cores, and a versioned SQLite format that merges deterministically across CI shards. That is the machinery standing between your 85% gate and the truth — and now you know where each part of it lives, down to the line. Enjoyed this post? Never miss out on future posts by following us