Skip to content

system.query_log: single native-protocol INSERT logged twice with two distinct query_id values — server rewrites query with fully-qualified table name and assigns new UUID #1997

Open

Description

@margasystems

Observed

  1. A single PrepareBatch + Send() call from the Go native client — with an explicit, known query_id set via clickhouse.WithQueryID — produces two QueryStart/QueryFinish pairs in system.query_log, each with a distinct query_id and both with is_initial_query = 1.
  2. The server-generated second entry rewrites the query: the client sent INSERT INTO dup_test_events (id, value) FORMAT Native; the server logged INSERT INTO vts_dup_test3.dup_test_events (id, value) FORMAT Native — fully qualifying the table name and altering formatting — under a new server-assigned UUID.
  3. Physical storage (system.parts) on a plain MergeTree table (no deduplication mechanism) shows exactly the expected row count (10 rows, not 20), proving only one write reached storage despite two log entries each claiming written_rows = 10.

Expected behaviour

Exactly one QueryStart/QueryFinish pair per client Send() call, carrying the client-supplied query_id. The server should not generate an additional top-level query_log entry with a rewritten query string and a new UUID for the same physical insert.

Code example

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2"
)

const insertDupTestEvents = `INSERT INTO dup_test_events
(
    id,
    value
)`

const explicitQueryID = "vts-explicit-query-id-test-0001"

func main() {
	options := &clickhouse.Options{
		Addr: []string{"127.0.0.1:9000"},
		Auth: clickhouse.Auth{
			Database: "vts_dup_test3",
			Username: "vts",
			Password: "vts123",
		},
		Compression:     &clickhouse.Compression{Method: clickhouse.CompressionLZ4},
		DialTimeout:     5 * time.Second,
		MaxOpenConns:    5,
		MaxIdleConns:    5,
		ConnMaxLifetime: 10 * time.Minute,
	}

	conn, err := clickhouse.Open(options)
	if err != nil {
		log.Fatalf("open: %v", err)
	}
	defer conn.Close()

	ctx := clickhouse.Context(context.Background(), clickhouse.WithQueryID(explicitQueryID))
	if err := conn.Ping(ctx); err != nil {
		log.Fatalf("ping: %v", err)
	}

	batch, err := conn.PrepareBatch(ctx, insertDupTestEvents)
	if err != nil {
		log.Fatalf("prepare batch: %v", err)
	}
	defer batch.Close()

	for i := 0; i < 10; i++ {
		if err := batch.Append(uint64(i), fmt.Sprintf("row-%d", i)); err != nil {
			log.Fatalf("append row %d: %v", i, err)
		}
	}

	if err := batch.Send(); err != nil {
		log.Fatalf("send: %v", err)
	}
	fmt.Printf("sent with explicit query_id=%s\n", explicitQueryID)
}

After running, query:

SELECT
    query_id,
    initial_query_id,
    is_initial_query,
    type,
    written_rows,
    query
FROM system.query_log
WHERE (query ILIKE '%dup_test_events%') AND (query ILIKE '%INSERT%')
ORDER BY event_time_microseconds ASC
FORMAT Vertical;

And verify physical row count:

SELECT sum(rows)
FROM system.parts
WHERE database = 'vts_dup_test3'
  AND table = 'dup_test_events'
  AND active = 1;

Error log

No error returned to the client. The anomaly is silent —
batch.Send() returns nil. The duplicate entry is only
visible in system.query_log.

Details

Environment

  • clickhouse-go version: v2.40.3
  • Interface: ClickHouse API (clickhouse.Open, native protocol)
  • Go version: (please fill in)
  • Operating system: (please fill in)
  • ClickHouse version: 26.7.1.1315
  • Is it a ClickHouse Cloud? No (self-hosted single node)
  • ClickHouse Server non-default settings, if any: None relevant; isolated test database, no replicas, no distributed tables, no materialized views
  • CREATE TABLE statement:
CREATE DATABASE IF NOT EXISTS vts_dup_test3;

CREATE TABLE vts_dup_test3.dup_test_events
(
    id    UInt64,
    value String
)
ENGINE = MergeTree()
ORDER BY id;
  • Sample data: 10 synthetic rows (id 0–9, value "row-0" … "row-9"), no obfuscation needed.

Activity

  1. margasystems commented on Aug 31, 2026

    @margasystems
    Author

    Update with additional findings since filing this:

    1. Confirmed independent of the client library version. Reproduces identically on both v2.40.3 (originally reported) and the latest v2.48.0 — same two-query_id pattern, same row counts, same query-text difference. Ruling out a client-side fix.

    2. Confirmed the client only ever issues one request. Setting an explicit query_id via clickhouse.Context(ctx, clickhouse.WithQueryID("my-id")) before the single PrepareBatch/Send() call shows that chosen ID lands on exactly one of the two logged entries (the unqualified, literal-text one). The other entry gets its own independently-generated UUID that the client never created or passed anywhere — proving the second entry isn't a second client-issued request, but something generated server-side.

    3. Bisected across ClickHouse server versions with the identical minimal repro (PrepareBatch/Append(10 rows)/Send(), plain MergeTree, no replicas/distributed tables):

    ClickHouse version Duplicate query_id?
    24.8.14.39-lts Clean — 1 query_id per insert
    25.3.14.14-lts Clean — 1 query_id per insert
    26.3.27.3-lts Reproduces
    26.7.1.1315-stable Reproduces

    So this looks like a regression introduced somewhere between the 25.3 and 26.3 server releases, not something specific to a single non-LTS build — it affects the current LTS line (26.3) too. Given (2) above, I'd guess this points to a server-side query-logging change in that range rather than anything in the Go client, though I don't have visibility into the ClickHouse server source to confirm exactly what changed.

    Given system.parts conclusively shows only the true row count ever lands on disk (no actual duplicate write, confirmed on a non-deduplicating MergeTree table across every version tested), this looks like a query-log bookkeeping/instrumentation issue rather than a data-integrity risk — but still worth fixing since it silently doubles what shows up in system.query_log metrics/monitoring built on top of it.

  2. added a commit that references this issue on Nov 11, 2026
  3. polyglotAI-bot commented on Nov 13, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Close — no-op: works as intended
    The second row is the flush of a server-side async insert: ClickHouse turned on async_insert by default in 26.2, and the client sends only one query. PR #2000 adds a note about this to the batch-insert docs; it can be reviewed separately, and it uses Refs, so it does not close this issue.

    Analysis: system.settings_changes on 26.9.1 has the row 26.2: async_insert 0 → 1, "Enable async inserts by default.", which agrees with the bisect in the issue (25.3 clean, 26.3 shows it). With async_insert=1, the server puts the rows of the client INSERT in a buffer and writes them later in a flush query. The server logs the flush with query_kind = AsyncInsertFlush, a new query_id, and the table name with the database name. system.asynchronous_insert_log links the two IDs (query_id → flush_query_id), and the table gets each row once. The client sends one Query packet with the caller's query_id (conn_send_query.go:20) and cannot set the query_id of the flush. To get one query_log row for a batch, set async_insert=0 in Options.Settings or with clickhouse.WithSettings on the context of PrepareBatch; to count inserts in system.query_log, filter on query_kind.

    Reproduction: complete program and output
    // Issue 1997: one PrepareBatch + Send shows two INSERT rows in system.query_log.
    package main
    
    import (
    	"context"
    	"fmt"
    	"os"
    	"time"
    
    	"github.com/ClickHouse/clickhouse-go/v2"
    )
    
    func main() {
    	addr := os.Getenv("CLICKHOUSE_ADDR")
    	if addr == "" {
    		addr = "localhost:9000"
    	}
    	conn, err := clickhouse.Open(&clickhouse.Options{
    		Addr:        []string{addr},
    		Compression: &clickhouse.Compression{Method: clickhouse.CompressionLZ4},
    	})
    	if err != nil {
    		fmt.Println("open:", err)
    		return
    	}
    	defer conn.Close()
    	ctx := context.Background()
    
    	v, err := conn.ServerVersion()
    	if err != nil {
    		fmt.Println("version:", err)
    		return
    	}
    	var asyncDefault string
    	if err := conn.QueryRow(ctx, "SELECT getSetting('async_insert')::String").Scan(&asyncDefault); err != nil {
    		fmt.Println("getSetting:", err)
    		return
    	}
    	fmt.Printf("server %s, async_insert=%s\n", v.Version, asyncDefault)
    
    	for _, q := range []string{
    		"DROP TABLE IF EXISTS dup_test_events",
    		"CREATE TABLE dup_test_events (id UInt64, value String) ENGINE = MergeTree ORDER BY id",
    	} {
    		if err := conn.Exec(ctx, q); err != nil {
    			fmt.Println("exec:", err)
    			return
    		}
    	}
    
    	run := time.Now().UnixNano()
    	cases := []struct {
    		name     string
    		settings clickhouse.Settings
    	}{
    		{"server default", nil},
    		{"async_insert=0", clickhouse.Settings{"async_insert": 0}},
    	}
    	for _, c := range cases {
    		queryID := fmt.Sprintf("issue1997-%d-%s", run, c.name)
    		bctx := clickhouse.Context(ctx, clickhouse.WithQueryID(queryID), clickhouse.WithSettings(c.settings))
    		batch, err := conn.PrepareBatch(bctx, "INSERT INTO dup_test_events (id, value)")
    		if err != nil {
    			fmt.Printf("%s: prepare: %v\n", c.name, err)
    			return
    		}
    		for i := 0; i < 10; i++ {
    			if err := batch.Append(uint64(i), fmt.Sprintf("row-%d", i)); err != nil {
    				fmt.Printf("%s: append: %v\n", c.name, err)
    				return
    			}
    		}
    		if err := batch.Send(); err != nil {
    			fmt.Printf("%s: send: %v\n", c.name, err)
    			return
    		}
    	}
    
    	if err := conn.Exec(ctx, "SYSTEM FLUSH LOGS"); err != nil {
    		fmt.Println("flush logs:", err)
    		return
    	}
    	for _, c := range cases {
    		queryID := fmt.Sprintf("issue1997-%d-%s", run, c.name)
    		rows, err := conn.Query(ctx, `
    			SELECT if(query_id = $1, 'client query_id', 'new query_id') AS id, toString(query_kind), is_initial_query, written_rows, query
    			FROM system.query_log
    			WHERE type = 'QueryFinish' AND event_date >= yesterday()
    			  AND (query_id = $1 OR query_id IN (
    			        SELECT flush_query_id FROM system.asynchronous_insert_log WHERE query_id = $1))
    			ORDER BY event_time_microseconds`, queryID)
    		if err != nil {
    			fmt.Printf("%s: query_log: %v\n", c.name, err)
    			return
    		}
    		fmt.Printf("batch with %s:\n", c.name)
    		for rows.Next() {
    			var id, kind, query string
    			var initial uint8
    			var written uint64
    			if err := rows.Scan(&id, &kind, &initial, &written, &query); err != nil {
    				fmt.Println("scan:", err)
    				return
    			}
    			fmt.Printf("  query_log row: %s, query_kind=%s, is_initial_query=%d, written_rows=%d, query=%q\n", id, kind, initial, written, query)
    		}
    		rows.Close()
    		var asyncRows uint64
    		if err := conn.QueryRow(ctx, "SELECT count() FROM system.asynchronous_insert_log WHERE query_id = $1", queryID).Scan(&asyncRows); err != nil {
    			fmt.Println("asynchronous_insert_log:", err)
    			return
    		}
    		fmt.Printf("  asynchronous_insert_log rows for the client query_id: %d\n", asyncRows)
    	}
    
    	var stored uint64
    	if err := conn.QueryRow(ctx, "SELECT count() FROM dup_test_events").Scan(&stored); err != nil {
    		fmt.Println("count:", err)
    		return
    	}
    	fmt.Printf("rows in table: %d (2 batches of 10)\n", stored)
    	_ = conn.Exec(ctx, "DROP TABLE dup_test_events")
    }

    Output on main (7188b645), ClickHouse 26.9.1:

    server 26.9.1, async_insert=true
    batch with server default:
      query_log row: new query_id, query_kind=AsyncInsertFlush, is_initial_query=1, written_rows=10, query="INSERT INTO default.dup_test_events (id, value) FORMAT Native"
      query_log row: client query_id, query_kind=Insert, is_initial_query=1, written_rows=10, query="INSERT INTO dup_test_events (id, value) FORMAT Native"
      asynchronous_insert_log rows for the client query_id: 1
    batch with async_insert=0:
      query_log row: client query_id, query_kind=Insert, is_initial_query=1, written_rows=10, query="INSERT INTO dup_test_events (id, value) FORMAT Native"
      asynchronous_insert_log rows for the client query_id: 0
    rows in table: 20 (2 batches of 10)
    

    The same INSERT over HTTP with curl, without the client:

    Q(){ curl -s "http://clickhouse:8123/?$2" --data-binary "$1"; }
    Q "CREATE TABLE dup_test_events (id UInt64, value String) ENGINE = MergeTree ORDER BY id"
    Q "INSERT INTO dup_test_events (id, value) VALUES (1, 'row-1')" "query_id=curl-1997"
    Q "SYSTEM FLUSH LOGS"
    Q "SELECT if(query_id = 'curl-1997', 'client query_id', 'new query_id'), query_kind, written_rows, query FROM system.query_log WHERE type = 'QueryFinish' AND (query_id = 'curl-1997' OR query_id IN (SELECT flush_query_id FROM system.asynchronous_insert_log WHERE query_id = 'curl-1997')) ORDER BY event_time_microseconds FORMAT TSV"
    Q "DROP TABLE dup_test_events"
    new query_id	AsyncInsertFlush	1	INSERT INTO default.dup_test_events (id, value) FORMAT Values
    client query_id	Insert	1	INSERT INTO dup_test_events (id, value) VALUES 
    

    Automated triage by Polyglot AI. Classification added on 2026-11-19. A maintainer makes the final decision.

  4. added
    queries
    and removed on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    incorrect usagequeries

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions