Skip to content

Reset the SQLite input format between streamed inputs - #129140

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:sqlite-input-format-reset-parser
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:sqlite-input-format-reset-parser

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed lost rows when several INSERT ... FORMAT SQLite queries are combined into one asynchronous insert batch (asynchronous inserts are enabled by default): only the first query's rows were inserted, and a query that followed a failed one inserted the failed query's remaining rows instead of its own.

Description

Related: #128943 (the same defect class in MsgPack)
Related: #129109 (the same defect class in Npy)

On 26.10.2.103, of two concurrent INSERT INTO t FORMAT SQLite queries with default settings, often only the first one's rows are inserted (20 of 40 rows in 10 tries), and both clients get success; system.asynchronous_insert_log logs the lost entry Ok with 0 rows.

StreamingFormatExecutor reuses one input format for all entries of an asynchronous insert batch (and for Kafka, NATS, RabbitMQ and FileLog messages) and calls resetParser between them, also after a parse error. SQLiteInputFormat did not override it, so its per-input state survived: sqlite_finished made every later input insert nothing; after an input that failed mid-read, initialized made the next one keep reading the failed input's statement; and the statement reader keeps facts about the first statement's columns, which would reject a valid TEXT 'nan' in a later input's REAL column once the flags are cleared.

SQLiteInputFormat::resetParser now finalizes the statement, closes the database, frees the in-memory copy of the input, re-creates the statement reader and clears both flags. file, url, s3 and synchronous inserts build one format per input and are unchanged.

The new test queues three valid databases, a failing one followed by a valid one, and a typeless column followed by a REAL one into one batch each. On master it gives [1,2], [7] and [2.5]; with the fix it passes 50/50 with randomized settings.

MySQLDump and One have the same defect (a later input of a batch is rejected or dropped); they are not addressed here.


Workflow [PR]
Sync PR [sync-upstream/pr/129140]

`StreamingFormatExecutor` reuses one input format for every entry of an
asynchronous insert batch (and for the messages of Kafka, NATS, RabbitMQ,
FileLog) and calls `resetParser()` between them. `SQLiteInputFormat` had no
override, so its per-input state survived:

- `sqlite_finished` stayed set after the first input, so every later input
  of the batch inserted 0 rows and was logged `Ok`. With `async_insert` on by
  default, two concurrent `INSERT ... FORMAT SQLite` queries often kept only
  the first one's rows.
- `initialized` stayed set after an input that failed mid-read, so the next
  input kept stepping the failed input's statement and inserted its
  remaining rows instead of its own.
- `statement_reader` keeps facts about the first statement it read
  (undeclared columns, exact storage class), so a later input's `REAL`
  column was checked as the earlier input's typeless one and a valid TEXT
  'nan' was rejected.

The override finalizes the statement, closes the database, frees the
in-memory copy of the input, re-creates the statement reader and clears
both flags. The order matters: `sqlite3_close` fails with `SQLITE_BUSY`
while a statement is unfinalized, and the deserialized database reads the
copy without owning it, so the connection is closed explicitly before the
`SQLiteDatabase` is reset (its move-assignment would free the copy first).

`MySQLDump` and `One` have the same defect class; they are fixed separately.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test does not prove that one format object was reused (entries could be flushed separately) DISAGREE Red on unfixed master with the batched-reuse output [1,2] / [7] / [2.5]; on the fixed server each table's entries share one flush. A split batch can only make the test pass on a buggy server, and Bugfix validation checks it fails on master. Asserting a shared flush_query_id would make it flaky when another test flushes all queues. Same structure as the merged 05493_msgpack_async_insert_after_invalid_entry.
2 💡 Use Critical Bug Fix for data loss DISAGREE I leave that category to a maintainer's call.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261104-003400

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05498_sqlite_async_insert_batch forces each table's entries into one batch (busy timeout 100 s, explicit flush): on master it prints [1,2], [7], [2.5] on every run.
b Root cause explained? StreamingFormatExecutor reuses one format per batch and calls resetParser between entries; SQLiteInputFormat had no override, so sqlite_finished, initialized and the statement reader's first-row facts carried over to the next input.
c Fix matches root cause? Yes. The per-input state is dropped in resetParser, the hook made for this, as MsgPack and Npy do.
d Test intent preserved / new tests added? New test, one case per stale member. Removing only the statement-reader reset makes the third case fail again, so that case is live.
e Both directions demonstrated? Fails on master and on the unfixed base commit with the exact output above; passes with the fix, 50/50 with randomized settings.
f Fix is general across code paths? Every per-input member of the format is reset; the normal and the error paths go through the same resetParser. MySQLDump and One have the same defect class in other files; not addressed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? The state does not depend on column types. Covered: several valid inputs incl. a different table name, an input failing mid-read, a typeless then a REAL column; also checked by hand: a non-database and a truncated database before valid inputs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; a single input is parsed as before.
i Invariants and contracts preserved? After resetParser the format parses the next input as a fresh one. The statement is finalized before the database is closed, and the database is closed before the input copy it reads from is freed.

