Skip to content

fix(cpp): make a shared TsFileReader safe for concurrent queries - #1165

Closed
ColinLeeo wants to merge 3 commits into
developfrom
fix/tsfile-212
Closed

ColinLeeo wants to merge 3 commits into
developfrom
fix/tsfile-212

Conversation

@ColinLeeo

Copy link
Copy Markdown
Contributor

Problem

Multiple threads sharing one storage::TsFileReader could crash while querying (tree and/or table model). Root causes found in develop:

  • TsFileExecutor::query_exprs_ was written by every tree query with no synchronization.
  • TsFileIOReader lazy-loaded tsfile_meta_, its arena and tsfile_meta_ready_ on first use without a lock.
  • ensure_table_query_executor() deleted the table executor whenever batch_size changed, while live TableResultSets still borrowed its MetadataQuerier and TsFileIOReader — a use-after-free on a single thread as well.
  • get_timeseries_metadata() callers reset a shared metadata arena concurrently.
  • Result sets read lazily, so locking only query() could not make iteration safe.

Fix

  • Each TsFileReader owns one recursive per-reader mutex (not a global lock). Every public method takes it, and every result set the reader returns is bound to the same lock, so next()/get_next_tsblock()/close() are serialized with queries and with each other.
  • The table executor is a shared_ptr that is replaced, not deleted; result sets keep the executor they borrow alive (set_keep_alive), so a later query with a different batch_size cannot dangle them.
  • The tree executor is shared-owned too, so destroying an unclosed result set after close() is safe (iteration after close remains invalid).
  • TsFileReader::with_reader_lock() lets callers keep lazy metadata views valid while copying them. The C wrapper now converts metadata into caller-owned C structures inside that lock, which closes a concurrent heap-use-after-free in populate_c_metadata_map_from_cpp.
  • Concurrency contract documented in tsfile_reader.h, result_set.h, tsfile_cwrapper.h and skills/tsfile/references/{cpp.md,c.md}: concurrent use is safe but serialized; one thread advances one result set; consume result sets before close(); get_timeseries_metadata() views are invalidated by the next metadata call from any thread.

Tests

New cpp/test/reader/tsfile_reader_concurrency_test.cc:

  • shared-reader tree queries, shared-reader table queries with alternating batch sizes;
  • metadata calls interleaved with queries; QDSWithTimeGenerator queries; table queryByRow; prepared queries;
  • a batch result set that outlives a query with a different batch size;
  • repeated open/close across threads, error paths that must not latch the lock;
  • destroying unclosed tree/table result sets after close().

New cpp/test/cwrapper/cwrapper_reader_concurrency_test.cc: 6 threads call both C metadata entry points in a loop and verify every converted field (device path, measurement name, row count). With only the wrapper fix reverted, this test reproduces the ASan heap-use-after-free in populate_c_metadata_map_from_cpp.

Verification on the branch:

  • Before the fix: concurrent tree/table tests aborted with malloc(): unaligned tcache chunk detected; metadata-mix and executor-replacement tests SIGSEGV'd.
  • After: full Debug suite 1928/1928; reader suites under ASan 81/81 (0 reports) and under TSan 81/81 (0 warnings); clang-format 17 clean.
  • Row-mode throughput (Debug, idle machine, 400k rows): ~823–843 → ~889–898 ns/row (+~7%, ~60 ns/row); a recursive mutex lock/unlock measures ~9.7 ns.

A third-party review of the first commit found the C-wrapper metadata UAF; the follow-up commits fix it, and the reviewer confirmed it closed with an independent ASan harness (no new locking/lifetime issues).

Multiple threads sharing one TsFileReader could corrupt the heap or
segfault: tree queries raced on TsFileExecutor::query_exprs_, the first
concurrent metadata load tore TsFileIOReader's tsfile_meta_, table
queries with different batch sizes deleted the executor that live
TableResultSets borrow (a single-threaded use-after-free as well), and
get_timeseries_metadata() callers reset a shared metadata arena.

Give each TsFileReader a recursive per-reader mutex. Every public reader
method takes it, and every result set the reader returns is bound to the
same lock so next()/get_next_tsblock()/close() are serialized with each
other and with new queries on that reader. The table executor is now a
shared_ptr that is replaced rather than deleted, and result sets keep it
alive, so an earlier result set survives a later batch-size change.

Concurrent use is now safe but serialized; the contract is documented in
tsfile_reader.h, result_set.h, the C wrapper header and the C++ skill
reference. Add a six-case concurrency/lifetime stress test that aborted
with heap corruption or SIGSEGV before the fix and passes, together with
the neighboring reader suites, under ThreadSanitizer afterwards.
The C wrapper's tsfile_reader_get_timeseries_metadata_all() and
tsfile_reader_get_timeseries_metadata_for_devices() copied the C++
metadata after the reader call had returned and its lock was released.
The returned timeseries indexes live in a per-reader arena that the next
metadata call - from any thread - resets, so a concurrent caller freed
them while another thread was still converting (heap-use-after-free in
populate_c_metadata_map_from_cpp, reproduced under ASan).

Add TsFileReader::with_reader_lock() and run the metadata call and the
C conversion inside it, so the copy completes before any other thread
can reset the arena.  Document the helper and the C-wrapper guarantee in
the headers and the C++/C skill references.

Also harden result-set lifetime: the tree executor is now a shared_ptr
and every result set keeps the executor it borrows alive, which makes
destroying an unclosed result set after close() safe (destroy_query_
data_set() no longer has to dereference an executor that close() may
have deleted).  Iterating after close() remains invalid and documented.

Tests: add a C-wrapper concurrency test that reads every converted field
(device path, measurement name, row count), which reproduced the ASan
use-after-free without the wrapper fix and passes with it; add
QDSWithTimeGenerator, table queryByRow, prepared-query and
destroy-after-close concurrency cases; use ASSERT_NO_FATAL_FAILURE for
the fixture writers.  Verified with the full Debug suite (1928 tests),
the reader suites under ASan (81 tests, no reports) and under TSan (81
tests, no warnings).
Address the documentation nits from the review of a3025e9:

- with_reader_lock(): state that every other operation on the reader is
  blocked for the duration, and that fn must not wait for another thread
  or for a different reader (long serialization / cross-reader lock
  cycles);
- TsFileReader thread-safety notes: point metadata callers at
  with_reader_lock(), and state consistently that destroying a result
  set after close() is safe (memory only) while iterating it is not;
- TsFileTreeReader: document that the facade inherits the reader's
  serialized concurrency and metadata lifetime contract;
- cwrapper concurrency test: include <cstdio> for remove() instead of
  relying on a transitive include.
@ColinLeeo

Copy link
Copy Markdown
Contributor Author

Duplicate of #1164 (same commits, fork-based head). Keeping #1164.

@ColinLeeo ColinLeeo closed this Dec 1, 2026
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.35294% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.30%. Comparing base (37e0d06) to head (c15d328).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
cpp/src/reader/tsfile_reader.cc 77.41% 0 Missing and 7 partials ⚠️
cpp/src/reader/result_set.h 33.33% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1165      +/-   ##
===========================================
+ Coverage    69.25%   69.30%   +0.04%     
===========================================
  Files          791      792       +1     
  Lines        58526    58588      +62     
  Branches      9506     9526      +20     
===========================================
+ Hits         40531    40602      +71     
+ Misses       16251    16213      -38     
- Partials      1744     1773      +29     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

2 participants