Skip to content

docs: Investigate a move of DBI's classes to S7 - #795

Open
krlmlr wants to merge 11 commits into
mainfrom
claude/s7-investigation
Open

krlmlr wants to merge 11 commits into
mainfrom
claude/s7-investigation

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Investigates whether DBI's virtual base classes (DBIObject, DBIDriver, DBIConnection, DBIResult, DBIResultArrow) and generics could move from S4 to S7, what that would mean for the existing S4 backends, and whether it would simplify the per-object .dbi state of #794. As Kirill asked, a second experiment adapts a vendored copy of S7 to fix the limitations the first one found, so that the move works without upgrading all backends at once.

Result

Two experiment records, each with scripts and output (R 4.5.3, S7 1.0.0); experiments/README.md lists them, and .Rbuildignore excludes the folder from the package build.

  • experiments/2026-11-29-s7/, with stock S7:
    • feat: Keep the driver in each connection and the connection in each result #794 is not simplified: a new S7 property, like a new S4 slot, reaches only backends reinstalled against the new DBI, so attr(x, ".dbi") stays necessary.
    • S7 base classes with S4 generics work for installed backends only as abstract classes registered via S4_register(), and S7's own tools then fail on backend objects.
    • S7 generics break installed backends, and S7 dispatch on S4 objects costs about 98 µs.
  • experiments/2026-11-29-s7-vendored/, with an adapted copy of S7 (MIT, with S7.diff against the CRAN tarball):
    • The patches fix prop(), dispatch and S7_inherits() for S4 subclasses of abstract S7 classes and S4_register() of a concrete child, cache S4 dispatch, and add S4_generic(), which makes an S7 generic also an S4 generic. S7's own 615 tests pass unchanged; one documented behavior change for pure S7 users.
    • With S7 base classes and S7 generics for dbConnect(), dbDisconnect() and dbGetQuery(), the RSQLite 3.54.1 and duckdb 2.0.1 binaries built against DBI 1.3.0 work unchanged; RSQLite's tests with DBItest (881) and DBI's (711) pass, as on main. A minimal S4 and a minimal S7 backend work side by side.
    • Properties reach only backends reinstalled against the S7 DBI; getMethod() and existsMethod() no longer find methods that moved to S7.
    • S7 dispatch on an S4 object drops from about 106 µs to 7 µs (S4: under 1 µs); dbGetQuery() on RSQLite was 5 to 14 % slower in one recorded run.
    • Six issue drafts for the S7 repository, posted here as comments, nothing filed upstream.
  • S7 requires R >= 4.2.0 and is a new dependency.
  • Not tested: DBI's other generics, R CMD check of the S7 DBI, duckdb's own tests, odbc, RPostgres, RMariaDB, bigrquery, adbi, other platforms.

Status

https://claude.ai/code/session_01Hr1rd6RgjpQxckjWTEReje

The record under experiments/2026-11-29-s7/ tests S7 1.0.0 base classes and S7 generics
against installed S4 backends (RSQLite, duckdb, a minimal backend).
It also tests whether S7 properties avoid the class caching that makes #794 read its slot with attr().
S7 base classes registered with S4 keep installed backends working, but give #794 nothing:
backends see S4 classes, and new properties reach only reinstalled backends.
S7 generics break installed backends that define methods.

The scripts and their recorded output sit beside the record,
and .Rbuildignore now excludes experiments/.

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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Drop the idea of moving DBI's classes or generics to S7?

Superseded by a question that takes the vendored S7 record into account: #795 (comment)

The experiment record (R 4.5.3, S7 1.0.0) finds:

  • S7 base classes with S4 generics can work for existing S4 backends without reinstalling them (RSQLite 3.53.3 and duckdb 2.0.1 binaries, DBI's and RSQLite's tests with 0 failures), but only as abstract classes with package = NULL registered via S4_register(); S7's own tools then do not work on backend objects (S7_inherits() is FALSE, no S7 method found for the parent, prop() never returns).

  • S7 generics break installed backends: the RSQLite binary fails to load ("not S4 generic: 'dbConnect', 'dbDisconnect'"), and only S7::method<- plus S7_on_load() in every backend works. An S7 generic on an S4 object takes a median of 98 µs per call against 0.68 µs for an S4 generic.

  • A new S7 property, like a new S4 slot, reaches only backends reinstalled against the new DBI, so feat: Keep the driver in each connection and the connection in each result #794 would still need attr(): S7 does not simplify it.

  • S7 needs R >= 4.2.0 and adds a dependency.

  • Drop the idea and keep S4 (recommended): no gain for feat: Keep the driver in each connection and the connection in each result #794, real costs for backends.

  • Keep S7 base classes as a later option: requires R >= 4.2, a new dependency, and offers no S7 tooling on backend objects.

  • Pursue S7 generics with a coordinated migration of backends: every backend changes its method registration, at a large dispatch cost.

Kirill decides. If nobody decides, the idea is dropped and DBI stays on S4.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Report the two S7 problems upstream?

Superseded by a question that takes the vendored S7 record into account: #795 (comment)

