Skip to content

fix(cpp): make TsFileWriter safe to share across threads - #1147

Merged
ColinLeeo merged 1 commit into
apache:developfrom
ColinLeeo:fix-shared-writer
Nov 27, 2026
Merged

ColinLeeo merged 1 commit into
apache:developfrom
ColinLeeo:fix-shared-writer

Conversation

@ColinLeeo

Copy link
Copy Markdown
Contributor

What

Sharing one TsFileWriter across threads to write to different devices intermittently crashes with SIGSEGV or glibc heap corruption ("double free or corruption", "corrupted size vs. prev_size"). The races are on:

  • the device schema map (schemas_),
  • lazy chunk_writer_ / value_chunk_writer_ creation,
  • the shared TsFileIOWriter buffer used by flush(),
  • flush bookkeeping (record_count_since_last_flush_, start_file_done_).

Change

Add a std::recursive_mutex to TsFileWriter and guard every public operation that touches the writer's internal state. The mutex is recursive because flush() is reached both directly and from write_record / write_tablet / write_table via check_memory_size_and_may_flush_chunks, and because close() calls flush().

Validation

A repro program (8 threads writing 20k records each to a distinct device through one shared writer, with periodic flushes) crashes the unmodified writer in 15/15 runs (SIGSEGV and heap corruption). With this change it passes 30/30 runs.

Notes

Calls are now serialized rather than truly parallel; for independent, fully parallel write throughput, use one writer per thread.

Concurrent writes to different devices through a single TsFileWriter raced on the device schema map, lazy chunk-writer creation, the shared IO buffer, and flush bookkeeping, intermittently crashing with SIGSEGV or heap corruption.

Serialize every public operation with an internal recursive mutex so a shared writer no longer crashes. Calls are serialized rather than truly parallel; for independent parallel throughput use one writer per thread.
@ColinLeeo
ColinLeeo merged commit 71c2d3c into apache:develop Nov 27, 2026
49 checks passed
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.

1 participant