Concurrent `file()` inserts with multiple files share one file: rows lost
Describe what's wrong
- Concurrent
INSERT INTO FUNCTION file(...)writers can pick the same new filename and silently overwrite each other's data. - Trigger: multiple parallel inserts using
engine_file_allow_create_multiple_files = 1against the same base path. - Expected all 16 writers to get distinct files with all 17 rows readable; actual result was only 6-9 rows readable with 0 errors reported.
- A previous PR fixed this collision only for
ENGINE = Filetables, not forfile()table function calls.
Root cause: StorageFile::write searches for a free suffix using fs::exists without claiming the name (no O_EXCL), and since TableFunctionFile::getStorage builds a new StorageFile per query, concurrent file() inserts never share the lock that would otherwise serialize this search.
Why we believe this is a bug: - TableFunctionFile::getStorage builds a fresh StorageFile per query (TableFunctionFile.cpp:168), so each file() INSERT has its own rwlock and paths.
StorageFile::writetakes that private lock (StorageFile.cpp:3114), starts the suffix search atpaths.size()= 1 and keeps the first namefs::existsreports free (StorageFile.cpp:3138-3145).StorageFileSink::initializeopens it withO_WRONLY | O_APPEND | O_CREATand checksnaked_buffer->size()once at open (StorageFile.cpp:2896, 2901): every writer sees an empty file and appends a complete Parquet file; the reader only sees the last footer.
Affected locations:
src/Storages/StorageFile.cpp:3142— suffix search starts at paths.size() and keeps the first name fs::exists reports free, without creating itsrc/Storages/StorageFile.cpp:2896— StorageFileSink::initialize opens the chosen name with O_APPEND | O_CREAT, no O_EXCL; size() append guard at 2901 runs once at opensrc/Storages/StorageFile.cpp:3114— the PR's exclusive rwlock is per StorageFile instancesrc/TableFunctions/TableFunctionFile.cpp:168— file() creates a new StorageFile per query, so concurrent inserts never share the lock
Impact: Silent data loss for parallel exports that rely on engine_file_allow_create_multiple_files (several jobs writing export.parquet at once): the INSERTs report success, and the rows of every writer but one per colliding file cannot be read back. A writer that opens the file after another has flushed fails with CANNOT_APPEND_TO_FILE instead. Pre-existing, not a regression of this PR; this PR's changelog claims the collision fixed, but the fix only covers one File table.
Does it reproduce on most recent release?
Yes — confirmed on current master (commit b34d8a8ea01814).
How to reproduce
Run many concurrent INSERT INTO FUNCTION file(...) statements with engine_file_allow_create_multiple_files = 1 against a Parquet path and compare row/file counts via _file.
# no-fasttest: Parquet is not available in the fast-test build.
# Concurrent `INSERT INTO FUNCTION file` with `engine_file_allow_create_multiple_files` must give
# every insert its own file: two inserts sharing one Parquet file leave only one of them readable.
WRITERS=16
DIR=test_repro
OUT_DIR="${CLICKHOUSE_TMP}/test_repro_streams"
trap 'rm -rf "${OUT_DIR:?}" "${CLICKHOUSE_USER_FILES:?}/${DIR:?}"' EXIT
rm -rf "${OUT_DIR:?}" "${CLICKHOUSE_USER_FILES:?}/${DIR:?}"
mkdir -p "$OUT_DIR"
FILE="file('${DIR}/data.parquet', 'Parquet', 'x UInt64, y String')"
clickhouse-client -q "INSERT INTO FUNCTION ${FILE} VALUES (0, 'base')"
pids=()
for i in $(seq 1 $WRITERS); do
curl -sS -X POST http://localhost:8123/ --data-binary "
INSERT INTO FUNCTION ${FILE}
SETTINGS engine_file_allow_create_multiple_files = 1,
engine_file_truncate_on_insert = 0,
async_insert = 0
VALUES ($i, 'w$i')" > "$OUT_DIR/w$i.out" 2> "$OUT_DIR/w$i.err" &
pids+=("$!")
done
for pid in "${pids[@]}"; do
wait "$pid" || echo "writer $pid did not finish"
done
echo "writers $(find "$OUT_DIR" -name 'w*.out' | wc -l)"
echo "errors $(cat "$OUT_DIR"/w*.out "$OUT_DIR"/w*.err | grep -c 'DB::Exception')"
clickhouse-client -q "SELECT 'rows', count() FROM file('${DIR}/*.parquet', 'Parquet', 'x UInt64, y String')"
clickhouse-client -q "SELECT 'files', uniqExact(_file) FROM file('${DIR}/*.parquet', 'Parquet', 'x UInt64, y String')"Note: an automated re-run of this exact block on current master (1e5291bf9d43) did not show the failure; the analyst's run did (outputs below). Environment or ordering may matter.
Expected behavior
Each concurrent insert should get its own uniquely claimed file so all rows are written and readable.
Expected output of the reproducer above:
writers 16
errors 0
rows 17
files 17Error message and/or stacktrace
Multiple writers open the same append-mode file, each sees it as empty, and only the last writer's Parquet footer remains readable, losing the others' rows silently.
Actual output of the reproducer above on master (b34d8a8ea01814):
writers 16
errors 0
rows 9
files 9
(reruns: rows 6 / files 6, rows 6 / files 6, and rows 8 / files 8 with randomized settings)Claim the name atomically: in the suffix loop create the candidate with open(O_CREAT | O_EXCL | O_WRONLY) and advance on EEXIST, then let the sink open the claimed file. Covers writers on any number of StorageFile instances, and the in-memory start index becomes a hint only. Trade-off: one extra open/close; a failed INSERT leaves an empty file, which already happens today because the sink creates the file at construction. The new case fits into 05237_storage_file_concurrent_insert_paths_race.sh.
Open risks:
- Not exercised: an explicit-path
Filetable and afile()insert writing the same path go through the same unclaimed suffix search and should collide the same way. - Not exercised:
url('file://...')inserts, if they build a per-queryStorageFile.
Found during automated review of PR #121598; whether that PR introduced it could not be established, so nobody is tagged. Severity P2 · Finding h_pr121598_001
Source: ClickHouse/ClickHouse