Session id: cron:clickhouse-impl-self-slot-57:20261104-000900

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @vitlibar, could you review this and add the can be tested label so CI runs? SQLiteInputFormat had no resetParser override, so when an asynchronous insert batch reused one format for several FORMAT SQLite inputs, the first input's sqlite_finished/initialized state made later inputs insert nothing or keep reading the old statement; the override now finalizes the statement, closes the database and clears that state.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9c10bc]

Summary: ✅


AI Review

Summary

PR #129140, reviewed at f9c10bcfe6bca9a3b8a7be193a7729ea0ee51772, fixes state leaking between streamed SQLite inputs by finalizing the statement, closing the database before freeing its input buffer, recreating SQLiteStatementReader, and clearing the completion and initialization flags. The regression test covers successive valid databases, recovery after a parsing exception, and changing column declarations. No actionable findings.

Missing context / blind spots
  • ⚠️ Runtime validation was not repeated locally because this checkout has no ClickHouse binary or build directory. The author reports failure on the unfixed code and 50 successful runs with the fix. The current CI run has not yet produced results for the new test; Fast test excludes SQLite. A completed stateless run and bugfix validation for 05498_sqlite_async_insert_batch would independently confirm that evidence.
Final Verdict

Status: ✅ Approve. No code changes requested; no inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Nov 4, 2026
@Algunenano

Copy link
Copy Markdown
Member

@groeneai If you open 3 PRs with the same issue in different formats, maybe it's time for an architectural change that prevents this issue from being possible

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged, agreed. I won't open separate PRs for the two other formats I found with the same problem (MySQLDump, One). I'm investigating a change at the StreamingFormatExecutor / IInputFormat level so that a reused input format cannot carry state from one streamed input to the next, and I'll follow up here with a PR (or my findings).

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f9c10bcfe with master 229b8fcdf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 22c6d431f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

I opened #129209: StreamingFormatExecutor now reuses an input format only if it is registered with FormatFactory::markInputFormatSupportsResetParser, and creates any other format anew for each input, so a format with an incomplete resetParser can no longer carry state into the next input. It covers SQLite, One, Npy, MySQLDump, JSON and DWARF with no per-format code, completes the reset of seven reused formats, and extends 02187_async_inserts_all_formats with a two-input batch per format (13 cases fail on master). It replaces this PR and #129109; I closed #129109 and left this one open for you to decide.

alexey-milovidov pushed a commit to bobrik/ClickHouse that referenced this pull request Nov 13, 2026
…self

StreamingFormatExecutor (async insert flushes, Kafka, Kafka2, NATS,
RabbitMQ, FileLog) kept one input format object for many independent
inputs and called resetParser() between them, trusting every format to
bring itself back to the state of a fresh object. Nothing enforced that:
32 of the 82 input format names kept some per-input field (One `done`,
Npy `read_rows`, MySQLDump `table_name` and column mapping, SQLite
flags and database, JSON `parse_as_json_each_row`, DWARF section
extractors, TSV `first_row`, CustomSeparated `columns` and the detected
header, RowBinaryWithNamesAndTypes `read_data_types`, Template
`row_num`), so a later input of an async insert batch or a later
message lost rows, was rejected, or was parsed with the previous
input's state. Per-format resetParser fixes (ClickHouse#128943, ClickHouse#129109, ClickHouse#129140)
leave the default unsafe for the next format and the next field.

Invert the default: a format is reused only when its name is registered
with FormatFactory::markInputFormatSupportsResetParser; any other format
is released after each input and created anew for the next one. The
executor now takes a format creator and an AddingDefaultsTransform
creator (the transform holds a reference to the format). The streaming
engines compute their single-threaded parser resources once and share
them between created formats.

Marked: the 50 names whose reset is complete and 26 hot names completed
here with one statement each (TSV first_row, CustomSeparated columns,
WithNamesAndTypes is_header_detected, RowBinary read_data_types,
Template row_num). Reuse matters for them: a fresh CapnProto, Template,
Protobuf, Regexp or AvroConfluent object reads or compiles schemas.
Not marked, so re-created with no per-format code: One, Npy, MySQLDump,
SQLite, JSON, DWARF. DWARF's incomplete resetParser is deleted.

02187_async_inserts_all_formats now also inserts every format as one
batch of two different inputs, plus targeted cases for the leaks that
a same-shaped pair does not show, and a FileLog case.

Closes ClickHouse#122351

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants