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).
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:
Split the branch into 8 stand-alone commits
organized by layer (C headers, XS core, Perl layer, mock driver, docs,
unit tests, regression tests, built-in AsyncWatcher
adapters).
Overhauled several of the most popular DBD
drivers (DBD::Pg, DBD::mysql,
DBD::MariaDB, DBD::ODBC, plus net-new
gRPC-based DBD::Spanner, DBD::BigQuery,
DBD::Bigtable, and DBD::Datastore) against
this branch to surface real-world ergonomic hitches and edge cases
before finalizing DBI core.
Documented every piece of community and security feedback received so far, how it was addressed, and where we would especially welcome further collaboration.
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):
2004 DBI Roadmap & Early dbi-dev
Proposals: Tim Bunce's official August 2004 DBI roadmap
explicitly listed "Support non-blocking mode for drivers that can
enable it in their client API", though early
$sth->ready() / $sth->done() proposals
stalled over differing vendor C client capabilities.
2010 DBD::Gofer::Transport::corostream
Experiment: In DBI 1.615, Bunce prototyped async proxying via
Coro and AnyEvent to avoid rewriting
DBI.xs, noting it was experimental because globally
altering CORE::select was fragile.
Driver Fragmentation & Ecosystem
Workarounds: Without a shared core contract, drivers built
mutually incompatible async APIs (PG_ASYNC /
pg_ready / pg_socket in DBD::Pg,
mysql_async in DBD::mysql,
mariadb_async in DBD::MariaDB,
SQL_ATTR_ASYNC_ENABLE in DBD::ODBC).
Frameworks such as Mojo::Pg and DBIx::Poggy
had to reach underneath DBI for raw driver FDs, while others bypassed
DBI entirely (Database::Async) or resorted to
worker-process pools (AnyEvent::DBI,
DBIx::Class::Async).
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.
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).
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 | 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) |
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
}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);#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" */
}
#endifRather 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:
DBD::Pg — bucardo/dbdpg#224
(c5eccd6):
Bridges libpq (PG_ASYNC,
pg_ready, pg_result, PQsocket,
PQflush). Live PostgreSQL 17 container runs pass
14/14 new t/09async_dbi.t
tests alongside 127/127 existing
t/08async.t tests.
DBD::mysql — perl5-dbi/DBD-mysql#505
(ab9b9c6):
Bridges mysql_async, mysql_async_ready,
mysql_async_result, and net.fd, with t/async_dbi.t.
DBD::MariaDB — perl5-dbi/DBD-MariaDB#257
(aae95cf):
Bridges mariadb_async, mariadb_async_ready,
mariadb_async_result, and sock_fd, with t/async_dbi.t.
DBD::ODBC — perl5-dbi/DBD-ODBC#35
(1b39c1c):
Bridges SQL_ATTR_ASYNC_ENABLE /
SQL_STILL_EXECUTING for Cloud SQL for SQL Server and ODBC
drivers, with t/async_dbi.t.
Net-New Cloud gRPC Drivers (Multiplexed HTTP/2, all
guarding AsyncMultiplex behind DBI_HAS_ASYNC
for legacy blocking DBI compatibility):
DBD::Spanner — GoogleCloudPlatform/google-auth-library-perl#42
(feat/dbd-spanner): Built on
Google::Cloud::Spanner::V1::SpannerClient; validates
AsyncMultiplex => 1 with concurrent in-flight statements
on a single HTTP/2 gRPC channel and fetch_async_row /
fetch_async_hashref.
DBD::BigQuery — GoogleCloudPlatform/google-auth-library-perl#43
(feat/dbd-bigquery): Built on
Google::Cloud::Bigquery::V2::JobServiceClient with optional
lazy-loaded Google::Cloud::Bigquery::Storage::V1 +
PDL::IO::Arrow columnar side-loading
(bq_fetch_arrow_batch / bq_fetch_pdl) that
yields DBI_ASYNC_WOULDBLOCK cleanly under
Async => 1.
DBD::Bigtable — GoogleCloudPlatform/google-auth-library-perl#44
(feat/dbd-bigtable): GoogleSQL v2 ExecuteQuery
over gRPC with AsyncMultiplex => 1 and
DBI_HAS_ASYNC legacy DBI fallback.
DBD::Datastore — GoogleCloudPlatform/google-auth-library-perl#45
(feat/dbd-datastore): GQL v1 RunQuery over
gRPC with AsyncMultiplex => 1, entity-to-row decoding,
and DBI_HAS_ASYNC legacy DBI fallback.
Live DBD::Pg testing caught a real
concurrency-guard bug in DBI.xs: Calling
$sth->err or $sth->state immediately
after $sth->execute() (while AsyncWantRead
is active) tripped the synchronous concurrency guard. Adding
err, errstr, state, and
set_err to the non-blocking inspection exemption fixed both
DBD::Pg and DBD::MockAsync.
DBD::Pg SQLSTATE alignment:
DBD::Pg::st::state reads imp_dbh->sqlstate
rather than DBIc_STATE(imp_sth), which surfaced immediately
in t/09async_dbi.t and clarified what driver authors must
update on yield.
Pure-Perl dual-DBI compatibility
(DBD::Spanner, DBD::BigQuery,
DBD::Bigtable, & DBD::Datastore):
Pure-Perl drivers cannot use C #ifdef DBIcf_Async; gating
on defined(&DBI::is_wouldblock) (before calling
DBI->import(':async') or setting
AsyncMultiplex) proved a clean, zero-overhead pattern for
supporting both standard DBI and non-blocking DBI from one
codebase.
Eliminating 50+ lines of C boilerplate per
driver: Dogfooding DBD::Pg,
DBD::mysql, DBD::MariaDB, and
DBD::ODBC revealed every C driver was duplicating Perl
stack manipulation (dSP/ENTER/SAVETMPS/call_sv) and
PERL_MAGIC_tied parent-handle traversal for
AsyncWatcher plus hand-assembling
DBI_ASYNC_WOULDBLOCK / HYAS0. Promoting
DBIh_ASYNC_SET_WOULDBLOCK,
DBIh_ASYNC_NOTIFY_WATCHER, and
DBIh_ASYNC_CLEAR_WANT into DBIXS.h /
dbistate_t cut ~50 lines per driver and also fixed strict
C89 declaration-after-statement compliance in
DBD::Pg.
Idiomatic async_read_ready() return contract
(0 vs undef): Initial driver drafts
returned undef for both "still pending" and
"fatal error", breaking the DBI idiom
defined(my $rv = $sth->async_read_ready()) or die $sth->errstr.
Standardized across DBI::DBD and all drivers to return
0 when still pending, row count / '0E0' on
completion, and undef strictly on error.
Warning-free DBI::is_wouldblock() & true
dualvar constant: Checking $val == -1 warned under
use warnings whenever called on row arrayrefs
(last if DBI::is_wouldblock($row)) or non-numeric driver
error strings. Rejecting ref($val) and comparing via
eq eliminated all warnings, and
DBI_ASYNC_WOULDBLOCK() now returns the true dualvar
(-1 / 'DBI_ASYNC_WOULDBLOCK') in both XS and
DBI::PurePerl.
Socket FD safety & Perl naming idioms in
DBI::AsyncWatcher: Caught an FD-aliasing hazard
(open my $fh, '<&=', $fd closed the driver's live
socket when $fh was freed on on_remove; fixed
to '<&' via dup(2)), and renamed
DBI::AsyncWatcher->for(...) to
DBI::AsyncWatcher->new(...) to avoid shadowing Perl's
for builtin
(ProhibitBuiltinHomonyms).
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) |
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.
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).
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.
ithreads and fork()?Under ithreads, async_wouldblock_sv
lives in per-interpreter dbistate_t (rebuilt in
dbi_bootinit() during CLONE), so no SV is
shared across interpreters.
Across fork(), non-DESTROY method calls
on an async handle from a child PID croak with a PID mismatch
diagnostic, while DESTROY skips the check so
AutoInactiveDestroy cleans up inherited handles
quietly.
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.
We want this interface to serve the whole Perl DBI and DBD ecosystem. Feedback is especially welcome on:
Driver capability detection: Whether checking
for a driver-implemented async_read_ready is the cleanest
opt-in mechanism or if an explicit driver flag is preferable.
fetch_async_row yield return value:
Whether returning DBI_ASYNC_WOULDBLOCK vs. returning
undef (with $sth->{AsyncWantRead}
distinguishing pause from EOF) is preferred for
while (my $row = $sth->fetch_async_row) loops.
Scope of DBI::AsyncWatcher (2ad72af):
Whether keeping lazy-loaded event-loop adapters in DBI core is welcome,
or if maintainers prefer moving commit 8 to a separate CPAN
distribution.
AsyncWatcher ergonomics: Whether
on_add($fd, $mode) / on_remove($fd) /
on_modify($fd, $mode) covers IO::Async,
AnyEvent, EV, and Mojo::IOLoop
cleanly without leaks or re-entrancy surprises.
Additional DBD prototypes: If you maintain a DBD driver and want to test or co-author an async branch against perl5-dbi/dbi#185, please chime in on the PR!
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