Repository navigation
Create the table before the workers append in to_sql with num_proc - #8839
mertkayacs wants to merge 4 commits into
Conversation
|
Checked this against the race in #8838: running batch 0 in the parent before the pool starts means the table exists (with One heads-up for whoever merges: this edits the same |
|
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 |
|
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. |
|
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:
Optional change: create the pool and check that the tasks pickle, then write batch 0With 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:
What that leaves behind depends on
Nothing promises atomicity, or that connection objects work with Suggested diff (+8/−4 in
|
| 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=1in all 94 runs, including the 11 cases that also raise withnum_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.pypasses 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_sqlalso passes.ruff check,ruff format --checkandgit diff --checkare clean.- No existing test runs concurrent batches:
test_dataset_to_sql_multiprochas 4 rows (one batch), and compares withzipwithout a length check.BaseDatasetTest.test_to_sqlreturns before itsnum_proc=3block under pandas ≥ 3. Under pandas 2 that block writes 4 rows in one batch.
- In fix: add
num_procargument toDataset.to_sql#7791, which addednum_prochere, 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_csvandto_jsonwithnum_procwork the same way.
- For a 1M-row in-memory dataset (28 MB), that is 28 MB per task and about 2.8 GB per export at
num_procbarely helps on SQLite. At 1M rows withbatch_size=10_000,num_proc=4gave about 1.4× (macOS) to 1.8× (Linux), and about 1.0× at the defaultbatch_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), becausemultiprocessing.Poolnever 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_sqlcallsos._exitin 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.
- I reproduced it on main and on this PR with a writer subclass whose
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]>
|
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 |
|
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 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]>
|
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. |
to_sqlwithnum_proc > 1hands every batch to the pool at once. The batch at offset 0 runsDataFrame.to_sqlwithif_existsas given ("fail"by default) and is meant to create the table; the later batches run withif_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 raisestable 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
methodlambda, still raises before anything is written), then writes the first batch itself before any task is submitted. The table exists withif_existsapplied 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_csvalone:pool.imapreturns its results in order and the parent writes them, so CSV output has no such race.Verification
The tests no longer rely on sleeps. A fixture wraps
multiprocessing.Pooland records the table's rows each time the writer callspool.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 (defaultif_existsand"replace"), that an existing table withif_exists="fail"raises before any batch is submitted and keeps its rows, and that a task that can't be pickled (amethodlambda) 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. Withsrc/datasets/io/sql.pyback 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