Skip to content

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

Done

Description

@krlmlr

A warning or a server notice that RPostgres signals while its C++ code still holds a result or a connection runs R calling handlers right away. A handler that calls dbClearResult() or dbDisconnect() then frees the object under the C++ code's feet: R crashes, or the fetch reads freed memory. RMariaDB had the same bug (r-dbi/RMariaDB#601) and fixed it in r-dbi/RMariaDB#632 by queueing warnings and signaling them from the entry points just before returning to R. This issue tracks the equivalent here.

Severity: medium (proposed, Kirill may change). It takes a calling handler that clears the result or closes the connection, but then it crashes R or reads freed memory.

Sites, all against CRAN RPostgres 1.4.10 and main as of f764ba1:

  • DbConnection::set_current_result() warns "Closing open result set, cancelling previous query" from inside dbSendQuery(). A handler that disconnects crashes R (reprex 1). A handler that clears the previous result happens to survive.
  • PqResultImpl::fetch_rows() warns "Don't need to call dbFetch() for statements, only for queries" before the fetch loop. A handler that clears the result frees the PqResultImpl the loop then reads; valgrind reports an invalid read in RPostgres.so, and a plain Rscript run fails with Error in result_fetch(res@ptr, n = n) : vector is too large. The reprex is not deterministic, it may also return the right result.
  • DbConnection::cancel_query(), DbColumn::warn_type_conflicts() and the "result object still in use" warning in connection_release() signal the same way from inside C++ work.
  • Server notices go through DbConnection::process_notice() as cpp11::message() while libpq is reading a result, so a message handler that clears the result makes the fetch read freed memory (reprex 2). Deferring them changes when notices appear during long statements, so this may need its own decision.
  • Tests for each site.

options(warn = 2) around the "Closing open result set" warning is handled cleanly today: the error comes before any work, and the previous result stays usable.

Reprex 1: disconnect from a handler (crash)

library(RPostgres)
con <- dbConnect(Postgres())

rs1 <- dbSendQuery(con, "SELECT generate_series(1, 3) AS a")
# The warning about cancelling rs1 is signaled while the C++ code
# is creating the new result
rs2 <- withCallingHandlers(
  dbSendQuery(con, "SELECT 2 AS a"),
  warning = function(w) {
    dbDisconnect(con)
    invokeRestart("muffleWarning")
  }
)
# Expected: a clean error, e.g. "Invalid connection", and no crash
dbIsValid(con)

reprex v2.1.1 reports: "This reprex appears to crash R." Standard output and error, first lines of the traceback:

 *** caught segfault ***
address 0x55f076dde81d, cause 'memory not mapped'

Traceback:
 1: result_create(conn@ptr, statement, immediate)
 2: initialize(value, ...)
 3: initialize(value, ...)
 4: new("PqResult", conn = conn, ptr = result_create(conn@ptr, statement,     immediate), sql = statement, bigint = conn@bigint)
 5: .local(conn, statement, ...)
 6: dbSendQuery(con, "SELECT 2 AS a")

Reprex 2: clear the result from a notice handler

library(RPostgres)
con <- dbConnect(Postgres())

# Same for a server notice, relayed as a message during the fetch
dbExecute(
  con,
  "CREATE FUNCTION pg_temp.noisy(x int) RETURNS int AS $$
   BEGIN RAISE NOTICE 'row %', x; RETURN x; END $$ LANGUAGE plpgsql"
)
#> [1] 0
rs <- dbSendQuery(con, "SELECT pg_temp.noisy(a) AS a FROM generate_series(1, 3) a")
#> NOTICE:  row 1
#> NOTICE:  row 2
res <- withCallingHandlers(
  dbFetch(rs),
  message = function(m) {
    if (dbIsValid(rs)) dbClearResult(rs)
    invokeRestart("muffleMessage")
  }
)
#> NOTICE:  row 3
#> Error:
#> ! Failed to fetch row : message contents do not agree with length in message type "N"
# Expected: no error (or a clean "Invalid result set" error)
res
#> Error:
#> ! object 'res' not found

Created on 2026-11-29 with reprex v2.1.1

The error message varies from run to run, it comes from libpq reading a freed result.


Generated by Claude Code

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions