Skip to content

docs: explain the second query_log row of a batch insert - #2000

Open
sankalpsthakur wants to merge 10 commits into
ClickHouse:mainfrom
sankalpsthakur:cursor/fix-1997-native-insert-query-id-efec
Open

sankalpsthakur wants to merge 10 commits into
ClickHouse:mainfrom
sankalpsthakur:cursor/fix-1997-native-insert-query-id-efec

Conversation

@sankalpsthakur

@sankalpsthakur sankalpsthakur commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1997

What this PR does

A batch insert can show two INSERT rows in system.query_log. From ClickHouse 26.2, async_insert is on by default. The first row is the INSERT of the client, with the query_id of the client. The second row is the flush of the server, with a new query_id. Only one write reaches the table. The query_id and flush_query_id columns of system.asynchronous_insert_log link the two IDs.

The client cannot set the query_id of the flush. To get one query_id for a batch, set async_insert=0 in Options.Settings, or in clickhouse.WithSettings on the context of PrepareBatch. The driver already sends the settings and the query ID, so this PR does not change the behavior of the driver.

  • Docs: a note in the batch insert sections of docs/clickhouse-api.mdx and docs/database-sql-api.mdx.
  • Tests: tests/issues/issue_1997_test.go sets async_insert=0 in both ways, on the Native and HTTP protocols, for the ClickHouse API and for database/sql. On ClickHouse Cloud the tests flush and read system.query_log on all replicas.

An earlier version of this PR added Options.SyncBatchInsert and a sync_batch_insert DSN key. This version removes both, because async_insert=0 in the settings gives the same result. #1848 is open for an API that disables async inserts in general.

Validation

  • go build ./..., gofmt and go test -c ./tests/issues pass locally.
  • The tests/issues tests need a ClickHouse server and have not run on this version yet. CI is their first run.

AI coding tools assisted with the change and this description.

@CLAassistant

CLAassistant commented Sep 1, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@sankalpsthakur
sankalpsthakur marked this pull request as draft September 2, 2026 00:23
@sankalpsthakur
sankalpsthakur force-pushed the cursor/fix-1997-native-insert-query-id-efec branch from 15159aa to 597b95c Compare September 3, 2026 20:53
ClickHouse 26.3+ defaults async_insert=1, so PrepareBatch/Send was
logged twice in system.query_log: the client INSERT under the intended
query_id, then a server flush that rewrites the table as database.table
and assigns a new UUID. PrepareBatch already buffers client-side; send
async_insert=0 unless the caller set it on the context or connection.
@sankalpsthakur
sankalpsthakur force-pushed the cursor/fix-1997-native-insert-query-id-efec branch from 597b95c to 5d35867 Compare September 3, 2026 21:34
@sankalpsthakur
sankalpsthakur marked this pull request as ready for review September 3, 2026 21:34
@must108
must108 self-requested a review September 3, 2026 22:01
Comment thread conn_batch.go Resolved
Comment thread conn_batch.go Resolved
Comment thread tests/issues/issue_1997_test.go Resolved
@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Claude review

The PR adds Options.SyncBatchInsert (DSN sync_batch_insert). When it is set, batch inserts send async_insert=0, so one batch has one query_id in system.query_log. The default behavior is now the same as main, which resolves the earlier must-fix finding. Maintainers must decide if the new option is necessary before merge.

Key concerns:

  • SyncBatchInsert gives almost the same result as the connection setting Settings{"async_insert": 0}. The new exported field and DSN parameter need a clear reason.
  • The new helper changes the precedence between WithAsync and a query-level async_insert setting for batches. main and the Exec path let WithAsync win.
  • The regression tests do not obey the ClickHouse Cloud rules for system.query_log, and the HTTP test cannot connect when TLS is necessary.
  • The PR title and description still describe the old design (async_insert=0 by default). The issue is not fixed for a caller who does not set the option.

Blind spots:

  • I did not run the tests. I did not confirm that ClickHouse 26.3+ has async_insert=1 as the server default, which the docs notes and the code comment state as a fact.
  • On a server with async_insert=0 as default, the three regression tests pass with or without the fix.

Verdict: 💬 Needs discussion

General findings

  • ⚠️ Should fix — PR title and description do not agree with the code
    The description says the change "defaults batch inserts to async_insert=0" and the title says fix: keep a single query_id. The code at the head commit changes nothing by default: a caller must set SyncBatchInsert.

    • Update the title and description to describe the opt-in, because they become the merge commit and the release note.
    • Fixes #1997 closes the issue, but the reported behavior stays for a caller who does not set the option. Make sure that the issue reporter accepts an opt-in before the issue closes.
  • 💡 Nit — nit: regression tests do not fail without the fix on servers that default to async_insert=0
    The three tests in tests/issues/issue_1997_test.go pass without SyncBatchInsert on each server where async_insert is 0 by default. Thus only the newest server in the CI matrix gives evidence. A comment in the test that states this limit, or a CheckMinServerVersion guard, makes the coverage clear.

