Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,13 @@ CSVReader reader(infile, format);
- Communicates via `ThreadSafeDeque<CSVRow>`
- Operational errors propagate explicitly as `CSVError`; exception-enabled builds also transport user exceptions via `std::exception_ptr`
- A caller can consume queued rows while the internal worker is still finishing a
source window. Keep `eof_` atomic, and keep speculative-diagnostics merge and
snapshot operations under the same synchronization so snapshots remain coherent.
This protects metadata access from the library's worker; it does not make a
shared `CSVReader` generally safe for concurrent user operations.
source window. Keep source exhaustion worker-owned: `eof_` is a plain internal
flag, and consumer-side code may inspect it only after `CSVReadScheduler` joins.
Non-consuming row lookahead must use the synchronized queue front and may drive
`check_for_rows()`; it must not poll source exhaustion independently.
Keep speculative-diagnostics merge and snapshot operations under the same
synchronization so snapshots remain coherent. This narrow metadata protection
does not make a shared `CSVReader` generally safe for concurrent user operations.
- Critical: Fields spanning chunk boundaries must not corrupt

**Testing requirement:** Use ≥500K rows to cross 10MB boundary.
Expand Down
6 changes: 4 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ Notes:
- Internal architecture content lives under include/internal to stay close to implementation.
- Detailed file map, parser data flow, and component relationship diagrams are maintained in include/internal/ARCHITECTURE.md.
- Unicode BOM ownership and source-offset invariants are maintained in include/internal/ARCHITECTURE.md.
- Reader metadata publication (`CSVReader::eof()` and speculative diagnostics)
is maintained in include/internal/ARCHITECTURE.md.
- Reader worker-state ownership and speculative-diagnostics publication are
maintained in include/internal/ARCHITECTURE.md.
- Non-consuming row lookahead and its join-before-EOF invariant are maintained
in include/internal/ARCHITECTURE.md and THREADSAFE_DEQUE_DESIGN.md.
- Queue synchronization details are maintained only in THREADSAFE_DEQUE_DESIGN.md to avoid duplication.
- Always update or remove incorrect comments.
- Public API comments should remain user-facing and avoid references to internal helper/function details.
Expand Down
274 changes: 125 additions & 149 deletions README.md

Large diffs are not rendered by default.

11 changes: 7 additions & 4 deletions docs/source/Doxy.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ For exception-disabled builds and engine-owned resources, see
* csv::CSVReader::end()
* csv::CSVReader::read_row()
* csv::CSVReader::read_chunk()
* csv::CSVReader::has_next_row()
* csv::CSVReader::try_has_next_row()
* Convenience Functions
* csv::parse()
* csv::operator ""_csv()
Expand Down Expand Up @@ -127,7 +129,8 @@ high-level overview of writing CSVs.
* csv::DelimWriter::write_row()
* csv::DelimWriter::write_rows(): C++20 data-row batches
* csv::DelimWriter::try_open(): Open an owned output file
* csv::DelimWriter::try_write_row(): Checked rows or a complete DataFrame, in either exception mode
* csv::DelimWriter::try_write_row(): Checked single rows in either exception mode
* csv::DelimWriter::try_write_frame(): Checked complete DataFrame including its header
* csv::DelimWriter::try_write_rows(): Checked C++20 data-row batches
* csv::DelimWriter::try_flush()
* csv::DelimWriter::try_close(): Finish an owned output file
Expand All @@ -152,9 +155,9 @@ experimenting should follow these guidelines:
* Treat each csv::CSVReader as a single-consumer object. Do not concurrently call
row-consumption APIs, iterate, mutate, or destroy the same reader from user threads.
* A reader's own background worker may still overlap an ordinary single-threaded
caller after rows have been queued. csv::CSVReader::eof() is synchronized with
that worker, and csv::CSVReader::speculative_diagnostics() returns a coherent
snapshot rather than counters from a partially completed merge.
caller after rows have been queued. csv::CSVReader::speculative_diagnostics()
returns a coherent snapshot rather than counters from a partially completed
merge.
* That metadata guarantee is narrow: it does not make other operations on a shared
csv::CSVReader generally thread-safe.
* csv::CSVReader::iterator should only be used from one thread
Expand Down
2 changes: 1 addition & 1 deletion docs/source/csv_writing.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ With C++20, you can use `std::ranges::views` to elegantly reorder fields in a si
order, including sparse edits and structural column changes. It accepts const
frames and is available in C++11 and later. A frame with a schema but no rows
still writes its header. This convenience requires compiler exceptions enabled.
In either exception mode, `writer.try_write_row(error, frame)` writes the same
In either exception mode, `writer.try_write_frame(frame, error)` writes the same
document and reports errors explicitly.

The writer's delimiter, quoting, and buffering settings apply. With auto-flush
Expand Down
14 changes: 9 additions & 5 deletions docs/source/no_exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ void load_items() {
`try_read_row()` returns `false` with a clear error at EOF. A reader failure is
terminal; further reads report that failure. The same distinction applies to
`try_read_chunk()`, whose output may contain an already consumed prefix on error.
`try_has_next_row()` makes the same checked distinction without consuming the
next returnable row, although it may block while parsing and may discard records
excluded by the active variable-column policy.

Each checked operation clears stale errors before reporting its own result.
Inspect an error before making another checked call. `CSVError::context` is a
Expand Down Expand Up @@ -124,12 +127,13 @@ Default and row-batch DataFrame construction and valid frame-row iteration
remain available. Structural mutation invalidates outstanding proxies as
documented by each operation. Const access continues to produce read-only cells.

Writers expose `try_open()`, `try_write_row(error, ...)`, `try_flush(error)`, and
file-owning `try_close(error)`. Checked single-row writes accept `CSVRow`,
Writers expose `try_open()`, `try_write_row(error, ...)`,
`try_write_frame(frame, error)`, `try_flush(error)`, and file-owning
`try_close(error)`. Checked single-row writes accept `CSVRow`,
`DataFrameRow`, and `DataFrameColumn` directly in C++11 and later without
materializing a vector. Passing a complete DataFrame includes its header;
C++20 `try_write_rows(rows, error)` writes data rows only. A lone empty field is
quoted so it stays distinct from a zero-field row's blank line.
materializing a vector. `try_write_frame()` writes a complete DataFrame,
including its header; C++20 `try_write_rows(rows, error)` writes data rows only.
A lone empty field is quoted so it stays distinct from a zero-field row's blank line.

Buffered writes are complete only after a
successful explicit flush or close. Destruction performs a best-effort flush;
Expand Down
2 changes: 1 addition & 1 deletion include/csv.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
CSV for C++, version 5.7.2
CSV for C++, version 5.8.0
https://github.com/vincentlaucsb/csv-parser

MIT License
Expand Down
37 changes: 22 additions & 15 deletions include/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,19 +230,25 @@ Fields spanning chunk boundaries must not be split/corrupted.

Mmap and stream parsers must preserve the same externally observable behavior.

### Reader metadata publication during background parsing
### Reader worker state during background parsing

A single-threaded application can still have two threads touching parser state.
The consumer may wake after rows have been queued and call metadata accessors
while `CSVReadScheduler`'s worker finishes the current source window. Queue
synchronization protects row transport; it does not by itself protect state in
the source adapter or parse orchestrator.

The source-exhaustion flag in `CSVParserDriverBase` must remain atomic for both
`MmapParser` and `StreamParser`. `CSVReader::eof()` reads that flag without
joining the worker, preserving the non-blocking overlap between row consumption
and parsing. A plain `bool` here races the worker's final write even when the
application never shares its reader between user-created threads.
`CSVReader` intentionally has no public EOF accessor. Source exhaustion can be
observed while parsed rows remain queued, so it is not the same as reader
exhaustion. `has_next_row()` and `try_has_next_row()` answer whether a logical
row can be returned by driving `check_for_rows()` and taking a synchronized copy
of the queue front; a returnable row remains queued. Policy-excluded physical
records may be discarded while searching. The source-exhaustion flag in
`CSVParserDriverBase` is therefore a plain, worker-owned `bool`. `MmapParser` and
`StreamParser` read and write it on the active parser thread, while consumer-side
checks in `check_for_rows()` and `initial_read()` occur only after
`CSVReadScheduler` has joined. Preserve that ownership and join ordering instead
of exposing the flag to an unsynchronized observer.

Speculative diagnostics have a stronger snapshot requirement. The worker merges
seven cumulative counters after a speculative window, while the consumer may
Expand All @@ -251,20 +257,20 @@ short critical section so a returned snapshot belongs to one completed merge.
Independent atomic counters would remove individual data races but could still
combine values from different merge epochs and violate cross-counter invariants.

This synchronization is deliberately narrow:
The remaining synchronization is deliberately narrow:

- It makes `eof()` and `speculative_diagnostics()` safe against the reader's own
background worker. It does not make `CSVReader`, its iterator, row consumption,
- It makes `speculative_diagnostics()` safe against the reader's own background
worker. It does not make `CSVReader`, its iterator, row consumption,
destruction, or mutation generally safe across user threads.
- Operational parser errors remain worker-owned; consumer-side inspection occurs
only after the scheduler has joined.
- Source exhaustion and operational parser errors remain worker-owned;
consumer-side inspection occurs only after the scheduler has joined.
- `utf8_bom()` and `parse_worker_count()` expose state resolved during synchronous
reader initialization and are not mutated by later worker cycles.
- Neither accessor joins the worker. EOF is an atomic load; diagnostics lock only
long enough to copy or add the fixed set of counters.
- The diagnostics accessor does not join the worker; it locks only long enough to
copy or add the fixed set of counters.

Regression coverage lives in `tests/test_threadsafe_deque_race.cpp`
(`[issue_353]`). It observes both accessors while parsing a 500,000-row,
(`[issue_353]`). It observes diagnostics while parsing a 500,000-row,
greater-than-10MB fixture with distinct column values, using separate mmap and
stream `SECTION`s so ThreadSanitizer exercises both source adapters.

Expand Down Expand Up @@ -420,7 +426,8 @@ This invariant is canonical here and summarized in the root `AGENTS.md` guidance
- Speculative parallel parsing changes:
- speculative/scanner.hpp, speculative/validator.hpp, speculative/parallel_parser.hpp, parser/orchestrator.hpp, speculative/diagnostics.hpp, parser/mmap.cpp, parser/stream.hpp

- Reader worker/iteration behavior and concurrent metadata publication:
- Reader worker/iteration behavior, worker-owned EOF, and concurrent diagnostics
publication:
- csv_reader.hpp, csv_reader.cpp, csv_reader_iterator.cpp, parser/scheduler.hpp,
parser/driver.hpp, parser/orchestrator.hpp

Expand Down
16 changes: 16 additions & 0 deletions include/internal/THREADSAFE_DEQUE_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ The producer is intentionally not always running.
- The consumer drains queued rows and only then triggers the next worker cycle if EOF is not reached.
- This keeps parsed rows bounded in memory instead of allowing unbounded producer run-ahead.

## Non-Consuming Row Lookahead

`CSVReader::has_next_row()` and `try_has_next_row()` use
`ThreadSafeDeque::try_copy_front()` to copy the front `CSVRow` while holding the
queue mutex. A returnable row remains queued, so the next `read_row()`,
`read_chunk()`, or iterator operation still receives it. Records excluded by a
variable-column policy are popped while lookahead searches for the next logical
row.

The queue has one consumer: the parser worker only appends at the back. That
contract keeps the copied front stable until the consumer either leaves it
queued or discards an excluded record. Lookahead still reaches source exhaustion
through `CSVReader::check_for_rows()`, which joins the worker before inspecting
parser EOF; the queue peek does not require an atomic source-exhaustion flag.

## Two-Thread Model

| Step | Consumer (read_row) | Producer (read_csv worker) | Shared State / Note |
Expand Down Expand Up @@ -257,6 +272,7 @@ t=5: Consumer: pop_front() → returns row1
| **Producer** | [csv_reader.cpp](../csv_reader.cpp) | kill_all() terminal signal |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | push_back() producer path |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | pop_front() consumer path |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | try_copy_front() synchronized lookahead |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | wait() condition protocol |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | notify_all() wake-up state |
| **Queue** | [thread_safe_deque.hpp](thread_safe_deque.hpp) | kill_all() terminal publication |
Expand Down
50 changes: 48 additions & 2 deletions include/internal/csv_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,11 @@ namespace csv {
#ifdef _MSC_VER
#pragma region Reading helpers
#endif
bool CSVReader::accept_row(CSVRow&& candidate, CSVRow* single_row, std::vector<CSVRow>* batch_rows) {
bool CSVReader::row_is_returnable(const CSVRow& candidate) {
// Any queued record proves that the previous source window made
// progress, even when policy filtering excludes the record.
this->_read_requested = false;

const auto policy = this->_format.variable_column_policy;
const size_t next_row_size = candidate.size();

Expand All @@ -200,6 +204,14 @@ namespace csv {
return false;
}

return true;
}

bool CSVReader::accept_row(CSVRow&& candidate, CSVRow* single_row, std::vector<CSVRow>* batch_rows) {
if (!this->row_is_returnable(candidate)) {
return false;
}

if (single_row != nullptr) {
*single_row = std::move(candidate);
} else if (batch_rows != nullptr) {
Expand All @@ -209,7 +221,6 @@ namespace csv {
}

this->_n_rows++;
this->_read_requested = false;
return true;
}

Expand Down Expand Up @@ -291,6 +302,34 @@ namespace csv {
return false;
}

bool CSVReader::try_has_next_row(CSVError& error) {
error.clear();
while (this->check_for_rows()) {
CSVRow candidate;
if (!this->records->try_copy_front(candidate)) {
continue;
}

if (this->row_is_returnable(candidate)) {
return true;
}

if (error_) {
error = error_;
return false;
}

// Keep this lookahead loop separate from try_read_row(): only callers
// requesting a peek should pay for the locked front-row copy. Under
// CSVReader's single-consumer contract, the copied front remains the
// queue front until this discard.
this->records->pop_front();
}

error = error_;
return false;
}

bool CSVReader::try_read_chunk(std::vector<CSVRow>& out, size_t max_rows, CSVError& error) {
error.clear();
out.clear();
Expand Down Expand Up @@ -319,6 +358,13 @@ namespace csv {
return true;
}
#if CSV_EXCEPTIONS_ENABLED
bool CSVReader::has_next_row() {
CSVError error;
const bool has_row = try_has_next_row(error);
internals::throw_error(error);
return has_row;
}

bool CSVReader::read_row(CSVRow& row) {
CSVError error;
const bool read = try_read_row(row, error);
Expand Down
43 changes: 34 additions & 9 deletions include/internal/csv_reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ namespace csv {
* - Custom behavior can be defined by overriding bad_row_handler in a subclass
*
* **Streaming semantics:** CSVReader is a single-pass streaming reader. Every read
* operation — read_row(), the iterator interface — pulls rows permanently
* from the internal queue. Rows consumed by one interface are not visible to another.
* There is no rewind or seek.
* operation — read_row(), read_chunk(), and the iterator interface — pulls rows
* permanently from the internal queue. Rows consumed by one interface are not
* visible to another. has_next_row()/try_has_next_row() can check for a
* logical next row without consuming it, but there is no rewind or seek.
*
* **Ownership and sharing:** CSVReader is non-copyable and move-enabled. It manages
* live parsing state (worker thread, internal queue, and optional owned stream), so
Expand Down Expand Up @@ -265,6 +266,27 @@ namespace csv {
*/
bool try_read_row(CSVRow& row, CSVError& error);

/** Check whether a logical next row is available without consuming it.
*
* This may read from the source and block while parsing completes. Rows
* excluded by the active variable-column policy may be discarded while
* searching for the next row that a consumption API would return.
*
* @returns `true` if the next call to a row-consumption API can produce a
* row, or `false` after ordinary exhaustion.
*
* @note This reader remains a single-consumer object. Do not call this
* concurrently with other reader operations.
*/
#if CSV_EXCEPTIONS_ENABLED
bool has_next_row();
#endif
/** Check for a logical next row, distinguishing exhaustion from failure.
* This has the same blocking, filtering, and non-consumption semantics
* as has_next_row(). Returns false with a clear error at ordinary exhaustion.
*/
bool try_has_next_row(CSVError& error);

/** Read up to `max_rows` rows into a caller-owned batch buffer.
*
* This is the easiest way to process a CSV in bounded batches without
Expand Down Expand Up @@ -296,8 +318,6 @@ namespace csv {
*/
bool try_read_chunk(std::vector<CSVRow>& out, size_t max_rows, CSVError& error);

/** Returns true if we have reached end of file */
bool eof() const noexcept { return this->parser->eof(); }
///@}

/** @name CSV Metadata */
Expand Down Expand Up @@ -328,11 +348,11 @@ namespace csv {

/** @name CSV Metadata: Attributes */
///@{
/** Whether or not the file or stream contains valid CSV rows,
* not including the header.
*
* @note Gives an accurate answer regardless of when it is called.
/** Whether no data rows have been successfully returned yet.
*
* This is historical consumption metadata equivalent to `n_rows() == 0`;
* it does not report whether unread rows remain. Use has_next_row() or
* try_has_next_row() for non-consuming lookahead.
*/
CONSTEXPR bool empty() const noexcept { return this->n_rows() == 0; }

Expand Down Expand Up @@ -479,6 +499,11 @@ namespace csv {
* Shared consumer-side logic used by both single-row and batch reads.
*/
///@{
/** Mark parser progress and apply variable-column policy.
* A THROW-policy mismatch records a terminal error in error_.
*/
bool row_is_returnable(const CSVRow& candidate);

/** Apply variable-column policy to a parsed row and emit it if accepted. */
bool accept_row(CSVRow&& candidate, CSVRow* single_row, std::vector<CSVRow>* batch_rows);

Expand Down
Loading
Loading