Closing SD Card Files Before CircuitPython Resets the Bus
How Adafruit's merged PR #12017 preserves writes by closing flagged FAT files while the SD-card bus is still available.

When CircuitPython stops with an SD-card file still open, its last buffered writes can be lost if shutdown resets the card's bus before closing the file. A merged change in Adafruit CircuitPython moves selected FAT-file finalizers earlier in shutdown.
Adafruit CircuitPython PR #12017 was authored by @mikeysklar and merged by @dhalbert on December 3, 2026. It closes a class of files before the storage hardware is reset. The implementation is a scoped ordering rule, not a general sort of all object finalizers.
The shutdown-ordering problem
Issue #11562 describes a CircuitPython program writing to a FAT-formatted SD card. It periodically calls flush(), but leaves the file open when code.py stops. Lines written after the last flush may disappear, and a new file that was never flushed may not appear on the card.
The failure is about teardown order. Closing a file writes its buffered data through the SD-card driver. That operation needs the card and its SPI bus to remain usable. Before the fix, VM shutdown could reset the bus before the file's finalizer called close(). Garbage-collection finalizer order also did not guarantee that the file would close before its SDCard object.
The issue's example makes the timing visible:
log = open("/sd/LOG.TXT", "a")
i = 0
while True:
log.write(f"line {i}\n")
if i % 100 == 0:
log.flush()
i += 1
The file remains open when the VM stops. A context manager or an explicit close() handles normal completion; this issue covers stop paths where the program leaves a file open.
What the merged fix changes
PR #12017 adds a targeted finalizer-first pass for FAT file wrappers. The raw and text FAT file types receive MP_TYPE_FLAG_FINALISER_FIRST. During VM cleanup, CircuitPython finds those marked objects and runs their finalizers while the VM and storage bus are still available. Hardware reset follows.
Figure 1. Shutdown ordering reported in PR #12017. Flagged FAT files close while the card and its bus are usable. Other finalizers keep the regular teardown path.
The finalizer table is a bitmap indexed by heap block, so heap address order cannot express a general dependency order. The new pass scans for explicitly flagged objects, clears their finalizer-table entries, and holds them in a small C stack array. It then calls their finalizers after the scan. That matters because a finalizer can call into a Python block device and trigger allocation or garbage collection. The code does not read the finalizer table while those finalizers run.
The shutdown routine also keeps _vm_is_running true until this pass finishes and defers a pending reload or Ctrl-C while a close is in progress. A representative slice of the ordering is:
MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
gc_run_finalisers_first();
MP_STATE_THREAD(mp_pending_exception) = pending_exception;
_vm_is_running = false;
This is a scoped ordering rule for file types that need to close before the hardware they depend on. It is not a general topological sort of every finalizer dependency.
How the earlier PR connects
I proposed a related first-finalizer pass in my PR #11647, which was closed without merging. The discussion surfaced two important limits: a reverse walk through the finalizer bitmap cannot assume that the file object is above its SDCard object in the heap, and a pass that keeps the heap locked cannot close files backed by a Python SD-card driver.
The merged PR #12017 uses an explicit flag for FAT file wrappers and runs the closes after scanning. Its test table compares the fix with both the baseline and a locked first pass like #11647. The approaches share the goal of ordering some finalizers, but #12017 is Mikey Sklar's implementation and is the change that merged.
What the reported tests show
The chart summarizes emulated SD-card scenarios reported in PR #12017. Each value is the number of runs that kept the written data divided by total runs. The PR author reported these results; I did not independently rerun them.
Figure 2. Data-retention results reported in PR #12017 for emulated SD-card scenarios. The totals include five attempts per stop path. The earlier locked pass improves the sdcardio cases, while the final pass also handles adafruit_sdcard.
The pull request also reports tests on a PyPortal with a 512 MB SD card:
| Hardware test | Before | PR #12017 |
|---|---|---|
sdcardio, 25 runs |
0/25 writes kept; card wedged | 25/25 writes kept |
Python adafruit_sdcard driver, 25 runs |
0/25 writes kept; no error shown | 25/25 writes kept |
Other reported checks include 15/15 passing flush, close, and with controls; 1,025/1,025 Linux Unix-coverage tests, unchanged from before; and 212 additional flash bytes on a Metro M0 Express, with 6,360 bytes free. If a card is pulled while five files are open, the reported stop time is 2.5 seconds, compared with 0 seconds before. These are results from the PR description, not measurements I collected.
What I took away
The important design choice is the boundary of the ordering rule. This fix does not claim to solve finalizer dependencies for every Python object. It marks the FAT file wrappers that must close before a storage bus reset, then gives those finalizers a safe, explicit window during VM shutdown.
My earlier PR did not merge, but the issue discussion and the closed PR helped expose the ordering and heap-lock constraints. The final implementation by @mikeysklar carries the scoped approach through to Python-backed SD-card drivers and physical-card tests. The merge belongs to PR #12017, authored by @mikeysklar and merged by @dhalbert.
References
About the author
- Tech enthusiast, interested in ECE and other multidisciplinary projects.
Comments
Join the discussionNo comments yet. Be the first to comment.
Open-Source Contributions
A place where I write about my open-source contributions, the stuff I worked on, the bugs I ran into, what I learned, and how the whole process actually went. Basically the story behind the PR, not just the green merged badge.