Inline comments are attached to the relevant lines. This summary updates in place on re-review.

@must108 must108 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @sankalpsthakur, thanks for your contribution! Could you please address the issues flagged by the agent? We will most likely have to discuss this change further, but until then, this would be great.

Keep the batch default of async_insert=0 when the caller did not opt in
(the 26.3+ duplicate query_id bug). Treat WithAsync/WithStdAsync as a
query-level opt-in before the connection setting, matching AsyncInsert.

Add an HTTP PrepareBatch/Send regression next to the native test.
@sankalpsthakur

Copy link
Copy Markdown
Contributor Author

Addressed the review notes that are code:

  • WithAsync / WithStdAsync on the batch context is now treated as a query-level opt-in (async_insert=1, wait_for_async_insert from the wait flag) before the connection setting.
  • Added TestIssue1997_HTTPInsertSingleQueryID for the HTTP PrepareBatch/Send path.

The default of sending async_insert=0 when the caller did not set it is the #1997 fix (26.3+ server default otherwise splits one batch into two query_ids). Happy to discuss keeping that default vs. inheriting the server profile.

@sankalpsthakur

Copy link
Copy Markdown
Contributor Author

@must108 thanks, I added coverage for the HTTP batch path and database/sql in tests/issues/issue_1997_test.go (native, HTTP, database/sql, with race detector on 26.3). Could you take another look when you have a moment?

@sankalpsthakur

Copy link
Copy Markdown
Contributor Author

agreed, batches no longer force async_insert=0, server setting applies unless the caller opts in with SyncBatchInsert or sync_batch_insert=true, ptal

…ive-insert-query-id-efec

# Conflicts:
#	conn_batch.go
#	conn_http_batch.go
@sankalpsthakur

Copy link
Copy Markdown
Contributor Author

merged main, resolved conflict with #2068 by reusing applyBatchAsyncInsertSettings, explicit async_insert still wins, ptal

Comment thread clickhouse_options.go Outdated
ConnMaxLifetime time.Duration // default 1 hour
ConnOpenStrategy ConnOpenStrategy
FreeBufOnConnRelease bool // drop preserved memory buffer after each query
SyncBatchInsert bool // send async_insert=0 on batch inserts unless async_insert is set explicitly

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Should fix — show that SyncBatchInsert is necessary

SyncBatchInsert sends async_insert=0 for batches, which a caller can already get with Options.Settings{"async_insert": 0} or WithSettings on the batch context.

  • The only difference is that Exec inserts keep the server default. The PR does not give a use case for that difference.
  • The connection setting silently cancels the option (Settings{"async_insert": 1} + SyncBatchInsert: true gives async batches). A caller can set the two and get no error.
  • If the option stays, add it to docs/config-reference.mdx, docs/configuration.mdx, and the DSN parameter list in README.md, and add a DSN parse case to clickhouse_options_test.go.
  • Alternative: remove the field and keep only a docs note that recommends async_insert=0 for callers who need one query_id.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not necessary, so i removed it in be7583d. Options.Settings{"async_insert": 0} sends the same setting for every query on the connection, and WithSettings on the context of PrepareBatch sends it for one batch, so a caller can keep async Exec inserts and still get a sync batch. #1848 is open for a general way to disable async inserts. the docs now show both ways (7d5fb88).

Comment thread conn_batch.go Outdated
// An explicit query-level or connection-level `async_insert` always wins.
func applyBatchAsyncInsert(opt *Options, o *QueryOptions) {
if o.settings != nil {
if _, ok := o.settings["async_insert"]; ok {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Should fix — query-level async_insert now cancels WithAsync for batches

This early return changes the behavior of main, where applyBatchAsyncInsertSettings always writes the WithAsync settings, as asyncInsert does for Exec.

  • WithSettings{"async_insert": 1} + WithAsync(false): main sends wait_for_async_insert=0. This PR sends no wait_for_async_insert, so the server waits for the flush.
  • WithSettings{"async_insert": 0} + WithAsync(true): main sends an async batch. This PR sends a sync batch, while Exec with the same context stays async.
  • This check is not necessary for the opt-in. Move it below the o.async.ok block, then update the query setting wins over WithAsync unit test and the two docs notes.
-	if o.settings != nil {
-		if _, ok := o.settings["async_insert"]; ok {
-			return
-		}
-	}
 	if o.async.ok {
 		...
 		return
 	}
+	if _, ok := o.settings["async_insert"]; ok {
+		return
+	}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed by removing the helper in be7583d. the diff now touches no go file outside tests/, so applyBatchAsyncInsertSettings writes the WithAsync settings as it does on main.

Comment thread tests/issues/issue_1997_test.go Outdated
require.NoError(t, conn.QueryRow(ctx, fmt.Sprintf("SELECT count() FROM %s", table)).Scan(&stored))
require.Equal(t, uint64(10), stored)

if err := conn.Exec(ctx, "SYSTEM FLUSH LOGS"); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Should fix — read system.query_log from all replicas on ClickHouse Cloud

On ClickHouse Cloud the INSERT and the log query can go to different replicas, so uniqExact(query_id) can return 0 and the test is flaky.

  • When clickhouse_tests.CloudClickHouse is true, use SYSTEM FLUSH LOGS ON CLUSTER 'default' and clusterAllReplicas('default', system.query_log), as tests/issues/issue_2067_test.go does.
  • The same change is necessary in the HTTP test and the database/sql test in this file. A shared helper for the flush and the two assertions removes the three copies.
  • t.Skipf on a SYSTEM FLUSH LOGS error hides a failure of the main assertion. Use require.NoError.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in b2cd7b5. one helper replaces the three copies; on cloud it runs SYSTEM FLUSH LOGS ON CLUSTER 'default' and reads clusterAllReplicas('default', system.query_log), and polls until the insert row is in the log, as issue_2067_test.go does.

Comment thread tests/issues/issue_1997_test.go Outdated
// regression: httpBatch.Send also honors Options.SyncBatchInsert.
func TestIssue1997_HTTPInsertSingleQueryID(t *testing.T) {
env, err := clickhouse_tests.GetTestEnvironment("issues")
require.NoError(t, err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Should fix — HTTP test ignores TLS and the suite options

These hand-made options always use env.HttpPort without TLS, so the test cannot connect when CLICKHOUSE_USE_SSL=true (ClickHouse Cloud).

  • Build the options with clickhouse_tests.ClientOptionsFromEnv(env, clickhouse.Settings{}, true), then set SyncBatchInsert = true. This function selects the HTTPS port and the TLS configuration, and it does not add async_insert.
  • The database/sql test covers only the native protocol. Add an HTTP DSN case if the option stays.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in b2cd7b5. the options come from ClientOptionsFromEnv, so HTTP gets the HTTPS port and TLS on cloud. the database/sql test runs on native and HTTP now.

Comment thread clickhouse_options.go Outdated
case "sync_batch_insert":
syncBatch, err := strconv.ParseBool(params.Get(v))
if err != nil {
return fmt.Errorf("clickhouse [dsn parse]: sync_batch_insert: %s", err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Nit — nit: wrap the parse error with %w

%s drops the error chain. The adjacent http_proxy case already uses %w.

Suggested change
return fmt.Errorf("clickhouse [dsn parse]: sync_batch_insert: %s", err)
return fmt.Errorf("clickhouse [dsn parse]: sync_batch_insert: %w", err)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no longer applies, the sync_batch_insert dsn key is gone with the option in be7583d.

…loud-safe

The tests set async_insert=0 themselves, with Options.Settings or with
WithSettings on the context of the batch. They no longer use
Options.SyncBatchInsert. They cover the Native and HTTP protocols, for the
ClickHouse API and for database/sql.

The test suite sets async_insert=0 on its connections, so the tests remove
it from the client settings first.

On ClickHouse Cloud, the tests flush and read system.query_log on all
replicas. One helper replaces the three copies of the log check. It fails
the test when the flush fails, and it polls until the row of the INSERT is
in the log. The client options come from ClientOptionsFromEnv, so the HTTP
cases use the TLS port and the settings of the test suite.
async_insert=0 in Options.Settings, or in WithSettings on the context of the
batch, gives the same result. The new option is not necessary. Remove the
option, the sync_batch_insert DSN key, the unit test, and the notes in the
docs. The option was never in a release.

This restores applyBatchAsyncInsertSettings in the Native and HTTP batch
code. WithAsync overrides a query-level async_insert setting again, as it did
before this PR.
ClickHouse 26.2 and later runs inserts as async inserts by default. An
async insert adds a second INSERT row to system.query_log, with the
query_id of the server flush. Explain this in the batch insert sections of
the ClickHouse API page and the database/sql page. Show how to get one
query_id: set async_insert=0 in Options.Settings, or in WithSettings on the
context of the batch.
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.

4 participants