Skip to content

fix: Raise warnings only after the C++ code is done with the result - #632

Merged
krlmlr merged 11 commits into
mainfrom
claude/fetch-deferred-warnings
Nov 29, 2026
Merged

krlmlr merged 11 commits into
mainfrom
claude/fetch-deferred-warnings

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Closes #601. An alternative to #611, as asked there: instead of refusing dbClearResult() while a fetch runs, warnings are queued and raised just before returning to R.

Before this change, cpp11::warning() inside MariaResultPrep::fetch() ran R's calling handlers while the C++ code still held the result. A handler that called dbClearResult() freed it, and the fetch then read freed memory.

Change

  • A new queue in src/DeferredWarnings.{h,cpp} collects warnings during C++ work. The text and number of warnings are unchanged.
  • These warnings are now queued: the two "Use dbExecute()" warnings in fetch(), the warning for an unrecognized field type (also reached from update_metadata() since fix: Read result types after dbBind(), so that placeholder columns keep their values #618), and "result object still in use" in disconnect().
  • The entry points in src/result.cpp and src/connection.cpp raise the queue after the C++ work is done:
    • result_fetch() and result_bind() raise it after the work.
    • result_create() raises it at the end, once R owns the new result, so that nothing leaks under options(warn = 2).
    • result_release() and connection_release() raise it after resetting their pointers.
  • The queue is emptied before raising. Under options(warn = 2) the first warning becomes an error, the rest are dropped, and nothing is left behind.
  • "Cancelling previous query" is now raised by result_create() before any C++ work, and the connection is checked again afterwards. A handler that clears the old result works, and one that disconnects gets a clean "Invalid connection" error.
  • The connection destructor only queues its warning, because a destructor must not call into R. The warning now reads "A connection from an earlier operation was garbage-collected without dbDisconnect(): call dbDisconnect() when finished working with a connection". It is raised at the start of the next query, fetch, bind or dbConnect(), before that call does any work, so that under options(warn = 2) the error leaves nothing half-done. On main, a leaked connection collected by gc() under options(warn = 2) aborts R, because std::terminate() is called on cpp11's unwind exception.
  • Each entry point clears warnings left over from a call that failed. If raising the warnings of a new result fails, the new result is released.

The interrupt check in the fetch loop (#621) is handled separately, in #629.

Tests

tests/testthat/test-deferred-warnings.R (new) covers:

  • the Use-after-free in dbFetch() when a warning handler clears the result #601 handler for prepared and immediate = TRUE results, which now gets the empty data frame back, with the result cleared afterwards;
  • the warning texts;
  • that options(warn = 2) leaves the result valid and clearable;
  • both "Cancelling previous query" handlers;
  • the gc() case, with the warning raised by the next query and by dbConnect(), and under options(warn = 2) before the next query starts.

Under valgrind, the #601 script shows 5 invalid reads on main and 0 errors with this change. The new tests and test-queries.R show 0 memory errors with MariaDB Connector/C 3.3.17 and libmysqlclient 8.0.46.

Local runs against MariaDB 10.11 with NOT_CRAN=true, with each client library and with -D_GLIBCXX_ASSERTIONS, before the merge with the latest main: the whole suite had 0 failures. Two test-timezone.R errors came from this container: "US/Alaska" unknown to CCTZ, and "SYSTEM" as the server's time zone, which had been reset and is fixed again. After the merge, the targeted test files pass. MySQL servers were not tested: there is no server in this container, and CI's MySQL entries currently run MariaDB (#592).

Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ


Generated by Claude Code

Closes #601.

Warnings raised while C++ code holds a result or a connection are queued
and signaled by the entry points just before returning to R,
so that a calling handler can no longer free the result or close the connection under our feet.
The warning about cancelling the previous query is raised before the new result is created,
and destructors only queue.
This is an alternative to #611, which refuses dbClearResult() from such a handler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Status: the clean review found one Medium, now being fixed. The destructor's "call dbDisconnect()" warning from a connection collected by gc() went into the same queue, and surfaced on the next unrelated call to any connection. Under options(warn = 2) that turned a healthy call into an error. Destructor warnings will get a separate queue, raised at top level by a task callback. Three Lows are fixed with it: the result is cleaned up if the warning flush errors in result_create(), warnings left over from a call that errored are cleared, and the test is made robust against unrelated warnings. A second review round follows.


Generated by Claude Code

…d call

The warning for a connection collected by gc() went into the same queue
as the warnings of the current call,
and surfaced in the next call on any connection.
With options(warn = 2), it turned a healthy call into an error and lost its result.

Destructors now queue into a separate queue.
A task callback registered in .onLoad() drains it after each top-level call,
and R prints its warnings after the output of that call.
An error from the callback, e.g. with options(warn = 2), is printed
and keeps the callback registered.

The tests ignore unrelated warnings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ
A call that queued a warning and then failed never signaled it,
so the warning surfaced in a later, unrelated call.
Each entry point that signals queued warnings now clears the queue first.
A warning that preceded an error is dropped, the error is what matters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ
With options(warn = 2) or an exiting warning handler,
dbSendQuery() never returned the new result,
which stayed the connection's current result until garbage collection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Three review rounds. The first found a Medium: the destructor's leak warning surfaced in unrelated calls. It now has its own queue, raised at top level by a task callback (1044b9f), together with three Lows (4a55a0c, 7c752d3). The second found two Mediums: the callback was removed by position, and leak warnings were lost when R never returns to top level. Both are fixed in 94c197a: the callback is registered by name, and dbConnect() raises pending leak warnings as well. The third round found nothing above Low. Valgrind is clean with both client libraries.

  • R/zzz.R: a leak warning from a connection collected by gc() appears after the current top-level call, or at the next dbConnect(), not at the time of gc(). In a process that never returns to top level and never connects again, it is lost. Before, it appeared during gc(), and under options(warn = 2) it aborted R. Relevance: low, a diagnostic only. Reviewer confidence: high.
  • Under options(warn = 2), such a leak warning is printed as an error but no longer stops the script, since it is raised inside try(). CI that relies on warn = 2 to catch leaked connections won't fail on them any more. Relevance: low. Reviewer confidence: high.
  • A warning queued by a call that then fails with an error is dropped. This affects at most the "unrecognized field type" warning. Relevance: low. Reviewer confidence: high.
  • The dbConnect() test would also pass if the callback had raised the warning first. Relevance: low. Reviewer confidence: high.
  • R code can still run during a fetch through the interrupt check, and through finalizers and error handlers. This already happens on main; for the interrupt check, see fix: A fetch stops cleanly when R code it calls closes its result or connection #629.

Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 14:31
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Drop the top-level callback, this is overkill. Instead, raise with the next call into the library, and amend the warning text to indicate that the origin may be from previous operations.

…f from a task callback

Drop the top-level task callback.
Warnings queued by destructors during garbage collection are now raised
at the start of the next call into the library
(result_create(), result_fetch(), result_bind(), connection_create()),
before any C++ work, so that an error under options(warn = 2)
leaves no state changed and no result lost.
The leak warning text says that the connection may stem from an earlier operation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Done in caa5ca3 and 5bb90c7.

  • The task callback is gone, along with the extra drain in dbConnect().
  • A leak warning from a garbage-collected connection is raised at the start of the next query, fetch, bind or dbConnect(), before that call does any work. Under options(warn = 2), the error therefore leaves nothing half-done.
  • dbClearResult() and dbDisconnect() don't raise it, so cleanup code can't fail under warn = 2.
  • The text now reads "A connection from an earlier operation was garbage-collected without dbDisconnect(): call dbDisconnect() when finished working with a connection".

A clean review of the change found nothing above Low. The local test server is down, so this version was only built and reviewed here; CI runs the tests.

Accepted limitations

  • src/DeferredWarnings.h: a leak that is followed by no further query, fetch, bind or dbConnect() is never reported. Calls to dbClearResult() and dbDisconnect() don't report it either. Relevance: low, a diagnostic only. Reviewer confidence: high.
  • Under options(warn = 2), a leak turns the next query into an error before it starts, wherever the leak happened. Relevance: low. Reviewer confidence: high.
  • A warning queued by a call that then fails with an error is dropped. This affects at most the "unrecognized field type" warning. Relevance: low. Reviewer confidence: high.
  • R code can still run during a fetch, through the interrupt check, finalizers and error handlers. This already happens on main; for the interrupt check, see fix: A fetch stops cleanly when R code it calls closes its result or connection #629.

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Merged the latest main into this PR (f327fc3). The only conflict was the warning in DbConnection::disconnect(): #624 changed its text to "It has been closed with the connection.", and this PR turns it into a deferred warning. The merge keeps both. It is still raised when dbDisconnect() returns, which is what test-dbDisconnect.R from #624 expects. The branch builds locally. The tests run in CI, because the local database server is down.


Generated by Claude Code

@krlmlr
krlmlr merged commit c1948bb into main Nov 29, 2026
9 checks passed
@krlmlr
krlmlr deleted the claude/fetch-deferred-warnings branch November 29, 2026 16:23
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
result_create() keeps the deferred warnings and the re-check after the
cancel warning from #632, and reads the connection through
connection_ptr(), so that a connection closed by a handler fails with
"Invalid or closed connection".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5PUWgaCJzotWt9NhJ
krlmlr added a commit to r-dbi/RPostgres that referenced this pull request Nov 29, 2026
…669)

* fix: Raise warnings only after the C++ code is done with the result

Part of #668.

Warnings raised while C++ code holds a result or a connection are queued
and signaled by the entry points just before returning to R,
so that a calling handler can no longer free the result or close the connection under our feet.
The warning about cancelling the previous query is raised in `result_create()` before the new result is created,
and the connection is checked again after it.
A warning left by a failed call is dropped at the start of the next one.
Modeled after r-dbi/RMariaDB#632.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc

* fix: Drop warnings from result destructors, and test the handlers in `dbDisconnect()`

A result collected by gc() inside another call queued its `PQcancel()` failure warning,
which then surfaced in that unrelated call.
The destructor now drops warnings,
and `result_release()` deactivates the result before releasing it to keep them for `dbClearResult()`.

New tests cover handlers that clear the result or disconnect again
while `dbDisconnect()` warns about a result still in use.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use-after-free in dbFetch() when a warning handler clears the result

2 participants