The experiment record found two behaviors of S7 1.0.0 that look like bugs: for an S4 subclass of an abstract S7 class, prop() never returns (even for an existing property), and S7 dispatch finds no method registered for the abstract parent (S7_inherits() is FALSE). With a concrete parent, all three work. Reporting them would be a public post in the S7 repository.

  • Report both, each with a minimal reprex, after this record's review is through (recommended): helps anyone mixing S4 subclasses with S7 classes, and costs one issue each.
  • Leave them unreported: nothing is posted; DBI does not depend on S7.

Kirill decides; nothing is posted without his go-ahead. If nobody decides, nothing is reported.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Merge the experiment record, or close this PR as a record only?

This PR adds experiments/2026-11-29-s7/ with scripts and recorded output, a registry at experiments/README.md, and ^experiments$ in .Rbuildignore, so the package build ignores it. DBI has no experiments/ folder on main yet.

  • Merge it after its clean review (recommended): the findings stay next to the code they concern and can be rerun when S7 or DBI change.
  • Close the PR unmerged and keep the branch as the record: main stays free of experiment files; the record is reachable from this PR.

Kirill decides. If nobody decides, the PR stays open as a draft and is not merged.


Generated by Claude Code

The record no longer says every installed backend fails to load with S7 generics:
only RSQLite was reached, and the minimal backend loads but finds no method.
Also name the variant where `dbConnect()` fails,
give the real reason `attr()` stays necessary,
add the fetch and the preinstalled packages to the replication steps,
and default `WORK` to a neutral temporary directory.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Clean review, round 1 (at cf332c3)

Reviewed by an agent without context from the work, by re-running the record's scripts and checking its facts. No High findings; every claim re-run reproduced, and the conclusion (S7 does not simplify #794; attr() stays necessary) holds.

Medium, both fixed in 06b3891:

  1. "The backends that are not updated fail to load" contradicted the record's own output: under the s7gen variant only RSQLite fails to load; the minimal backend loads with a warning and then fails at dbConnect(). Reworded.
  2. "Moving the generics to S7 breaks every installed backend" rested on RSQLite and the minimal backend only: duckdb is never reached under s7gen, because the script stops after RSQLite. The conclusion now says so.

Low, fixed in 06b3891: "[email protected] is list() with every variant" did not hold for s7gen; the reason given for attr() was weak (the evidence is that a new slot or property reaches only reinstalled backends); the replication steps lacked a fetch of the #794 branch and the preinstalled packages; the default work directory was session-specific and now defaults to ${TMPDIR:-/tmp}/s7-795. Accepted: the record links to its output files more than it quotes excerpts, and no other document cites it yet.

Reproduced: naming.R, abstract.R, installed-backends.R (with s7 and s7gen), probe-backend.sh (variants main, s7, s7gen), s7-subclass-cache.R, generics-s7.R; the prop() hang (still running after 30 s).

Facts checked: versions; S7 requires R (>= 4.2.0); 287 strong and 151 suggests reverse dependencies of DBI on CRAN; roxygen2 added S7 support in 8.0.0; .Rbuildignore excludes experiments/ from the tarball; no private paths or addresses in the outputs.

Not checked: the pr794 and s7-nodbi builds, the RSQLite 3.54.1 rebuild, and hence the test counts and benchmarks, which are taken from the record.


Generated by Claude Code

…ectory

Say which variants the `.dbi` result holds for,
and treat an empty `TMPDIR` in the R scripts as the shell scripts do.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Clean review, rounds 2 and 3 (06b3891, 4b56685)

  • Round 2 (06b3891): the fixes of round 1 match the record's output; one Medium (the .dbi sentence did not say that the probe backend cannot be installed against s7gen) and one Low (with TMPDIR set but empty, the R scripts defaulted to /s7-795 while the shell scripts use /tmp/s7-795), both fixed in 4b56685.
  • Round 3 (4b56685): no High or Medium findings. The R default now matches ${TMPDIR:-/tmp} (checked with TMPDIR empty, unset, and set) and is identical in all three R scripts. One Low, accepted below.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

  • experiments/2026-11-29-s7/README.md#L102-L104: the .dbi finding is correct but incomplete: [email protected] is also list() for a backend installed against pr794 or s7 and loaded with main or s7-nodbi; the full matrix is in output/probe-backend.txt. Relevance low; reviewer confidence high.
  • experiments/2026-11-29-s7/README.md: the record links to its output files more than it quotes excerpts, and no other document cites it yet. Relevance low; reviewer confidence high.
  • The test counts (702 DBI, 875 RSQLite) and the benchmarks were not re-run by the reviewer; they are taken from the record. Relevance low for the conclusion, which rests on the reproduced dispatch and caching results; reviewer confidence medium.

Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Run another experiment with a vendored version of S7, adapted to fix the limitations and to make the move viable without having to upgrade all backends at the same time. Post issue drafts for the S7 repo as individual comments here.

Adds the experiment record `experiments/2026-11-29-s7-vendored/`.
It vendors S7 1.0.0 under its MIT license, with the changes in `S7.diff`:
`prop()`, S7 dispatch and `S7_inherits()` work on S4 subclasses of abstract S7 classes,
`S4_register()` accepts a concrete child of a registered abstract class,
S7 dispatch on S4 objects caches the dispatch vector,
and a new `S4_generic()` makes an S7 generic available as an S4 generic.

With it, a DBI variant with S7 base classes and S7 generics for
`dbConnect()`, `dbDisconnect()` and `dbGetQuery()` keeps the RSQLite and duckdb binaries
and a minimal S4 backend working without reinstalling, alongside a minimal S7 backend.
The record also holds issue drafts for S7, not posted.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Clean review of the vendored S7 record, round 1 (5dc085b)

Scope: experiments/2026-11-29-s7-vendored/, the second experiment Kirill asked for, with an adapted copy of S7 1.0.0 and six issue drafts. Reviewed by an agent without context from the work, by re-running the record's scripts and reprexes. No High findings.

Medium

  1. One patch changes behavior for pure S7 users and is not stated: for a registered abstract S7 class A, method(g, methods::getClass("A")) <- stored the method under "S4/A" and now under "A", the key method(g, A) uses, so the two overwrite each other. No tests cover the patches. → Being documented.

Low, all being fixed:

  1. The dbGetQuery() overhead ("9 to 27 µs", "5 to 14 %") is from one run; a re-run gave 9.6, 14.1 and 40 µs (5–22 %).
  2. The adapted copy's DESCRIPTION still says Repository: CRAN.
  3. Two recorded test outputs contain a user library path.
  4. Draft 01 says the hang "cannot be interrupted" without showing it, and one expectation comment is muddled.
  5. The drafts link to the branch rather than a commit.

Reproduced: S7.diff regenerated byte-identical and applies to the CRAN tarball to give the vendored copy exactly; S7's own tests (615, 0 failures) with both S7 versions; every reprex against CRAN S7 (fails or times out) and the adapted S7 (works); RSQLite's tests (881, 0 failures) and DBI's (711, 0 failures, 60 skipped) with the installed binaries under both DBI variants; R CMD check of the probe backends OK; prop(con, ".dbi") only for classes installed against the S7 DBI; getMethod() and existsMethod() miss moved methods while callNextMethod() reaches them; dispatch timings of the same order (CRAN S7: 104 µs on an S4 object; adapted: 8.4 µs; through S4_generic(): 1.1 to 8.1 µs); the package tarball contains no experiments/ files.

Checked and correct: the patches only change paths where CRAN S7 errored or that S4_generic() creates, apart from the Medium above; the dispatch cache validates the class definition before use; each draft's cause matches the CRAN source, its expected and actual are stated correctly, and it uses plain S7 without DBI; the README states the limitations; no tokens, user names or private emails; MIT license files present.

Not checked: that the binaries were built against DBI 1.3.0 (only the installed DBI 1.3.0 was seen); prop<- on S4 subclasses; R CMD check of the adapted S7; other platforms and R versions.


Generated by Claude Code

…red S7 record

States that the adapted S7 now stores methods for a registered abstract class
and for its S4 class from `methods::getClass()` under one key,
that no tests cover the changes to S7,
and that the `dbGetQuery()` timings are from one run.
Drops `Repository: CRAN` from the adapted copy's DESCRIPTION and says it is not a release of S7,
redacts the default R library path in the recorded output,
and clarifies the prop() hang draft, linking the loop in S7's source.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Clean review of the vendored S7 record, round 2 (5dc085b..85573f7)

Scope: the fixes of round 1. No High or Medium findings, so the review stops here.

Low, all being fixed:

  1. The README and draft 06 cite timings from a run that is not recorded; draft 06 is meant for a public issue. → Dropped.
  2. The drafts' links are pinned to a commit where the drafts themselves still have the old wording. → Re-pinned to the final commit.
  3. "No tests were added for the changes" appears three times in the README. → One dropped.
  4. The adapted copy's DESCRIPTION keeps Date/Publication, another CRAN field. → Dropped.

Checked and correct: the Medium of round 1 re-run (CRAN S7 stores keys A and S4/A, the adapted copy only A, and the method set last wins, as documented); S7.diff still reproduces the vendored copy exactly from the CRAN tarball, and Repository: CRAN is gone; the adapted S7 installs and passes S7's 615 tests; the <R library> redaction is applied by the script and noted in the README, and no private paths remain; the S7 source link points at while(1); in src/prop.c at tag v1.0.0; the recorded percentages match bench-dbgetquery.txt.

Not checked: a fresh run of run-all.sh (about 15 minutes); the rendered GitHub pages.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 1 of 6 for the S7 repository (not posted there)

Source: 01-prop-hang-s4-subclass-abstract.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


prop() never returns for an S4 subclass of an abstract S7 class

prop() loops forever when called on an object of an S4 class that extends an abstract S7 class registered with S4_register(). The same works for a concrete S7 parent.

Reprex

With S7 1.0.0 from CRAN:

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

Base <- new_class("Base", abstract = TRUE, properties = list(a = class_numeric))
S4_register(Base)
methods::setClass("Child4", contains = S4_contains(Base))

