Skip to content

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

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

krlmlr merged 2 commits into
mainfrom
claude/deferred-warnings

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Part of #668: fixes the warning sites. Server notices, the remaining item there, are an open question below; this PR closes #668 only if they go in here.

Warnings that RPostgres signals while its C++ code holds a result or a connection used to run R calling handlers right away. A handler that called dbClearResult() or dbDisconnect() freed the object under the C++ code's feet: dbDisconnect() from a handler for "Closing open result set" crashed R, and dbClearResult() from a handler for "Don't need to call dbFetch()" made the fetch read freed memory. This ports the fix from r-dbi/RMariaDB#632 (for r-dbi/RMariaDB#601).

Current state

  • src/DeferredWarnings.{h,cpp} holds a queue: defer_warning(), clear_deferred_warnings(), raise_deferred_warnings().
  • The warnings in DbConnection::cancel_query(), PqResultImpl::fetch_rows(), DbColumn::warn_type_conflicts() and the "result object still in use" warning in connection_release() are queued.
  • result_create(), result_release(), result_fetch(), result_bind() and connection_release() clear the queue on entry, so that a warning left by a failed call never surfaces in a later one, and signal it just before returning.
  • "Closing open result set, cancelling previous query" moves from DbConnection::set_current_result() to the start of result_create(), before any C++ work, and the connection is checked again afterwards: a handler that disconnects now gets "Invalid connection" instead of a crash.
  • If signaling a warning fails in result_create() (options(warn = 2), an exiting handler), the new result is released at once, so that it does not stay the connection's current result.
  • Unlike RMariaDB, no destructor here warns on purpose. ~DbResult() can reach the PQcancel() failure warning and may run during garbage collection inside another call, so it drops queued warnings with a DeferredWarningsSuppressor guard; result_release() deactivates the result before releasing it, so dbClearResult() keeps them.
  • tests/testthat/test-deferred-warnings.R ports the RMariaDB tests and adds handlers that clear the result or disconnect again from the warning in dbDisconnect(). Against CRAN RPostgres 1.4.10 the disconnect test crashes R. The options(warn = 2) test for dbSendQuery() passes on the old code too; it guards the order of checks, not a regression.

Review

A clean review (round 1) found nothing above Low; the Lows are fixed or listed in the Accepted limitations. Locally, the full suite passes with NOT_CRAN=true against PostgreSQL 16, and valgrind reports no errors for the reprexes, which read freed memory before.

Overlap

#638 (row sink) and #666 (SQLSTATE errors) also touch src/PqResultImpl.cpp, and #666 touches src/DbConnection.cpp. The change here is a one-call swap of cpp11::warning() for defer_warning() in fetch_rows() and cancel_query(), plus the removal of the warning from set_current_result(), so a conflict is a trivial one.

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Server notices

Server notices (RAISE NOTICE) reach R through DbConnection::process_notice() as cpp11::message() while libpq reads a result, so a message handler that calls dbClearResult() makes the fetch read freed memory, reprex 2 in #668. The same callback can also run from a result's destructor during garbage collection. This PR leaves notices alone because queueing them, like the warnings here, changes when they appear: a long dbExecute() that reports progress through notices would print them all at its end instead of as they arrive. Queueing costs that timing; leaving them costs the crash risk with message handlers that touch the result. If nobody decides, notices stay as they are and #668 stays open.

  • Queue notices like warnings and signal them at the end of each entry point, in a follow-up PR (recommended)
  • Same, in this PR
  • Leave notices immediate and document that a message handler must not clear the result or close the connection

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: A result opened from the handler for "Closing open result set"

The warning now comes at the start of result_create(), and DbConnection::set_current_result() no longer warns. If a calling handler for that warning sends a new query on the same connection, the new result is closed by the outer dbSendQuery() without a second warning, where it used to warn. Warning again costs a second check in result_create() after the handler returns (a few lines). The clean review confirmed this at runtime: the inner result ends up invalid, and its own warning never appears. It is an unusual handler, and the result is closed correctly either way. A loop that warns until the current result stops changing would not terminate for a handler that sends a query on every warning, so the fix would have to warn exactly once more. If nobody decides, it stays silent.

  • Accept: closed silently (recommended)
  • Warn once more after the handler returns if the connection has another result now

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: Queued warnings that no entry point signals

Only result_create(), result_release(), result_fetch(), result_bind() and connection_release() signal the queue, and only on success. Two cases lose a warning:

  • A warning queued anywhere else is dropped at the start of the next of these calls: the type-conflict warning from dbColumnInfo(). It is not reachable for PostgreSQL types today, since each column has one type, so no test covers it.
  • A call that fails after queueing drops the warning, where the old code showed it before the error: for example the PQcancel() failure warning followed by "Interrupted." in step_run().

A result collected by garbage collection now drops its PQcancel() failure warning instead of signaling it from the finalizer (unsafe before) or in an unrelated call (this PR before a4fd30c). Neither case is in a test, PQcancel() does not fail against a healthy server. Signaling them too costs a catch-and-rethrow wrapper around every entry point that flushes the queue before the error. If nobody decides, they stay dropped.

  • Accept: these rare warnings may be dropped (recommended)
  • Flush the queue before rethrowing an error, and signal it from every entry point

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

See the current list.

From the author's own review; the clean review by a fresh agent is still to come, and this list will be updated after it.


Generated by Claude Code

…`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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

After the clean review (round 1, nothing above Low).


Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 16:55
@krlmlr
krlmlr merged commit 4f3eca5 into main Nov 29, 2026
9 checks passed
@krlmlr
krlmlr deleted the claude/deferred-warnings branch November 29, 2026 17:49
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
No conflicts with the deferred warnings of #669.
An RPostgres_error leaves any warnings queued by the failing call in the queue;
the next entry point that raises deferred warnings clears it first,
so they never surface in a later call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Resolves the conflict in `PqResultImpl::fetch_rows()`:
`main` now raises the "Don't need to call dbFetch() for statements" warning through `defer_warning()` (#669)
and dropped nothing else the row sink needs.
The warning moves into `fetch_into()` with `defer_warning()`,
and the unused row-count argument of `fetch_rows()` from `main` is not carried over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g
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.

Warnings and notices signaled from C++ run handlers that can free the result or close the connection

2 participants