Skip to content

Create the table before the workers append in to_sql with num_proc - #8839

Open
mertkayacs wants to merge 4 commits into
huggingface:mainfrom
mertkayacs:fix-to-sql-multiproc-table
Open

mertkayacs wants to merge 4 commits into
huggingface:mainfrom
mertkayacs:fix-to-sql-multiproc-table

Conversation

@mertkayacs

@mertkayacs mertkayacs commented Oct 17, 2026 •

Copy link
Copy Markdown

to_sql with num_proc > 1 hands every batch to the pool at once. The batch at offset 0 runs DataFrame.to_sql with if_exists as given ("fail" by default) and is meant to create the table; the later batches run with if_exists="append", which also creates the table when it is missing. Whenever a later batch reaches the database before the first one, the first then finds the table and raises table already exists. With 40 single-row batches and four workers it failed in 10 runs out of 10 for me.

The parent now creates the pool, pickles one of the later tasks the way the pool would (so a task that can't be pickled, such as a method lambda, still raises before anything is written), then writes the first batch itself before any task is submitted. The table exists with if_exists applied once, and the workers only ever append. The progress bar keeps its total and starts at one. An empty dataset writes nothing, as before.

I left to_csv alone: pool.imap returns its results in order and the parent writes them, so CSV output has no such race.

Verification

$ python -m pytest tests/io/test_sql.py -q   # Python 3.10, 3.12 and 3.14; pandas 2.3.3 / 3.1.1, sqlalchemy 2.0.57 / 2.1.8, pyarrow 24.0.0 / 26.0.1
16 passed in 1.61s   (same result on each Python)
$ python -m pytest tests/test_arrow_dataset.py -q -k to_sql
2 passed, 439 deselected in 1.44s
$ ruff check tests src benchmarks utils setup.py && ruff format --check tests src benchmarks utils setup.py
All checks passed!
257 files already formatted
# not run: the rest of tests/

The tests no longer rely on sleeps. A fixture wraps multiprocessing.Pool and records the table's rows each time the writer calls pool.imap, which is the moment the later batches go to the workers. The tests check that the first batch has already created the table at that point (default if_exists and "replace"), that an existing table with if_exists="fail" raises before any batch is submitted and keeps its rows, and that a task that can't be pickled (a method lambda) raises before anything is written and leaves an existing table untouched. That last test fails if the pickling check is removed or moved after the first batch. With src/datasets/io/sql.py back at 18378f7 and the tests kept, the first three fail every time, since the table does not exist yet when the batches are handed out. The issue's probe (40 rows, batch_size=1, num_proc=4, ten runs) goes from 10 failures to 0 with the fix, with all 40 rows present each time.

Fixes #8838

@charan-rathore

Copy link
Copy Markdown

Checked this against the race in #8838: running batch 0 in the parent before the pool starts means the table exists (with if_exists applied once) before any worker appends, and the empty-dataset and single-batch paths still behave. The test discriminates the right way too: the sleep on offset 0 only matters without the fix, when offset 0 still goes through the pool and loses the race.

One heads-up for whoever merges: this edits the same pool.imap block as #8834 (index numbering across batches), so whichever lands second will need a small rebase.

@mertkayacs

Copy link
Copy Markdown
Author

You read it right, running batch 0 in the parent is what closes the race before the pool starts. And yes, this touches the same pool.imap block as #8834, so I'll rebase whichever of the two lands second.

@charan-rathore

Copy link
Copy Markdown

That works. Whichever of the two lands first, ping me after the rebase and I'll re-run the same race check on the updated pool block.

@AdrianPerez3

Copy link
Copy Markdown

Thanks mertkayacs for the fix and the clear write-up in #8838, and charan-rathore for checking the scheduling. I ran an independent local check of this PR. CI hasn't run yet (both workflows are waiting for approval), so everything below is from local runs. In short:

  • The fix works. With this PR the race is gone in every run I tried, including two cases that are worse than "table already exists": with replace and delete_rows the unfixed code can silently lose rows.
  • Optional change (+8/−4): with this PR, batch 0 is committed before the pool is created and the tasks are pickled, so a later pickling error now leaves the database modified. Creating the pool first and pickling one task before writing avoids that.
  • Optional test: a deterministic alternative to the sleep(0.5) test.

Optional change: create the pool and check that the tasks pickle, then write batch 0

With this PR, batch 0 is written and committed in the parent before the pool is created and the tasks are pickled. The inputs below failed without writing anything before this PR. With this PR they fail after batch 0 has been committed:

  • A connection object (sqlite3.Connection, SQLAlchemy Engine or Connection) with num_proc > 1 and more than one batch. Every task fails to pickle. For a sqlite3.Connection that is TypeError: cannot pickle 'sqlite3.Connection' object; SQLAlchemy objects raise AttributeError on Python 3.12 and PicklingError on 3.14. It happens under spawn, fork and forkserver alike, because pool tasks are always pickled.
  • Other unpicklable task parts, e.g. method=lambda, with_transform(lambda), or a writer subclass defined inside a function.
  • multiprocessing.Pool() itself raising, e.g. on a file-descriptor limit (simulated).

What that leaves behind depends on if_exists:

  • replace or delete_rows: the caller's existing rows are gone when the error is raised, and only the first batch remains.
  • fail on a new table: a table holding batch 0 is left behind.
  • append: batch 0 is added.

Nothing promises atomicity, or that connection objects work with num_proc, so this isn't a broken contract. Still, one of the two docstring examples uses a sqlite3 connection, and num_proc is documented without restriction, so the combination is plausible.

Suggested diff (+8/−4 in src/datasets/io/sql.py, applies with git apply on d72b0a2)
diff --git a/src/datasets/io/sql.py b/src/datasets/io/sql.py
index a87d7c9b..bf692180 100644
--- a/src/datasets/io/sql.py
+++ b/src/datasets/io/sql.py
@@ -1,4 +1,5 @@
 import multiprocessing
+from multiprocessing.reduction import ForkingPickler
 from typing import TYPE_CHECKING, Optional, Union
 
 from .. import Dataset, Features, config
@@ -108,11 +109,14 @@ class SqlDatasetWriter:
         else:
             num_rows, batch_size = len(self.dataset), self.batch_size
             num_batches = (num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size
-            # the first batch creates the table (with if_exists as given) before the workers start:
-            # the later batches append, and one of them could otherwise reach the database first
-            if num_rows:
-                written += self._batch_sql((0, index, to_sql_kwargs))
             with multiprocessing.Pool(self.num_proc) as pool:
+                if num_rows > batch_size:
+                    # the later batches are sent to the workers: fail before writing anything if they can't be
+                    ForkingPickler.dumps((self._batch_sql, ((batch_size, index, to_sql_kwargs),)))
+                # the first batch creates the table (with if_exists as given) before any task is submitted:
+                # the later batches append, and one of them could otherwise reach the database first
+                if num_rows:
+                    written += self._batch_sql((0, index, to_sql_kwargs))
                 for num_rows_written in hf_tqdm(
                     pool.imap(
                         self._batch_sql,

What I measured with the diff:

  • The race and table-policy results are the same as with this PR.
  • Each failure case above raises the same exception as before this PR and leaves the database untouched.
  • Single-batch exports with a connection object keep working. They work with this PR, but not before it.
  • Large batches: it removes a slowdown this PR introduces, because the workers start while the parent writes batch 0. Setup: 1M rows, batch_size=100_000, 4 processes, macOS spawn.
    • Before this PR: 1.07 s. This PR: 1.21 s. This PR with the diff: 1.07 s.
    • I ran three benchmark sessions. In each, this PR was 13–24% slower than whichever of the unfixed code and the diff ran in that session.
    • At batch_size=10_000, the unfixed code, this PR and the diff were within noise.
  • Linux with fork: it removes CPython's DeprecationWarning: This process ... is multi-threaded, use of fork() may lead to deadlocks in the child.
    • This PR triggers it in a fresh process, once per forked worker, because the parent converts batch 0 to pandas before forking.
    • It doesn't fail CI: inside a test session every tree warns, including the unfixed code.
Alternatives and one more case
  • An even smaller alternative: written += pool.apply(self._batch_sql, ((0, index, to_sql_kwargs),)) inside the with block. It's equally clean on the failure paths. But:
    • it was the slowest fixed variant (+5–12% vs the unfixed code at 200k rows and in memory);
    • single-batch exports have to wait for a worker to start (0.40–0.43 s vs this PR's 0.011–0.019 s, macOS spawn);
    • single-batch connection-object exports fail again, as before this PR.
  • A spawn script without an if __name__ == "__main__": guard that calls to_sql(..., if_exists="append", num_proc=2):
    • With this PR, every re-executed child appends batch 0 before its own Pool() raises: 31 copies after 8 s, while the script hangs.
    • Before this PR it also hangs, but writes nothing.
    • With the pool created first: 1 copy.

Optional test: deterministic instead of sleep(0.5)

The sleep-based test caught the bug in every run I made. Without the fix it failed 30/30 on macOS spawn, Linux fork and Linux forkserver, and 20/20 on Python 3.10 with pandas 2. Two things make it fragile, though:

  • It is timing-based.
  • The helper subclass is pickled to spawn workers. If the test module isn't importable there (e.g. --import-mode=importlib with the repo root off sys.path), the workers die while unpickling it and the pool waits forever. I reproduced this.

The alternative below wraps the Pool that datasets.io.sql uses and records the table's rows just before pool.imap is called. It asserts two things:

  • at that point only the first batch is in the table, with if_exists already applied;
  • with if_exists="fail" on an existing table, the pool is never reached.

Nothing test-defined is pickled, so it can't hang that way. It works whether batch 0 is written before or after the pool is created.

Test code (replaces SlowFirstBatchSqlDatasetWriter and its test; needs import multiprocessing, import types and import datasets.io.sql; time is no longer used)
def _table_rows(sqlite_path):
    with contextlib.closing(sqlite3.connect(sqlite_path)) as con:
        if con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dataset'").fetchone() is None:
            return None
        return sorted(con.execute("SELECT a FROM dataset").fetchall())


@pytest.fixture
def rows_when_workers_get_batches(monkeypatch):
    """Records the table's rows each time the writer calls pool.imap, i.e. just before batches go to the workers."""

    def watch(sqlite_path):
        records = []

        def pool(*args, **kwargs):
            real_pool = multiprocessing.Pool(*args, **kwargs)
            real_imap = real_pool.imap

            def imap(*imap_args, **imap_kwargs):
                records.append(_table_rows(sqlite_path))
                return real_imap(*imap_args, **imap_kwargs)

            real_pool.imap = imap
            return real_pool

        monkeypatch.setattr(datasets.io.sql, "multiprocessing", types.SimpleNamespace(Pool=pool))
        return records

    return watch


@require_sqlalchemy
@pytest.mark.parametrize("if_exists", [None, "replace"])
def test_dataset_to_sql_multiproc_creates_the_table_before_the_workers_append(
    if_exists, tmp_path, rows_when_workers_get_batches, set_sqlalchemy_silence_uber_warning
):
    # With num_proc > 1 the batches run in a pool, and a later batch (if_exists="append") could
    # reach the database before the first one. The first one then either raised "table already
    # exists" (default if_exists="fail") or dropped the rows already appended (if_exists="replace").
    # The first batch must have applied if_exists before the later batches are handed to the workers.
    output_sqlite_path = os.path.join(tmp_path, "out.sqlite")
    if if_exists == "replace":
        with contextlib.closing(sqlite3.connect(output_sqlite_path)) as con, con:
            con.execute("CREATE TABLE dataset (a INTEGER)")
            con.execute("INSERT INTO dataset VALUES (-1)")
    records = rows_when_workers_get_batches(output_sqlite_path)
    to_sql_kwargs = {"if_exists": if_exists} if if_exists else {}
    dataset = Dataset.from_dict({"a": list(range(6))})
    writer = SqlDatasetWriter(
        dataset, "dataset", "sqlite:///" + output_sqlite_path, batch_size=2, num_proc=2, **to_sql_kwargs
    )
    assert writer.write() == 6
    assert records == [[(0,), (1,)]]
    assert _table_rows(output_sqlite_path) == [(i,) for i in range(6)]


@require_sqlalchemy
def test_dataset_to_sql_multiproc_leaves_an_existing_table_untouched_with_if_exists_fail(
    tmp_path, rows_when_workers_get_batches, set_sqlalchemy_silence_uber_warning
):
    output_sqlite_path = os.path.join(tmp_path, "out.sqlite")
    with contextlib.closing(sqlite3.connect(output_sqlite_path)) as con, con:
        con.execute("CREATE TABLE dataset (a INTEGER)")
        con.execute("INSERT INTO dataset VALUES (-1)")
    records = rows_when_workers_get_batches(output_sqlite_path)
    dataset = Dataset.from_dict({"a": list(range(6))})
    writer = SqlDatasetWriter(dataset, "dataset", "sqlite:///" + output_sqlite_path, batch_size=2, num_proc=2)
    with pytest.raises(ValueError, match="already exists"):
        writer.write()
    assert records == []
    assert _table_rows(output_sqlite_path) == [(-1,)]

Results for tests/io/test_sql.py with these tests:

  • Without the fix: 3 fail, 12 pass.
  • With this PR, and with this PR plus the diff above: all 15 pass.
  • Same results on macOS (Python 3.12, pandas 3), Python 3.10 with pandas 2.3.3 (CI's latest and minimum pins), Linux 3.12 fork and Linux 3.14 forkserver, both serially and with -n 2 --dist loadfile.
  • The new tests also pass with --import-mode=importlib from an unrelated directory, the setup where the sleep-based test hangs.

Compatibility with #8834 and #8875

Evidence: setup, race results, sweep, existing coverage

Setup

  • Trees: the unfixed base 18378f73; this PR d72b0a29; main a1269ca9 with this PR applied (it applies cleanly).
  • macOS arm64: Python 3.12.12, pandas 3.0.6, pyarrow 26.0.0, SQLAlchemy 2.1.1 (spawn).
  • Linux aarch64 containers: Python 3.12.13 (fork) and 3.14.7 (forkserver).
  • Python 3.10 with pandas 2.3.3 and CI's latest and minimum pins, used for tests only.
  • All data was synthetic, and every export used a file-backed SQLite database.

Race runs

Setup: 400 rows, batch_size=20, num_proc=4, URI con, 20 runs per cell. "Exact" means the stored rows equal the dataset's rows as a multiset, and the returned count is right.

without the fix, macOS spawn without the fix, Linux 3.12 fork this PR (macOS, Linux 3.12, Linux 3.14)
new table, default fail 18/20 raise "already exists" 20/20 raise 20/20 exact
existing table + fail 20/20 raise, but in 19/20 rows had already been appended 20/20 raise, 19/20 appended 20/20 raise, table untouched
existing + replace 16/20 lost rows, 7/20 silently (write() returned 400, table held 20–380) 20/20 lost rows, 16/20 silently 20/20 exact
existing + delete_rows (pandas ≥ 3) 16/20 lost rows, all silently 20/20 lost rows, all silently 20/20 exact

Edge-case sweep

  • 47 cases on macOS: num_proc=3, batch_size=2, 9 rows. They covered index/index_label, method="multi", chunksize, dtype, select/shuffle/filter/sort/concatenate/shard, with_format, 10 column types, views and a read-only DB, among others.
  • This PR matched num_proc=1 in all 94 runs, including the 11 cases that also raise with num_proc=1.
  • Without the fix, one of three runs of an "int column, null-only later batches" case created the column as TEXT instead of BIGINT. That run also raised.

How other libraries do it

dask (to_sql with parallel=True), modin and Spark's JDBC writer follow the same pattern as this PR. The driver applies if_exists once (Spark: SaveMode), and the parallel tasks only append.

One difference: dask and modin create the table from an empty frame. Using the real first batch, as this PR does, keeps the column types identical to num_proc=1. An empty frame types two kinds of column differently:

  • a date32 column: TEXT instead of DATE;
  • a column that is all-null in the first batch: BIGINT/BOOLEAN instead of TEXT.

Existing tests and coverage

  • tests/io/test_sql.py passes before this PR, with it, and on main with this PR: 12, 13 and 13 passed, 0 skipped.
  • tests/test_arrow_dataset.py -k to_sql also passes.
  • ruff check, ruff format --check and git diff --check are clean.
  • No existing test runs concurrent batches:
    • test_dataset_to_sql_multiproc has 4 rows (one batch), and compares with zip without a length check.
    • BaseDatasetTest.test_to_sql returns before its num_proc=3 block under pandas ≥ 3. Under pandas 2 that block writes 4 rows in one batch.
  • In fix: add num_proc argument to Dataset.to_sql #7791, which added num_proc here, lhoestq asked for a test "in case there needs to be a special logic to handle the concurrent writes to the database". Your new test is the first one that exercises that.
Out of scope for this PR (I'll open separate issues)
  • Every pool task pickles the whole dataset, because it pickles the bound method.
    • For a 1M-row in-memory dataset (28 MB), that is 28 MB per task and about 2.8 GB per export at batch_size=10_000, and ten times more at the default of 1000.
    • Memory-mapped datasets need about 1.4 KB per task.
    • to_csv and to_json with num_proc work the same way.
  • num_proc barely helps on SQLite. At 1M rows with batch_size=10_000, num_proc=4 gave about 1.4× (macOS) to 1.8× (Linux), and about 1.0× at the default batch_size=1000. I measured this with this PR plus the diff above.
    • SQLite allows one writer at a time.
    • Most of the time goes to pandas/SQLAlchemy building parameters for each row, not to SQLite itself.
  • to_sql(num_proc>1) hangs forever if a pool worker dies (e.g. it is OOM-killed), because multiprocessing.Pool never resolves the lost task (multiprocessing.Pool shouldn't hang forever if a worker process dies unexpectedly python/cpython#66587).
    • I reproduced it on main and on this PR with a writer subclass whose _batch_sql calls os._exit in a worker.
    • There was no return after 60 s, and the other batches were already committed (2,700 of 3,000 rows).
    • This predates the PR.

Create the pool first and pickle one of the later tasks before batch 0 is written. A task
that can't be pickled (a sqlite3 connection or a lambda method with num_proc > 1) now raises
before anything is written, as it did before the race fix, and the workers start while the
parent writes batch 0.

Replace the sleep-based test with deterministic ones that record the table's rows when the
writer calls pool.imap. They pickle nothing defined in the test module.

Co-authored-by: AdrianPerez3 <[email protected]>
@mertkayacs

Copy link
Copy Markdown
Author

Thanks for the careful review. Both changes are in: the pool is created first with a pickling check before batch 0, and your fixture-based tests replace the sleep one. I added you as co-author on the commit. On Linux with Python 3.10, 3.12 and 3.14, your failure case with method=lambda and if_exists="replace" now raises with the existing rows still in the table.

@AdrianPerez3

Copy link
Copy Markdown

Thanks for adding both, and for the co-author credit. I checked b1b3c61 on macOS and on Linux with Python 3.10, 3.12 and 3.14: the tests pass, the race stays fixed (20/20 runs in each setup), and every failure case I had now raises with the existing rows intact, as you found.

One gap, which was already in my suggestion: no test covers the pickling check. With the check removed, or moved after batch 0, all the tests still pass. The test below fails in both cases and passes on your branch (it needs import pickle):

Test
@require_sqlalchemy
def test_dataset_to_sql_multiproc_unpicklable_task_leaves_an_existing_table_untouched(
    tmp_path, set_sqlalchemy_silence_uber_warning
):
    output_sqlite_path = os.path.join(tmp_path, "out.sqlite")
    with contextlib.closing(sqlite3.connect(output_sqlite_path)) as con, con:
        con.execute("CREATE TABLE dataset (a INTEGER)")
        con.execute("INSERT INTO dataset VALUES (-1)")
    dataset = Dataset.from_dict({"a": list(range(6))})
    writer = SqlDatasetWriter(
        dataset,
        "dataset",
        "sqlite:///" + output_sqlite_path,
        batch_size=2,
        num_proc=2,
        if_exists="replace",
        method=lambda pd_table, conn, keys, data_iter: pd_table._execute_insert(conn, keys, data_iter),
    )
    # the lambda can't be pickled: AttributeError up to Python 3.13, PicklingError from 3.14
    with pytest.raises((AttributeError, pickle.PicklingError)):
        writer.write()
    with contextlib.closing(sqlite3.connect(output_sqlite_path)) as con:
        assert con.execute("SELECT a FROM dataset").fetchall() == [(-1,)]

The PR description also still says batch 0 is written before the pool starts and describes the sleep-based test, so it may need an update.

With num_proc > 1 the later batches are pickled before the first one is written, so a task
that can't be pickled raises before anything reaches the database. Without this test, removing
that check or moving it after the first batch left every to_sql test green.

Co-authored-by: AdrianPerez3 <[email protected]>
@mertkayacs

Copy link
Copy Markdown
Author

Thanks, added your test in 6c4e157 with you as co-author again. I also fixed the description: it now follows the code (pool, pickling check, then batch 0 in the parent) and describes the current tests.

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.

to_sql with num_proc > 1 fails with 'table already exists' when a later batch reaches the database first

3 participants