Repository navigation
Description
Describe the bug
I made an agent (Claude Code) and asked it to find the places where we open a file or a socket and never close it. It built GRASS, then ran the pytest tests and the full gunittest testsuite (with the NC sample dataset, as in the Ubuntu CI job) with Python's development mode (python -X dev, or PYTHONDEVMODE=1 so that tool scripts started as subprocesses are covered too). Dev mode enables ResourceWarning, which reports files, pipes and database connections that are never closed. The agent then traced the warnings back to the code and wrote the reproducers below, which it ran on main at commit 79cd2b3 to produce the output shown.
grass.temporal never closes the SQLite connections it opens. This is by far the largest source of warnings: over 3,000 unclosed database warnings in 52 test files in a full gunittest run, and 86 in the pytest tests for grass.temporal alone. Unlike the small leaks tracked separately, this one is not a one-line fix (see below).
To reproduce
export PYTHONDEVMODE=1 # also reaches Python scripts launched by GRASS
export PYTHONTRACEMALLOC=20 # optional: adds "Object allocated at" tracebacks
grass --tmp-project XY --exec python3 -X dev -c "import grass.temporal as tgis; tgis.init()"<sys>:0: ResourceWarning: unclosed database in <sqlite3.Connection object at 0x...>
Or with pytest, from a source tree with an installed GRASS (see AGENTS.md for the PYTHONPATH and LD_LIBRARY_PATH setup). This gives 86 warnings:
pytest -W default::ResourceWarning \
python/grass/temporal/tests/grass_temporal_granularity_test.py \
python/grass/temporal/tests/grass_temporal_gui_support_test.py \
python/grass/temporal/tests/grass_temporal_core_init_skip_db_test.py \
python/grass/temporal/tests/grass_temporal_topology_test.pyThe warnings are printed when the object is garbage collected, so the line number in a warning is where the GC happened, not where the connection was opened. PYTHONTRACEMALLOC shows the allocation site (core.py:1407, self.dbmi.connect(...), reached from tgis.init(), get_tgis_metadata(), create_temporal_database() and init_dbif()).
Expected behavior
The connection is closed when DBConnection.close() is called, so a run with PYTHONDEVMODE=1 prints no unclosed database warning.
Screenshots
Not applicable.
System description
- Operating System: Ubuntu 24.04.5 LTS, x86_64
- GRASS version: 8.6.0dev (
mainat commit 79cd2b3, "locale: Update translation files (135) (locale: Update translation files (135) #8111)"), built with CMake without GUI and PDAL g.version -rge: proj=9.4.0, gdal=3.8.4, geos=3.12.1, sqlite=3.45.1- Python 3.13.17
- Test data:
nc_spm_full_v2beta1
Additional context
Cause
DBConnection.close() in python/grass/temporal/core.py commits and closes the cursor but never closes the connection:
def close(self) -> None:
self.connection.commit()
self.cursor.close()
self.connected = FalseSo every connection stays open until it is garbage collected.
Why it is not a one-line fix
Adding self.connection.close() alone breaks things: tgis.init() calls dbif.close() twice on the same object (once inside the SQLite existence check and again after if db_exists is True:). That was harmless while close() did not really close, but the second commit() now raises sqlite3.ProgrammingError: Cannot operate on a closed database. With that change python/grass/temporal/tests/ went to 1 failed and 14 errors.
What worked in my tests was making close() idempotent and closing the connection:
def close(self) -> None:
if not self.connected:
return
self.connection.commit()
self.cursor.close()
self.connection.close()
self.connected = FalseWith this, all 136 tests in python/grass/temporal/tests/ pass, the warnings go from 86 to 1, and the one-liner above no longer warns. I have not run the full gunittest suite against this change. It needs that run (the t.* tools and the temporal algebra tests use the connection most), and someone who knows this code should check whether anything relies on a connection staying open after close(), for example the multi-mapset SQLDatabaseInterfaceConnection.close(), which closes every connection in unique_connections, including ones other objects may still hold.
Smaller temporal items
python/grass/temporal/ply/yacc.py(vendored PLY): withdebug=True,yacc.yacc()opensparser.outand never closes it. The four temporal algebra parsers passdebug=self.debug, so this shows up in the temporal algebra tests, for examplepython/grass/temporal/testsuite/unittests_temporal_raster_algebra_grs.py. It only happens in debug mode and it is vendored code, so it may be better left alone or fixed upstream.python/grass/temporal/tests/grass_temporal_core_init_skip_db_test.py:66callssqlite3.connect(tgis_db)in the test and never closes it. This is the single warning left after the fix above.
Follow-up
Once this is fixed, the Python tests could run in CI with -X dev -W error::ResourceWarning, or at least report ResourceWarning, so new leaks are caught. That needs this issue fixed first, because it would otherwise fail everywhere.
Activity
Muhaddis-igis commentedon Nov 15, 2026
@echoix I'd like to pick this up and open a PR with the idempotent
close()you proposed. Before that, I ran the full gunittest suite you said was still missing, and I'd like to check the results and two open points with you.The change
def close(self) -> None: """Close the DBMI connection ... """ + if not self.connected: + return + self.connection.commit() self.cursor.close() + self.connection.close() self.connected = Falseif not self.connected: return: a secondclose()on the same object does nothing.init()relies on this, because it callsdbif.close()twice when the database exists (core.py:772andcore.py:810). Side effect:close()on aDBConnectionthat never connected now returns; onmainit raisesAttributeError, becauseself.connectiondoes not exist yet.self.connection.commit()andself.cursor.close(): unchanged.self.connection.close(): the missing call, which releases the database file.self.connected = False: unchanged; the guard reads it on the next call.Two test changes:
python/grass/temporal/tests/grass_temporal_core_db_connection_test.pywith two tests. The first checks that thesqlite3connection raisesProgrammingErrorafterclose(); onmainit fails withDID NOT RAISE ProgrammingError. The second callsclose()twice. The fixture mirrors the session intoos.environwithmonkeypatch, asgrass_temporal_gui_support_test.pydoes, becausetgisreads the session from there.grass_temporal_core_init_skip_db_test.py(line 66 onmain): the test's ownsqlite3.connect()is wrapped incontextlib.closing(). WithPYTHONTRACEMALLOC=20this was the one warning left after the fix.I left the PLY
parser.outitem alone.Results
Ubuntu 24.04 (WSL2), CMake build on top of
mainat 369ad74, Python 3.13.18,g.version -rge: proj=9.4.1, gdal=3.11.4, geos=3.12.2, sqlite=3.45.1, datasetnc_spm_full_v2beta1.mainPYTHONDEVMODE=1,python3 -X devunclosed database-W default::ResourceWarningpytest.yml,PYTHONWARNINGS=alwaysunclosed databasetemporal/andpython/grass/temporal/(60 files)unclosed databaseThe
mainnumbers in the last two rows are from 2b93f0d, one commit earlier; onlydb.testchanged in between.Full gunittest suite with
.gunittest.cfg, as intest_thorough.sh: 338 files, 336 passed, andCannot operate on a closed databaseappears nowhere. The two failures also fail onmain:python/grass/jupyter/testsuite/map3d_test.pytimes out after 300 s, also when run alone and onmain. Probably the 3D rendering in my WSL setup; I have not looked further.temporal/t.register/testsuite/test_t_register_raster.py: its 7 tests pass; the error is intearDownClass, wheret.listexits with 1. It fails the same way onmainin the dataset run of the temporal suites, and passes when run alone, with and without the change. I have not found the cause.47
unclosed databasewarnings remain in the full suite, none in a temporal test: 37 in thegrass.pygrassvector tests and doctests, and 10 inv.rast.stats. pygrass opens its own SQLite connections (pygrass/vector/table.py), so these look like #8122 material. I have not traced them.The naive version (only
self.connection.close()) fails as you predicted: 55 of the 60 temporal dataset files and 238 pytest tests, all throughinit()->core.py:810->SQLDatabaseInterfaceConnection.close()->commit()withCannot operate on a closed database.Open points
close()still commits. If a statement inexecute_transaction()fails half way, theclose()in itsfinallycommits the statements that ran before the error, as onmain. Keep that for this PR, or should it roll back?dbifwhile the window is open, and the PostgreSQL backend. Is there anything else you would want checked?If this looks fine to you, I'll open the PR. I used an AI assistant to set up the build, run the test suites and draft the regression test; I reviewed and ran the changes myself.
echoix commentedon Nov 15, 2026
I think I might have the fixes for the vector and doctests committed somewhere in a branch, I should try to find them
echoix commentedon Nov 15, 2026
Try and open the PR so we could review.
Muhaddis-igis commentedon Nov 18, 2026
@echoix I opened #8217 for open point 1 from my comment above (a failed
execute_transaction()being saved in part). It has the commit of #8202 unchanged plus a second one, so it replaces #8202.With #8217, a failed
execute_transaction()saves nothing: it rolls back infinally, andclose()no longer commits. With psycopg2, thatcommit()inclose()was what saved the writes made withexecute(), soexecute()now commits after the statement on PostgreSQL.On
nc_spm_full_v2beta1with SQLite, at.unregisterthat failed half way still removed 3 of its 6 maps onmainand #8202, whilet.infokept counting all 24. With #8217, all 24 maps stay. The PR describes one trade-off on PostgreSQL: writes made withexecute()before a failed transaction are now kept, as on SQLite already.Could you review #8217 instead of #8202? The test details, including the PostgreSQL runs, are in the PR description.
grass.temporal: Close the SQLite connection in DBConnection.close()
grass.temporal: Close the SQLite connection in DBConnection.close() (O…