Skip to content

[Bug] grass.temporal never closes its SQLite connections #8123

Description

@echoix

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.py

The 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 (main at 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 = False

So 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 = False

With 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): with debug=True, yacc.yacc() opens parser.out and never closes it. The four temporal algebra parsers pass debug=self.debug, so this shows up in the temporal algebra tests, for example python/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:66 calls sqlite3.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

  1. added theissue type on Oct 28, 2026
  2. added
    temporal
    on Oct 28, 2026
  3. Muhaddis-igis commented on Nov 15, 2026

    @Muhaddis-igis
    Contributor

    @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 = False
    • if not self.connected: return: a second close() on the same object does nothing. init() relies on this, because it calls dbif.close() twice when the database exists (core.py:772 and core.py:810). Side effect: close() on a DBConnection that never connected now returns; on main it raises AttributeError, because self.connection does not exist yet.
    • self.connection.commit() and self.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:

    • New python/grass/temporal/tests/grass_temporal_core_db_connection_test.py with two tests. The first checks that the sqlite3 connection raises ProgrammingError after close(); on main it fails with DID NOT RAISE ProgrammingError. The second calls close() twice. The fixture mirrors the session into os.environ with monkeypatch, as grass_temporal_gui_support_test.py does, because tgis reads the session from there.
    • grass_temporal_core_init_skip_db_test.py (line 66 on main): the test's own sqlite3.connect() is wrapped in contextlib.closing(). With PYTHONTRACEMALLOC=20 this was the one warning left after the fix.

    I left the PLY parser.out item alone.

    Results

    Ubuntu 24.04 (WSL2), CMake build on top of main at 369ad74, Python 3.13.18, g.version -rge: proj=9.4.1, gdal=3.11.4, geos=3.12.2, sqlite=3.45.1, dataset nc_spm_full_v2beta1.

    Run main With the change
    Your one-liner, PYTHONDEVMODE=1, python3 -X dev 1 unclosed database 0
    Your four pytest files, -W default::ResourceWarning 59 0
    pytest steps of pytest.yml, PYTHONWARNINGS=always 2148 + 66 + 94 passed, 101 unclosed database 2150 + 66 + 94 passed, 0
    gunittest on temporal/ and python/grass/temporal/ (60 files) 5775 unclosed database 0

    The main numbers in the last two rows are from 2b93f0d, one commit earlier; only db.test changed in between.

    Full gunittest suite with .gunittest.cfg, as in test_thorough.sh: 338 files, 336 passed, and Cannot operate on a closed database appears nowhere. The two failures also fail on main:

    • python/grass/jupyter/testsuite/map3d_test.py times out after 300 s, also when run alone and on main. 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 in tearDownClass, where t.list exits with 1. It fails the same way on main in 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 database warnings remain in the full suite, none in a temporal test: 37 in the grass.pygrass vector tests and doctests, and 10 in v.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 through init() -> core.py:810 -> SQLDatabaseInterfaceConnection.close() -> commit() with Cannot operate on a closed database.

    Open points

    1. close() still commits. If a statement in execute_transaction() fails half way, the close() in its finally commits the statements that ran before the error, as on main. Keep that for this PR, or should it roll back?
    2. Not covered by any test: the wxGUI timeline and plot tools, which hold a dbif while 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.

  4. echoix commented on Nov 15, 2026

    @echoix
    MemberAuthor

    I think I might have the fixes for the vector and doctests committed somewhere in a branch, I should try to find them

  5. echoix commented on Nov 15, 2026

    @echoix
    MemberAuthor

    Try and open the PR so we could review.

  6. Muhaddis-igis commented on Nov 18, 2026

    @Muhaddis-igis
    Contributor

    @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 in finally, and close() no longer commits. With psycopg2, that commit() in close() was what saved the writes made with execute(), so execute() now commits after the statement on PostgreSQL.

    On nc_spm_full_v2beta1 with SQLite, a t.unregister that failed half way still removed 3 of its 6 maps on main and #8202, while t.info kept counting all 24. With #8217, all 24 maps stay. The PR describes one trade-off on PostgreSQL: writes made with execute() 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.

  7. added a commit that references this issue on Nov 27, 2026
    9ac9aa5
  8. added a commit that references this issue on Nov 28, 2026
    f482a0c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    temporal

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions