[client-v2] RowBinaryFormatSerializer.writeUInt256 writes 16 bytes; writeInt128/writeInt256 wrap values above the signed maximum
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Facilidade para iniciantes
- 72/100
Direção de pesquisa
Os bugs estão em RowBinaryFormatSerializer.java: writeUInt256 (por volta da linha 90) chama writeUnsignedInt128 quando deveria chamar writeUnsignedInt256, e writeInt128 e writeInt256 (por volta das linhas 78 e 86) não têm verificação de intervalo com sinal. BinaryStreamUtils.writeBigInteger em clickhouse-data (por volta da linha 1064) também está envolvido, pois descarta um byte inicial em valores como 2^127. Está concluído quando UInt256 grava 32 bytes, aceita valores até 2^256-1, e Int128/Int256 lançam IllegalArgumentException fora do intervalo com sinal. Verifique isso com o programa de reprodução da issue.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Description
RowBinaryFormatSerializer (client-v2, the typed writer that an application uses in Client.insert(table, out -> ..., ClickHouseFormat.RowBinary, ...)) writes some big integers incorrectly:
writeUInt256(BigInteger)writes 16 bytes, but aUInt256value has 32 bytes. The server then reads the next columns from the wrong offset. The insert fails withCANNOT_READ_ALL_DATA, or it stores rows with wrong values and no error (5 rows written, 3 different rows stored). It also rejects a validUInt256value above theUInt128maximum.writeInt128(BigInteger)andwriteInt256(BigInteger)accept a value above the signed maximum (up to the unsigned maximum) and store it as a negative number with no error: 2^127 is stored as theInt128minimum. A value below the signed minimum is rejected.
RowBinaryFormatWriter, POJO insert and the jdbc-v2 RowBinary writer write UInt256 correctly (32 bytes).
Steps to reproduce
- Run the program below. It creates the tables (
ENGINE = Memory) and inserts withRowBinaryFormatSerializer. - Read the tables:
SELECT * FROM t_u256andSELECT * FROM t_i128.
Error Log or Exception StackTrace
Program output:
t_u256: inserted
t_u256_big: java.lang.IllegalArgumentException: BigInteger(340282366920938463463374607431768211456) should be between 0 and 340282366920938463463374607431768211455 inclusive of both values
t_i128: inserted
t_u128: java.lang.IllegalArgumentException: BigInteger(340282366920938463463374607431768211456) should be between 0 and 340282366920938463463374607431768211455 inclusive of both values
Server, SELECT * FROM t_u256 (written: five rows (i, 5, 7)) and SELECT * FROM t_i128 (written: (1, 2^127, 7)):
┌─id─┬─────────────────────────────────────────────────────────────────────v─┬─tail─┐
1. │ 1 │ 31385508679856407096222729520892270990187965513654415130629 │ 0 │
2. │ 0 │ 107839786712542271326374825694929048657002242602971011756044115247111 │ 5 │
3. │ 0 │ 1701411835000833130017321933642527670272 │ 7 │
└────┴───────────────────────────────────────────────────────────────────────┴──────┘
┌─id─┬────────────────────────────────────────v─┬─tail─┐
1. │ 1 │ -170141183460469231731687303715884105728 │ 7 │
└────┴──────────────────────────────────────────┴──────┘
With one row in t_u256, the insert fails instead: Code: 33. DB::Exception: Cannot read all data. Bytes read: 20. Bytes expected: 32: (at row 1) : While executing WaitForAsyncInsert. (CANNOT_READ_ALL_DATA).
Expected Behaviour
writeUInt256writes 32 bytes (server:SELECT byteSize(toUInt256(5))returns32) and accepts values up to 2^256 - 1.t_u256then has the five rows(i, 5, 7).writeInt128/writeInt256reject a value outside the signed range withIllegalArgumentException, aswriteUInt128does in the contrast caset_u128.
Root cause
RowBinaryFormatSerializer.java:90:writeUInt256callsBinaryStreamUtils.writeUnsignedInt128instead ofwriteUnsignedInt256.RowBinaryFormatSerializer.java:78and:86callBinaryStreamUtils.writeInt128/writeInt256with no range check, andBinaryStreamUtils.writeBigInteger(clickhouse-data,BinaryStreamUtils.java:1064) drops the leading zero byte of a positive value that is one byte too long, so 2^127 becomes0x80 00 .. 00.
The fix is in RowBinaryFormatSerializer only. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.
Related:
- #3411 (open): adds the signed
Int128/Int256range check inSerializerUtils; it does not changeRowBinaryFormatSerializer. - #3176 (open): the same kind of silent wrap on the
RowBinaryFormatWriterpath.
Code Example
Reproduction program (Java, 49 lines)
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.data_formats.RowBinaryFormatSerializer;
import com.clickhouse.client.api.insert.InsertSettings;
import com.clickhouse.data.ClickHouseFormat;
import java.math.BigInteger;
public class Min {
interface Rows { void write(RowBinaryFormatSerializer s) throws Exception; }
static void insert(Client client, String table, Rows rows) {
try {
client.insert(table, out -> {
try { rows.write(new RowBinaryFormatSerializer(out)); }
catch (Exception e) { throw new RuntimeException(e); }
}, ClickHouseFormat.RowBinary, new InsertSettings()).get().close();
System.out.println(table + ": inserted");
} catch (Exception e) {
Throwable t = e;
while (t.getCause() != null) t = t.getCause();
System.out.println(table + ": " + t);
}
}
public static void main(String[] args) throws Exception {
Client client = new Client.Builder().addEndpoint("http://localhost:8123")
.setUsername("default").setPassword("").build();
for (String t : new String[] {"t_u256 (id Int32, v UInt256, tail Int32)",
"t_u256_big (id Int32, v UInt256, tail Int32)",
"t_i128 (id Int32, v Int128, tail Int32)",
"t_u128 (id Int32, v UInt128, tail Int32)"}) {
client.execute("DROP TABLE IF EXISTS " + t.substring(0, t.indexOf(' '))).get().close();
client.execute("CREATE TABLE " + t + " ENGINE = Memory").get().close();
}
BigInteger p127 = BigInteger.ONE.shiftLeft(127);
BigInteger p128 = BigInteger.ONE.shiftLeft(128);
// 1. UInt256: five rows (id = i, v = 5, tail = 7)
insert(client, "t_u256", s -> {
for (int i = 1; i <= 5; i++) { s.writeInt32(i); s.writeUInt256(BigInteger.valueOf(5)); s.writeInt32(7); }
});
// 2. UInt256: v = 2^128, a valid UInt256 value
insert(client, "t_u256_big", s -> { s.writeInt32(1); s.writeUInt256(p128); s.writeInt32(7); });
// 3. Int128: v = 2^127 (Int128 maximum + 1)
insert(client, "t_i128", s -> { s.writeInt32(1); s.writeInt128(p127); s.writeInt32(7); });
// Contrast: UInt128: v = 2^128 (UInt128 maximum + 1)
insert(client, "t_u128", s -> { s.writeInt32(1); s.writeUInt128(p128); s.writeInt32(7); });
client.close();
}
}
Configuration
Client Configuration
Default settings (see the program).
Environment
- Cloud
- Client version: client-v2
0.12.0-rc1-SNAPSHOT,mainat 051a7ecfd - Language version: Java 17.0.21
- OS: Linux
ClickHouse Server
- ClickHouse Server version: 26.10.4.207
- ClickHouse Server non-default settings, if any: none
CREATE TABLEstatements for tables involved: in the program- Sample data for all these tables: in the program
Classification: impact: Data integrity · area: Data types & formats (UInt256, Int128, Int256)
Found by automated analysis (Polyglot AI) while working on #2619. Verified against a live server.
- Linguagem predominante
- Java
- Estrelas
- 1.6k
- Forks
- 657
- Merge médio
- 2d 6h
- PRs com merge (30d)
- 36
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de ClickHouse/clickhouse-java
-
api-diagnostics bug jdbc
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
ClickHouse/clickhouse-java#3464 ·
Mantenedores costumam responder em até 1 dia
-
tests
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
ClickHouse/clickhouse-java#3452 ·
Mantenedores costumam responder em até 1 dia
-
bug jdbc performance queries sql-parser
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 77/100
ClickHouse/clickhouse-java#3451 ·
Mantenedores costumam responder em até 1 dia
-
bug jdbc legacy queries
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
ClickHouse/clickhouse-java#3444 ·
Mantenedores costumam responder em até 1 dia
-
api-diagnostics bug client jdbc
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
ClickHouse/clickhouse-java#3439 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
Todas as issues de ClickHouse/clickhouse-java
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 60/100
quelea-projection/Quelea#749 ·
Mantenedores costumam responder em até 1 dia
-
free_port can hand one port to two callers, so the fixed-port http tests fail in parallel runsAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 92/100
erkamyaman/rust-anything#963 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 Meio dia Facilidade para iniciantes 76/100
-
Deferred
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Sanne/incus-spawn#2768 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 82/100
morluto/rea#15041 · 1 comentário ·
Mantenedores costumam responder em até 1 dia