Reviewer's Guide: Non-Blocking Asynchronous DBI Core (perl5-dbi/dbi#185)

Branch: feature/non-blocking-core (rebased on master at dd2c386)

Related Issues & Threads: perl5-dbi/dbi#52, perl5-dbi/dbi#183, dbi-dev (Jul 2026, msg8398)

Scope: 8 stand-alone commits (13 files, +1412 / -13 lines)

Test Status: Full DBI suite passes (228 files, 12,104 tests, Result: PASS), plus live PostgreSQL 17 DBD::Pg validation (t/08async.t 127/127, t/09async_dbi.t 14/14).


Why This Guide Exists

Non-blocking I/O touches DBI's C dispatcher, error handling, handle inheritance, and driver ABI. To make reviewing perl5-dbi/dbi#185 as straightforward as possible, we have:


Historical Context & Motivation

Non-blocking I/O in DBI has been an open community request for over 20 years, tracked across perl5-dbi/dbi#52, perl5-dbi/dbi#183, and dbi-dev (msg8398):

How PR #185 Addresses the Three Historical Bottlenecks

  1. Inconsistent C Client Libraries: Drivers opt in strictly via #ifdef DBIcf_Async and async_read_ready — FD-capable libraries (libpq, libmysqlclient, libmariadb, gRPC HTTP/2) drive AsyncWatcher callbacks, while non-FD libraries (DBD::ODBC) still participate cleanly via periodic polling.

  2. DBI.xs State Machine Complexity: Rather than rewriting DBI's call frame, new state flags pack into unused upper bits of dbih_com_std_t.flags (zero ABI breakage), with DBI_ASYNC_WOULDBLOCK suppression and parent-aware concurrency guards strictly gated on DBIc_ASYNC(imp_xxh).

  3. No Single Perl Event Loop: AsyncWatcher (on_add / on_remove / on_modify) and lazy-loaded DBI::AsyncWatcher adapters decouple DBI core from IO::Async, AnyEvent, EV, and Mojo::IOLoop with zero new core dependencies.


Commit-by-Commit Reading Order

# Commit Files Size What to Review
1 56bd55e DBIXS.h, Driver_xst.h +64/-4 Bitmask flags, DBIh_ASYNC_* driver macros, DBIcf_INHERITMASK, snprintf
2 5c3d3c0 DBI.xs +276/-5 dbistate_t sentinel + watcher dispatch, Async gate, guards, fetch_async_*
3 2af5246 DBI.pm, PurePerl.pm, pipeone.pm +96/-4 Method table, :async export tag, warning-free is_wouldblock, PurePerl sync
4 b22c5bd DBD/MockAsync.pm +187 POSIX pipe reference driver for zero-dependency async testing
5 4731bd9 DBI/DBD.pm +118 Driver author contract (ASYNCHRONOUS EXECUTION SUPPORT)
6 2ff8959 t/18async.t, t/19mock_async.t, MANIFEST +281 Core async API, dualvar/warning tests, mock driver, and concurrency tests
7 76aeab9 t/20async_regression.t +174 Regression tests for robrwo and security review findings
8 2ad72af DBI/AsyncWatcher.pm +216 Built-in lazy-loaded AsyncWatcher adapters (IO::Async, AnyEvent, EV, Mojo::IOLoop)

End-to-End Usage Examples

1. Application-Side Event Loop Integration

Applications opt in with Async => 1 and supply an event-loop-agnostic AsyncWatcher hashref. When execute() would block, DBI returns '0E0', sets $sth->err to DBI_ASYNC_WOULDBLOCK (SQLSTATE HYAS0), and suppresses RaiseError/PrintError/HandleError:

use strict;
use warnings;
use DBI qw(:async);

my $dbh = DBI->connect('dbi:Pg:dbname=app', $user, $pass, {
    RaiseError   => 1,
    Async        => 1,
    AsyncWatcher => {
        on_add    => sub { my ($fd, $mode) = @_; $loop->watch($fd, $mode) },
        on_remove => sub { my ($fd)        = @_; $loop->unwatch($fd) },
    },
});

my $sth = $dbh->prepare('SELECT id, name FROM accounts WHERE active = ?');
my $rv  = $sth->execute(1);

if (DBI::is_wouldblock($sth->err)) {
    # Yield to event loop; when fd becomes readable, poll:
    defined(my $rows = $sth->async_read_ready()) or die $sth->errstr;
    # $rows == 0 means still pending; truthy (or '0E0') means completed
}

while (my $row = $sth->fetch_async_row()) {
    last if DBI::is_wouldblock($row);
    # process @$row
}

2. Built-In DBI::AsyncWatcher Adapters (2ad72af)

DBI core ships DBI::AsyncWatcher so applications never have to write on_add / on_remove / on_modify boilerplate by hand. Each event loop module is lazy-loaded on demand (keeping DBI core dependency-free), $dbh references are weakened internally to prevent circular reference leaks, and file descriptors are safely duplicated via '<&' so closing a watcher handle never closes the driver's live socket:

use DBI qw(:async);
use DBI::AsyncWatcher;

my $dbh = DBI->connect($dsn, $user, $pass, { RaiseError => 1, Async => 1 });

# Pick whichever event loop your application already uses:
$dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('IO::Async',    $dbh, loop => $loop);
$dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('AnyEvent',     $dbh);
$dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('EV',           $dbh);
$dbh->{AsyncWatcher} = DBI::AsyncWatcher->new('Mojo::IOLoop', $dbh);

3. Driver-Side C/XS Integration (#ifdef DBIcf_Async)

Existing C/XS drivers opt in without breaking compatibility with older DBI releases using the one-line DBIh_ASYNC_* macros in DBIXS.h — no manual Perl stack manipulation or AsyncWatcher hash traversal required:

#ifdef DBIcf_Async
if (DBIc_ASYNC(imp_sth)) {
    DBIc_ASYNC_WANT_READ_on(imp_sth);
    DBIc_ASYNC_WANT_READ_on(imp_dbh);
    DBIh_ASYNC_SET_WOULDBLOCK(sth, imp_sth);
    DBIh_ASYNC_NOTIFY_WATCHER(sth, imp_sth, fd, "on_add", "r");
    return 0; /* Driver.xst maps 0 -> "0E0" */
}
#endif

Real-World Driver Overhauls (Surfacing Ergonomic Hitches Early)

Rather than designing DBI's async contract in a vacuum, we built working async branches for some of the most widely used DBD drivers — each structured as a clean 3-commit stack (dbdimp.{h,c} → *.xs → t/async_dbi.t) and gated on #ifdef DBIcf_Async:

Real Bugs & Insights Caught by Dogfooding


Community Collaboration & Feedback Addressed So Far

This effort builds directly on prior community guidance on perl5-dbi/dbi#52 as well as detailed reviews on perl5-dbi/dbi#185. Every technical finding below is backed by a regression test in t/19mock_async.t or t/20async_regression.t:

Contributor Feedback / Requirement How It Was Addressed
pali (issue #52) Requested a stable, driver-independent DBI API unifying DBD::Pg and DBD::mysql async execution and supporting parallel statements where backends allow Defined Async, AsyncMultiplex, AsyncWatcher, async_read_ready/async_write_ready, and fetch_async_*, validated across 8 DBDs (DBD::Pg, DBD::mysql, DBD::MariaDB, DBD::ODBC, DBD::Spanner, DBD::BigQuery, DBD::Bigtable, DBD::Datastore)
timbunce (#52 comment) Asked someone to synthesize prior discussions, start a dbi-dev design discussion, and drive it to a workable implementation Published RFC perl5-dbi/dbi#183, opened dbi-dev msg8398, and delivered PR perl5-dbi/dbi#185 + reference drivers
David Nicol (dbi-users / design review, Jul 2026) Reinforced the single-event-loop constraint (FD-to-coderef watcher mapping); warned against forcing Future/Promise dependencies or manual weaken() in user closures; emphasized PID tracking across fork() and raised the single-namespace vs. parallel-namespace (DBI_NB) trade-off Shaped the loop-agnostic AsyncWatcher contract with zero Future core dependencies; encapsulated weaken($dbh) inside DBI::AsyncWatcher (2ad72af); enforced creation-PID fork checks in DBI.xs (5c3d3c0); preserved the single DBI namespace via strict DBIc_ASYNC opt-in isolation to avoid Python 2/3-style ecosystem fragmentation
Tux (PR #185) Noted the patch looked clean, requested additional reviewers (including kstarsinic) and careful review Split branch into 8 focused commits and authored this Reviewer's Guide + companion driver PRs
robrwo err == -1 disarmed RaiseError process-wide on non-async handles Gated set_err_sv() and XS_DBI_dispatch suppression strictly on DBIc_ASYNC(imp_xxh) (5c3d3c0)
robrwo File-static DBI_async_wouldblock_sv caused use-after-free under ithreads Moved sentinel SV into per-interpreter dbistate_t initialized in dbi_bootinit() (5c3d3c0)
robrwo Async => 1 bypassed capability gate on sth; HvNAME NULL warning; strstr match Added DBD::_::st to exclusion list, guarded HvNAME, exact leaf-name match in _install_method (5c3d3c0)
robrwo Fork PID guard croaked inside DESTROY, breaking AutoInactiveDestroy Skipped PID check when is_DESTROY is set (5c3d3c0)
robrwo Unbounded C/Perl recursion & mortal buildup in fetch_async_* Added DBIc_CALL_DEPTH guard and ENTER/SAVETMPS/FREETMPS/LEAVE framing (5c3d3c0)
robrwo MANIFEST, Makefile.PL, duplicate is_wouldblock, ALIAS, DBI::DBD docs Restored t/17handle_error.t, dropped $(O_FILES), unified warning-free is_wouldblock, added DBI::DBD docs (4731bd9)
esabol Asked what DBD::Pg needs to adopt this interface ("PR welcome!") Answered on PR #185 and opened draft PR bucardo/dbdpg#224; this prompt also inspired the companion DBD::mysql (#505), DBD::MariaDB (#257), DBD::ODBC (#35), and cloud gRPC driver PRs (DBD::Spanner #42, DBD::BigQuery #43, DBD::Bigtable #44, DBD::Datastore #45)
Security review Idle-prepared $sth bypassed parent $dbh busy state; AsyncWantWrite unchecked; sprintf in Driver_xst.h Checked DBIc_PARENT_COM(imp_xxh) for both AsyncWantRead and AsyncWantWrite (5c3d3c0); replaced sprintf with snprintf in Driver_xst.h (56bd55e)

Reviewer FAQ

Does this break binary ABI for existing compiled DBDs?

No. All five new flags (DBIcf_Async, DBIcf_AsyncWantRead, DBIcf_AsyncWantWrite, DBIcf_AsyncMultiplex, DBIcf_AsyncBufferWrites) are packed into unused upper bits (0x01000000–0x10000000) of the existing U32 flags field in dbih_com_std_t, and the two new dbistate_t fields (async_wouldblock_sv and async_notify_watcher) consume two of the three reserved void *pad2[3] slots (pad2[1] remaining). No struct sizes or existing member offsets change.

What happens to synchronous applications that never set Async => 1?

Nothing changes. DBIc_ASYNC(imp_xxh) is 0 by default, so set_err_sv(), XS_DBI_dispatch, RaiseError, PrintError, and HandleError follow the exact pre-PR code path (including for drivers that emit err == -1).

Why introduce fetch_async_row instead of reusing fetchrow_array?

In Perl, while (my @row = $sth->fetchrow_array) evaluates a single-element list ("DBI_ASYNC_WOULDBLOCK") as truthy, creating an infinite spin loop on yield. fetch_async_row and fetch_async_hashref croak in list context (GIMME_V == G_ARRAY) to eliminate that trap at the boundary.

How does this interact with ithreads and fork()?

What about drivers without a POSIX socket FD (e.g., DBD::ODBC)?

Drivers without a POSIX FD still benefit from Async => 1 + async_read_ready() using a lightweight event-loop timer poll instead of an FD watcher, keeping the Perl event loop unblocked during long queries while preserving a uniform DBI API.


How to Collaborate

We want this interface to serve the whole Perl DBI and DBD ecosystem. Feedback is especially welcome on:


Local Verification Commands

perl Makefile.PL
make -j$(nproc)
prove -j$(nproc) -b t/

To run only the new async and error-handling suites:

prove -j$(nproc) -bv t/17handle_error.t t/18async.t t/19mock_async.t t/20async_regression.t