## prop() runs in a separate process, because it never returns
callr::r(
  function() {
    library(S7)
    Base <- new_class(
      "Base",
      abstract = TRUE,
      properties = list(a = class_numeric)
    )
    S4_register(Base)
    methods::setClass("Child4", contains = S4_contains(Base))
    x <- methods::new("Child4", a = 1)
    prop(x, "a")
  },
  timeout = 5
)
#> Error:
#> ! ! callr timed out
## Expected: 1

## The C-level check in prop() rejects the object,
## but the R-level check_is_S7() that is meant to signal the error accepts it:
x <- methods::new("Child4", a = 1)
check_is_S7(x)
## Expected: the same verdict as prop(): an error if prop() rejects x, nothing if it accepts it
S7_inherits(x)
#> [1] TRUE

Expected and actual

Expected: prop(x, "a") returns 1, as it does when Base is not abstract, or signals an error. Actual: it never returns. It cannot be interrupted either, which the reprex does not show: it follows from the busy loop while(1); in C, which never checks for an interrupt (https://github.com/RConsortium/S7/blob/584d1a160acede153f1891a42268ad719387e9c9/src/prop.c#L97, tag v1.0.0).

Cause

The C function prop_() checks is_s7_object(), which looks for "S7_object" in the class or in the .S3Class slot. An S4 class that extends an abstract S7 class has neither, because S4_register() registers an abstract class as a virtual S4 class without setOldClass(). prop_() then calls signal_is_not_S7(), which calls the R function check_is_S7() to signal the error and follows it with while(1); (https://github.com/RConsortium/S7/blob/584d1a160acede153f1891a42268ad719387e9c9/src/prop.c#L97). But check_is_S7() uses has_S7_class(), which finds the _S7_class slot that the S4 subclass inherits from the registered class's prototype, so it returns without an error, and the C code spins.

Proposed fix

Make is_s7_object() agree with has_S7_class() for S4 objects that carry a stored class, and error instead of looping if the two ever disagree again. With this patch, prop(x, "a") returns 1, and S7's own test suite passes unchanged (615 tests).

diff -ruN S7-1.0.0/src/prop.c S7/src/prop.c
--- S7-1.0.0/src/prop.c
+++ S7/src/prop.c
@@ -94,7 +94,9 @@
 
   // will signal error
   eval_here(Rf_lang2(check_is_S7, object));
-  while(1);
+  // check_is_S7() returned: it and is_s7_object() disagree.
+  // Error instead of looping forever.
+  Rf_error("Internal error: `object` is an S7 object for check_is_S7() only.");
 }
 
 
@@ -206,7 +208,11 @@
 
 static inline
 Rboolean is_s7_object(SEXP object) {
-  return inherits2(object, "S7_object");
+  // An S4 subclass of an abstract S7 class has no "S7_object" in its class,
+  // but carries the stored class in its `_S7_class` slot. Agree with
+  // has_S7_class() in R, which signal_is_not_S7() relies on to signal.
+  return inherits2(object, "S7_object") ||
+    (Rf_isS4(object) && get_S7_class(object) != R_NilValue);
 }
 
 static inline

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 2 of 6 for the S7 repository (not posted there)

Source: 02-dispatch-s4-subclass-registered-class.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


S7 dispatch does not find methods for an abstract S7 class from an S4 subclass of it

An S7 method registered for an S7 class is not found for an object of an S4 class that extends that S7 class through S4_register(), if the S7 class is abstract. For a concrete S7 parent it is found.

Reprex

With S7 1.0.0 from CRAN:

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

Base <- new_class("Base", abstract = TRUE)
S4_register(Base)
methods::setClass("Child4", contains = "Base")
x <- methods::new("Child4")

describe <- new_generic("describe", "x")
method(describe, Base) <- function(x) "method for Base"
describe(x)
#> Error:
#> ! Can't find method for `describe(S4<Child4>)`.
## Expected: "method for Base"

## S4 sees the inheritance:
methods::is(x, "Base")
#> [1] TRUE

## S7 looks for a method under the S4 name of the registered class,
## but the method is registered under the S7 name:
method_explain(describe, object = x)
#>    describe([S4/Child4])
#>    describe([S4/Base])
#>    describe([ANY])

Expected and actual

Expected: describe(x) finds the method registered for Base, as S4 dispatch would, and as S7 dispatch does when Base is concrete. Actual: "Can't find method".

Cause

For an S4 object, obj_dispatch() builds the dispatch vector from the S4 class hierarchy with S4_class_name(), which names every class S4/<package>::<class>. The S4 class that S4_register() creates for an S7 class gets the same treatment, so the S4 subclass dispatches on S4/Base, while method<- registered the method under the S7 name Base. (For a concrete S7 parent, setOldClass() makes is_oldClass() true, and the bare name is used, which is why that case works.)

Proposed fix

In S4_class_name(), recognize an S4 class that S4_register() created for an S7 class, by the _S7_class slot of its prototype whose name matches the S4 class name, and use the S7 class name for it. This covers dispatch and method registration with methods::getClass() of such a class alike. With the patch, the reprex returns "method for Base", and S7's test suite passes unchanged.

@@ S4_class_name()
+# The S7 class that `x`, an S4 class definition, was registered for, or NULL.
+# S4_register_class() stores the S7 class in the prototype's `_S7_class` slot;
+# S4 subclasses inherit that prototype, so the names must match too.
+S4_registered_S7_class <- function(x) {
+  S7_class <- .Call(S7_class_, x@prototype)
+  if (
+    is_class(S7_class) &&
+      identical(S7_class_name(S7_class), as.character(x@className))
+  ) {
+    S7_class
+  }
+}
+
 S4_class_name <- function(x) {
+  # An S4 class that S4_register() created for an S7 class stands for that
+  # S7 class: S4 subclasses then find methods registered for the S7 parent.
+  S7_class <- S4_registered_S7_class(x)
+  if (!is.null(S7_class)) {
+    return(S7_class_name(S7_class))
+  }
+
   if (is_oldClass(x)) {

This matters for a package that moves its base classes to abstract S7 classes while other, already installed packages extend them with setClass(contains = ): their objects can then use methods the package registers for its S7 classes.

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 3 of 6 for the S7 repository (not posted there)

Source: 03-S7-inherits-s4-subclass.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


S7_inherits() is FALSE for an S4 subclass of a registered abstract S7 class

S7_inherits(x, Base) returns FALSE for an object of an S4 class that extends the abstract S7 class Base registered with S4_register(), although methods::is() and inherits() both return TRUE.

Reprex

With S7 1.0.0 from CRAN:

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

Base <- new_class("Base", abstract = TRUE)
S4_register(Base)
methods::setClass("Child4", contains = "Base")
x <- methods::new("Child4")

S7_inherits(x, Base)
#> [1] FALSE
## Expected: TRUE

## S4 and base R see the inheritance:
methods::is(x, "Base")
#> [1] TRUE
inherits(x, "Base")
#> [1] TRUE

Expected and actual

Expected: TRUE, as from methods::is(). Actual: FALSE.

Cause

For an S7 class, class_inherits() requires "S7_object" in the class of x. An S4 object has only its S4 class there, and for an abstract parent, no .S3Class slot either.

Proposed fix

For an S4 object that does not inherit from "S7_object", test with methods::is() against the S4 class registered for the S7 class, if there is one. With the patch, the reprex returns TRUE, and S7's test suite passes unchanged.

diff -ruN S7-1.0.0/R/class-spec.R S7/R/class-spec.R
--- S7-1.0.0/R/class-spec.R
+++ S7/R/class-spec.R
@@ -341,7 +341,11 @@
     any = TRUE,
     S4 = methods::is(x, what),
     # Class-vector-only objects have no stored class to inspect.
-    S7 = inherits(x, "S7_object") && inherits(x, S7_class_name(what)),
+    S7 = if (isS4(x) && !inherits(x, "S7_object")) {
+      S4_inherits_S7(x, what)
+    } else {
+      inherits(x, "S7_object") && inherits(x, S7_class_name(what))
+    },
     S7_base = what$class == base_class(x),
     S7_union = some(what$classes, class_inherits, x = x),
     S7_S3 = !isS4(x) &&
@@ -350,6 +354,18 @@
   )
 }
 
+# An S4 object inherits from an S7 class that is registered with S4
+# when its S4 class extends the registered S4 class,
+# as for an S4 subclass created with `setClass(contains = S4_contains(class))`
+# or with `contains =` naming the registered class.
+S4_inherits_S7 <- function(x, what) {
+  name <- S7_class_name(what)
+  def <- methods::getClassDef(name)
+  !is.null(def) &&
+    !is.null(S4_registered_S7_class(def)) &&
+    methods::is(x, name)
+}
+
 class_inherits_external <- function(x, what) {
   if (!inherits(x, "S7_object")) {
     return(FALSE)

The patch relies on S4_registered_S7_class() from the proposed fix for dispatch on such objects (a separate issue).

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 4 of 6 for the S7 repository (not posted there)

Source: 04-S4-register-child-of-abstract.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


S4_register() fails for a concrete subclass of a registered abstract S7 class

S4_register() of a concrete S7 class fails when its parent is an abstract S7 class that is registered with S4 itself. So an S4 method registered for the abstract parent with method<- never reaches the subclass.

Reprex

With S7 1.0.0 from CRAN:

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

Base <- new_class("Base", abstract = TRUE)
S4_register(Base)
Child <- new_class("Child", parent = Base)
S4_register(Child)
#> Error in `methods::setOldClass()`:
#> ! inconsistent old-style class information for "Base"; the class is defined but does not extend "S7_object" and is not valid as the data part
## Expected: "Child", invisibly

## So an S4 method for the abstract parent does not reach the child:
methods::setGeneric("g4", function(x) standardGeneric("g4"))
#> [1] "g4"
method(g4, Base) <- function(x) "S4 method for Base"
g4(Child())
#> Error:
#> ! unable to find an inherited method for function 'g4' for signature 'x = "Child"'
## Expected: "S4 method for Base"

Expected and actual

Expected: S4_register(Child) registers Child, and g4(Child()) finds the S4 method for Base. Actual: setOldClass() errors with "inconsistent old-style class information for "Base"", and S4 dispatch then finds no method.

Cause

S4_register_class() passes the full dispatch vector of Child, c("Child", "Base", "S7_object"), to setOldClass(). But an abstract class is registered as a virtual S4 class with setClass(), not as an old class, so setOldClass() rejects it.

Proposed fix

Pass setOldClass() only the classes below the first abstract ancestor, as S4_old_classes() already computes for S7 classes with an S4 ancestor. The S4 class that S4_register_class() creates for Child already extends the virtual S4 class of Base, so S4 dispatch finds methods for Base. With the patch, S4_register(Child) returns "Child", g4(Child()) returns "S4 method for Base", and S7's test suite passes unchanged.

@@ S4_reified_old_classes()
     return(c(S4_old_classes(class), "S7_object"))
   }
 
+  # An abstract ancestor is registered as a virtual S4 class, not as an old
+  # class, so setOldClass() can't take it, nor the classes above it.
+  # The S4 class created for `class` already extends it.
+  old_classes <- S4_old_classes(class)
+  if (length(old_classes) > 0) {
+    return(old_classes)
+  }
+
   class_dispatch(class)
 }

In DBI, this is what an S7 backend needs: its connection class extends DBI's abstract DBIConnection and must be registered with S4 to get methods for DBI's S4 generics.

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 5 of 6 for the S7 repository (not posted there)

Source: 05-dispatch-cost-s4-objects.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


S7 dispatch on S4 objects is more than ten times slower than on S7 objects

Dispatching an S7 generic on an S4 object takes tens of microseconds per call, more than ten times the cost on an S7 object and 60 to 125 times the cost of an S4 generic on the same object, in the runs below. Almost all of it goes into computing the dispatch vector of the S4 class, which is the same on every call.

Reprex

With S7 1.0.0 from CRAN (timings vary between runs and machines):

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

methods::setClass("Obj4", slots = c(x = "numeric"))
Obj7 <- new_class("Obj7", properties = list(x = class_numeric))
methods::setGeneric("f4", function(x) standardGeneric("f4"))
#> [1] "f4"
methods::setMethod("f4", "Obj4", function(x) 1)
f7 <- new_generic("f7", "x")
method(f7, methods::getClass("Obj4")) <- function(x) 1
method(f7, Obj7) <- function(x) 1

o4 <- methods::new("Obj4", x = 1)
o7 <- Obj7(x = 1)
bench::mark(
  `S4 generic, S4 object` = f4(o4),
  `S7 generic, S4 object` = f7(o4),
  `S7 generic, S7 object` = f7(o7),
  min_iterations = 10000
)[, c("expression", "min", "median")]
#> # A tibble: 3 × 3
#>   expression                 min   median
#>   <bch:expr>            <bch:tm> <bch:tm>
#> 1 S4 generic, S4 object 597.91ns 884.06ns
#> 2 S7 generic, S4 object  40.45µs  58.98µs
#> 3 S7 generic, S7 object   3.14µs   4.74µs
## Expected: S7 dispatch on an S4 object about as fast as on an S7 object

## Most of the time goes into computing the dispatch vector of the S4 class,
## which is the same for every call:
bench::mark(S7:::obj_dispatch(o4), min_iterations = 10000)[, c(
  "expression",
  "median"
)]
#> # A tibble: 1 × 2
#>   expression              median
#>   <bch:expr>            <bch:tm>
#> 1 S7:::obj_dispatch(o4)   59.9µs

Expected and actual

Expected: S7 dispatch on an S4 object costs about as much as on an S7 object. Actual: 59 µs against 4.7 µs in the run above; 106 µs against 4.4 µs in the benchmark of the experiment record linked below.

Cause

For an S4 object, obj_dispatch() calls S4_class_dispatch(methods::getClass(class(x))) on every call, which walks methods::extends(fullInfo = TRUE) and calls methods::getClass() and methods::is() for each superclass.

Proposed fix

Cache the dispatch vector per S4 class, keyed by package and class name, and use a cache entry only while methods::getClassDef() returns the very class definition it was computed for (an identical() that succeeds on the pointer). Redefining the class gives a new definition and invalidates the entry, and S4_register() clears the cache. With the patch, the same reprex gives a median of 11.3 µs for the S4 object against 4.4 µs for the S7 object, and 5.3 µs for obj_dispatch() alone; the benchmark in the record gives 7.1 µs against 3.8 µs. S7's test suite passes unchanged.

+S4_dispatch_cache <- new.env(hash = TRUE, parent = emptyenv())
+
+S4_obj_dispatch <- function(x) {
+  class <- class(x)
+  def <- methods::getClassDef(class)
+  if (is.null(def)) {
+    return(S4_class_dispatch(methods::getClass(class)))
+  }
+  key <- paste0(def@package, "::", def@className)
+  hit <- S4_dispatch_cache[[key]]
+  if (!is.null(hit) && identical(hit[[1L]], def)) {
+    return(hit[[2L]])
+  }
+  dispatch <- S4_class_dispatch(def)
+  S4_dispatch_cache[[key]] <- list(def, dispatch)
+  dispatch
+}

and in obj_dispatch():

-    S4 = S4_class_dispatch(methods::getClass(class(x))),
+    S4 = S4_obj_dispatch(x),

What the cache does not notice: a superclass redefined without redefining the subclass. Moving the computation to C, or hooking into the class cache of methods, could bring the cost down further.

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Issue draft 6 of 6 for the S7 repository (not posted there)

Source: 06-S4-generic-interop.md in the vendored S7 record. Kirill decides whether and when it is filed; nothing has been posted to S7.


Feature request: S7 generics that are also S4 generics, to move a generic from S4 to S7 without breaking installed packages

A package that owns widely used S4 generics, such as DBI, cannot move them to S7 one release at a time: once a generic is an S7 generic, packages installed against the S4 generic break until they are changed and reinstalled. A way to create an S7 generic that also is an S4 generic, with S4 methods dispatched first and S7 methods after, would allow the move without upgrading all dependent packages at the same time.

Reprex

With S7 1.0.0 from CRAN:

library(S7)
packageVersion("S7")
#> [1] '1.0.0'

area <- new_generic("area", "shape")
Circle <- new_class("Circle", properties = list(r = class_numeric))
method(area, Circle) <- function(shape) pi * shape@r^2

## An S7 generic is not an S4 generic, so an installed package whose NAMESPACE has
## exportMethods(area) or importMethodsFrom(<pkg>, area) no longer loads
## once the generic moves from S4 to S7:
methods::is(area, "genericFunction")
#> [1] FALSE
## Expected: a way to get TRUE here

## setMethod(), as in packages written for the S4 generic,
## creates a new S4 generic that masks the S7 generic:
methods::setClass("Square4", slots = c(side = "numeric"))
methods::setMethod("area", "Square4", function(shape) shape@side^2)
#> Creating a generic function from function 'area' in the global environment
class(area)
#> [1] "standardGeneric"
#> attr(,"package")
#> [1] "methods"
## Expected: one generic with both methods
area(methods::new("Square4", side = 2))
#> [1] 4
area(Circle(r = 1))
#> Error in `S7_dispatch()`:
#> ! Must be called from within an S7 generic.

In packages, it is worse: an installed package whose NAMESPACE has exportMethods(area) fails to load with "Functions found when exporting methods from the namespace '' which are not S4 generic: 'area'". One with setMethod() and import(<pkg>) installs, but registers its methods on a new S4 generic in its own namespace, which the S7 generic does not see. An earlier experiment record in the same pull request, https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7, shows both with DBI's dbConnect() and the RSQLite binary.

Expected and actual

Expected: a supported way to keep one generic that S4 code can register methods for, with setMethod(), exportMethods() and importMethodsFrom(), and S7 code with method<-. Actual: the S7 generic is not an S4 generic, and setMethod() masks it.

Proposal

An S4_generic(generic) that creates an S4 generic of the same name and formals in the calling package and links it to the S7 generic:

  • The S4 generic's body is the S7 generic's body with S7_dispatch() replaced by standardGeneric(), so code before dispatch runs once in either path.
  • S4 dispatch runs first and finds methods registered with setMethod(), at the cost of S4 dispatch.
  • The S4 default method dispatches on the S7 generic's method table, reading the arguments from its own frame as S7_dispatch() does, without running the generic's body again.
  • method<-, method() and method_explain() given the S4 generic use the S7 generic.

With the S7 adapted in the experiment record:

## Needs the S7 adapted in this record, which adds S4_generic()
library(S7)
packageVersion("S7")
#> [1] '1.0.0.9000'

area7 <- new_generic("area", "shape", function(shape) {
  message("generic body runs once")
  S7_dispatch()
})
S4_generic(area7)
methods::is(area, "genericFunction")
#> [1] TRUE

## S4 methods, as installed packages register them:
methods::setClass("Square4", slots = c(side = "numeric"))
methods::setMethod("area", "Square4", function(shape) shape@side^2)
area(methods::new("Square4", side = 2))
#> generic body runs once
#> [1] 4

## S7 methods, registered with method<- on the S4 generic, live in the S7 generic:
Circle <- new_class("Circle", properties = list(r = class_numeric))
method(area, Circle) <- function(shape) pi * shape@r^2
area(Circle(r = 1))
#> generic body runs once
#> [1] 3.141593
method(area, Circle)
#> <S7_method> method(area, Circle)
#> function (shape) 
#> pi * shape@r^2

## An S4 class without an S4 method falls through to S7 dispatch,
## which finds the method for an S7 parent:
Shape <- new_class("Shape", abstract = TRUE)
S4_register(Shape)
method(area, Shape) <- function(shape) NA_real_
methods::setClass("Blob4", contains = "Shape")
area(methods::new("Blob4"))
#> generic body runs once
#> [1] NA

In the record, DBI's dbConnect(), dbDisconnect() and dbGetQuery() made this way, with DBI's own methods for them registered with method<-, kept the RSQLite and duckdb binaries built against the S4 DBI working without reinstalling, and an S7 backend registered its methods with method<- in the same session. RSQLite's test suite, which includes DBItest, passed against its binary with this DBI. The record also has the cost: with this DBI, dbGetQuery() on RSQLite goes through S4 dispatch to the S4 default method, then S7 dispatch on the S4 connection, and a small query took 9 to 27 µs (5 to 14 %) longer than with the S4 DBI in the one recorded run; timings vary between runs. With the S4 generic, dispatch on an S4 object with an S4 method took 0.92 µs, on an S7 object with an S7 method 4.0 µs, and on an S4 subclass of an abstract S7 class that finds the S7 method for its parent 7.3 µs.

Limits: by design, methods registered with setMethod() take precedence over S7 methods, even for a less specific class, so the owning package should register all of its own methods with method<- (the record did not test such a conflict). In the record, S4 code that asks for the owning package's methods by name, such as getMethod("dbGetQuery", c("DBIConnection", "character")) or existsMethod(), no longer finds them, while callNextMethod() from an S4 method reaches them through the S4 default method. The implementation in the record is a new R/S4-generic.R of about 120 lines, half of them documentation, plus a few lines that let as_generic(), method() and method_explain() unwrap the S4 generic. It relies on the fixes for dispatch on S4 subclasses of S7 classes in separate issues.

Found while investigating a move of DBI's classes and generics from S4 to S7, in #795. The experiment record with the adapted S7 and the complete patch is at https://github.com/r-dbi/DBI/tree/ca42bd8ff5d03616d78499f22eccd6799bc1a8b8/experiments/2026-11-29-s7-vendored.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: How to proceed with S7, now that an adapted S7 makes the move viable?

The vendored S7 record (R 4.5.3, S7 1.0.0 with patches) finds that DBI can make its base classes S7 classes and move generics to S7 one at a time, exporting each as an S4 generic with a new S4_generic(). The RSQLite and duckdb binaries built against DBI 1.3.0 keep working unchanged, and RSQLite's test suite with DBItest passes. S7 tools work on their objects, except properties, which reach only backends reinstalled against the S7 DBI. Costs: about 7 µs per S7 dispatch on an S4 object against under 1 µs for S4, 5 to 14 % on a small dbGetQuery() in one recorded run, and getMethod() no longer finds methods that moved to S7. Not tested: DBI's other generics, R CMD check of the S7 DBI, duckdb's own tests, odbc and other backends (list). The fixes are not in any released S7; the issue drafts propose them upstream.

  • Propose the fixes upstream first, and revisit the move once a released S7 contains them (recommended): DBI then depends on a stock S7, and nobody ships a patched copy; the untested parts can be checked meanwhile.
  • Vendor the adapted S7 inside DBI now and start moving: no wait for upstream, but DBI carries and maintains a fork of S7, C code included.
  • Drop the S7 idea and stay on S4: no new dependency and no dispatch cost, but no S7 tooling either.

Kirill decides. If nobody decides, nothing moves to S7 and the record stays on this PR.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: File the six issue drafts in the S7 repository?

The drafts are posted here for reading, one per comment: 01 prop() hang, 02 dispatch for S4 subclasses, 03 S7_inherits(), 04 S4_register() of a concrete child, 05 dispatch cost on S4 objects, 06 feature request: S7 generics that are also S4 generics. Each has a minimal reprex against CRAN S7 1.0.0 without DBI, re-run by the clean review. Filing them is a public post in the S7 repository, under whoever files them.

  • File all six, the bugs 01 to 04 first and the performance issue and feature request after them (recommended): the bugs stand on their own, and 05 and 06 explain the use case.
  • File only the bugs 01 to 04: smallest footprint; the interop proposal stays here.
  • File none.

Kirill decides; nothing is posted without his go-ahead. If nobody decides, nothing is filed.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Earlier record (2026-11-29-s7/):

  • experiments/2026-11-29-s7/README.md#L102-L104: the .dbi finding is correct but incomplete: [email protected] is also list() for a backend installed against pr794 or s7 and loaded with main or s7-nodbi; the full matrix is in output/probe-backend.txt. Relevance low; reviewer confidence high.
  • experiments/2026-11-29-s7/README.md: the record links to its output files more than it quotes excerpts, and no other document cites it yet. Relevance low; reviewer confidence high.
  • The test counts (702 DBI, 875 RSQLite) and the benchmarks were not re-run by the reviewer; they are taken from the record. Relevance low for the conclusion, which rests on the reproduced dispatch and caching results; reviewer confidence medium.

Vendored S7 record (2026-11-29-s7-vendored/):

  • README.md#L189-L202: DBI's other generics, R CMD check of the S7 DBI, duckdb's own test suite, and backends other than RSQLite, duckdb and minimal ones (odbc, RPostgres, RMariaDB, bigrquery, adbi) were not tested, so the viability holds for the tested cases only (question). Relevance medium for a decision to move; reviewer confidence high for what was tested.
  • README.md#L22-L54: no tests cover the patches to S7; S7's own 615 tests pass unchanged. One patch changes behavior for pure S7 users (methods for a registered abstract class and its S4 class share one key), now documented. Relevance low for a record, high before shipping the patches; reviewer confidence high.
  • README.md#L142-L158: the dbGetQuery() overhead comes from one recorded run; timings vary between runs. Relevance low, the order of magnitude was reproduced; reviewer confidence medium.

Generated by Claude Code

This branch has not been deployed

No deployments
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.

2 participants