From 30dcd46044a99b0743b676a891f106802c08f765 Mon Sep 17 00:00:00 2001 From: ColinLeeo Date: Tue, 24 Nov 2026 15:08:33 +0800 Subject: [PATCH 1/4] Reuse device prefix hashes for batch Bloom filter lookups Probe measurements of one device together and return matches in input order. Reuse complete Murmur hash blocks from the device prefix while preserving compatibility with existing filters. This SDK lookup operates on an in-memory filter and requires no CLI option. --- .../org/apache/tsfile/utils/BloomFilter.java | 55 +++++++- .../apache/tsfile/utils/Murmur128Hash.java | 121 ++++++++++++------ .../apache/tsfile/utils/BloomFilterTest.java | 110 ++++++++++++++++ skills/tsfile/references/java.md | 9 ++ 4 files changed, 249 insertions(+), 46 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java index 7f882b4ad2..13f2f38725 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java @@ -19,12 +19,17 @@ package org.apache.tsfile.utils; import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.common.constant.TsFileConstant; +import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.read.common.Path; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.BitSet; +import java.util.Collection; import java.util.Objects; import static org.apache.tsfile.utils.RamUsageEstimator.sizeOfLongArray; @@ -131,6 +136,47 @@ public boolean contains(String value) { return ret; } + /** + * Tests measurements of one device against this filter. Bit i in the result corresponds to the + * ith measurement in iteration order. A null measurement has a clear bit. An empty measurement + * tests the device's time-column path (including the trailing separator). + */ + public BitSet mightContainBatch(IDeviceID device, Collection measurements) { + BitSet matches = new BitSet(measurements.size()); + if (measurements.isEmpty()) { + return matches; + } + String prefix = device.toString() + TsFileConstant.PATH_SEPARATOR; + // The file's existing hashes use the default charset. Stateful encodings and byte-order marks + // can make encoding the prefix and suffix separately differ from encoding the full path. + Murmur128Hash.PrefixHasher hasher = + StandardCharsets.UTF_8.equals(Charset.defaultCharset()) + ? new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), SEEDS, hashFunctionSize) + : null; + int index = 0; + for (String measurement : measurements) { + if (measurement != null + && (hasher == null + ? contains(prefix + measurement) + : mightContain(hasher, measurement))) { + matches.set(index); + } + index++; + } + return matches; + } + + private boolean mightContain(Murmur128Hash.PrefixHasher hasher, String measurement) { + hasher.setSuffix(measurement.getBytes(StandardCharsets.UTF_8)); + for (int i = 0; i < hashFunctionSize; i++) { + if (!bits.get(bitIndex(hasher.hash(i), size))) { + return false; + } + } + return true; + } + public byte[] serialize() { return bits.toByteArray(); } @@ -161,12 +207,11 @@ public int hashCode() { } private static int hash(String value, int cap, int seed) { - int res = Murmur128Hash.hash(value, seed); - if (res == Integer.MIN_VALUE) { - res = 0; - } + return bitIndex(Murmur128Hash.hash(value, seed), cap); + } - return Math.abs(res) % cap; + private static int bitIndex(int hash, int cap) { + return (hash == Integer.MIN_VALUE ? 0 : Math.abs(hash)) % cap; } public int serialize(OutputStream outputStream) throws IOException { diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java index 284d5e8be2..bd155fd521 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java @@ -18,8 +18,14 @@ */ package org.apache.tsfile.utils; +import java.util.Arrays; + public class Murmur128Hash { + private static final int BLOCK_BYTES = 16; + private static final long C1 = 0x87c37b91114253d5L; + private static final long C2 = 0x4cf5ad432745937fL; + private Murmur128Hash() { // util class } @@ -32,7 +38,8 @@ private Murmur128Hash() { * @return hashcode of value */ public static int hash(String value, int seed) { - return (int) innerHash(value.getBytes(), 0, value.getBytes().length, seed); + byte[] bytes = value.getBytes(); + return (int) innerHash(bytes, bytes.length, bytes.length, seed, seed); } /** @@ -44,18 +51,18 @@ public static int hash(String value, int seed) { * @return hashcode of value */ public static int hash(String value1, long value2, int seed) { + int length = value1.length() + Long.BYTES; return (int) innerHash( BytesUtils.concatByteArray(value1.getBytes(), BytesUtils.longToBytes(value2)), - 0, - value1.length() + 8, + length, + length, + seed, seed); } /** Methods to perform murmur 128 hash. */ - private static long getBlock(byte[] key, int offset, int index) { - int i8 = index << 3; - int blockOffset = offset + i8; + private static long getBlock(byte[] key, int blockOffset) { return ((long) key[blockOffset] & 0xff) + (((long) key[blockOffset + 1] & 0xff) << 8) + (((long) key[blockOffset + 2] & 0xff) << 16) @@ -79,36 +86,68 @@ private static long fmix(long k) { return k; } - private static long innerHash(byte[] key, int offset, int length, long seed) { - final int nblocks = length >> 4; // Process as 128-bit blocks. - long h1 = seed; - long h2 = seed; - long c1 = 0x87c37b91114253d5L; - long c2 = 0x4cf5ad432745937fL; - // ---------- - // body - for (int i = 0; i < nblocks; i++) { - long k1 = getBlock(key, offset, i * 2); - long k2 = getBlock(key, offset, i * 2 + 1); - k1 *= c1; - k1 = rotl64(k1, 31); - k1 *= c2; - h1 ^= k1; - h1 = rotl64(h1, 27); - h1 += h2; - h1 = h1 * 5 + 0x52dce729; - k2 *= c2; - k2 = rotl64(k2, 33); - k2 *= c1; - h2 ^= k2; - h2 = rotl64(h2, 31); - h2 += h1; - h2 = h2 * 5 + 0x38495ab5; + // A complete 16-byte block updates h1 first. The new h1 feeds the update of h2. + private static long mixH1(long h1, long h2, long k1) { + h1 ^= rotl64(k1 * C1, 31) * C2; + return (rotl64(h1, 27) + h2) * 5 + 0x52dce729; + } + + private static long mixH2(long h1, long h2, long k2) { + h2 ^= rotl64(k2 * C2, 33) * C1; + return (rotl64(h2, 31) + h1) * 5 + 0x38495ab5; + } + + /** Hashes multiple suffixes sharing the same prefix, with one state per Bloom filter seed. */ + static final class PrefixHasher { + private final long[] h1; + private final long[] h2; + private final int prefixBlockBytes; + private final int prefixTailBytes; + private byte[] buffer; + private int length; + + PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { + h1 = new long[seedCount]; + h2 = new long[seedCount]; + for (int i = 0; i < seedCount; i++) { + h1[i] = seeds[i]; + h2[i] = seeds[i]; + } + prefixTailBytes = prefix.length % BLOCK_BYTES; + prefixBlockBytes = prefix.length - prefixTailBytes; + for (int offset = 0; offset < prefixBlockBytes; offset += BLOCK_BYTES) { + long k1 = getBlock(prefix, offset); + long k2 = getBlock(prefix, offset + Long.BYTES); + for (int i = 0; i < seedCount; i++) { + h1[i] = mixH1(h1[i], h2[i], k1); + h2[i] = mixH2(h1[i], h2[i], k2); + } + } + // A partial prefix block must be completed with bytes from the current measurement. + buffer = Arrays.copyOfRange(prefix, prefixBlockBytes, prefix.length); + } + + void setSuffix(byte[] suffix) { + length = prefixTailBytes + suffix.length; + if (buffer.length < length) { + buffer = Arrays.copyOf(buffer, length); + } + System.arraycopy(suffix, 0, buffer, prefixTailBytes, suffix.length); + } + + int hash(int seedIndex) { + return (int) + innerHash(buffer, length, prefixBlockBytes + length, h1[seedIndex], h2[seedIndex]); + } + } + + private static long innerHash(byte[] key, int length, int totalLength, long h1, long h2) { + int blockBytes = length - length % BLOCK_BYTES; + int offset = 0; + for (; offset < blockBytes; offset += BLOCK_BYTES) { + h1 = mixH1(h1, h2, getBlock(key, offset)); + h2 = mixH2(h1, h2, getBlock(key, offset + Long.BYTES)); } - // ---------- - // tail - // Advance offset to the unprocessed tail of the data. - offset += nblocks * 16; long k1 = 0; long k2 = 0; switch (length & 15) { @@ -132,9 +171,9 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { // fallthrough case 9: k2 ^= key[offset + 8]; - k2 *= c2; + k2 *= C2; k2 = rotl64(k2, 33); - k2 *= c1; + k2 *= C1; h2 ^= k2; // fallthrough case 8: @@ -160,9 +199,9 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { // fallthrough case 1: k1 ^= (key[offset]); - k1 *= c1; + k1 *= C1; k1 = rotl64(k1, 31); - k1 *= c2; + k1 *= C2; h1 ^= k1; break; default: // 0 @@ -171,8 +210,8 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { } // ---------- // finalization - h1 ^= length; - h2 ^= length; + h1 ^= totalLength; + h2 ^= totalLength; h1 += h2; h2 += h1; h1 = fmix(h1); diff --git a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java index ec46d67de2..5abbe03539 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java @@ -18,9 +18,23 @@ */ package org.apache.tsfile.utils; +import org.apache.tsfile.file.metadata.IDeviceID; +import org.apache.tsfile.read.common.FullPath; + import org.junit.Test; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; public class BloomFilterTest { @@ -63,4 +77,100 @@ public void testSerialize() { assertTrue(filter1.contains(value2)); assertTrue(filter1.contains(value3)); } + + @Test + public void testBatchMatchesIndividualPaths() { + List measurements = + Arrays.asList("传感器.温度", null, "absent", "", "s".repeat(80), "x", "传感器.温度"); + IDeviceID.Factory devices = IDeviceID.Factory.DEFAULT_FACTORY; + for (IDeviceID device : + Arrays.asList( + devices.create("d"), + devices.create("root.区域." + "a".repeat(70)), + devices.create(new String[] {"table", null, "region.1", "传感器"}))) { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.05, 100); + filter.add(new FullPath(device, "")); + filter.add(new FullPath(device, "传感器.温度")); + filter.add(new FullPath(device, "x")); + assertBatchMatchesSingles(filter, device, measurements); + assertBatchMatchesSingles( + filter, device, Collections.unmodifiableSet(new LinkedHashSet<>(measurements))); + assertBatchMatchesSingles( + filter, IDeviceID.Factory.DEFAULT_FACTORY.create("other"), measurements); + assertTrue(filter.mightContainBatch(device, Collections.emptySet()).isEmpty()); + assertTrue( + BloomFilter.getEmptyBloomFilter(0.05, 1) + .mightContainBatch(device, Collections.singleton("")) + .isEmpty()); + } + } + + private static void assertBatchMatchesSingles( + BloomFilter filter, IDeviceID device, Collection measurements) { + BitSet expected = new BitSet(); + int index = 0; + for (String measurement : measurements) { + expected.set( + index++, measurement != null && filter.contains(new FullPath(device, measurement))); + } + assertEquals(expected, filter.mightContainBatch(device, measurements)); + } + + @Test + public void testPrefixHashAtBlockBoundaries() { + // The optimized reader is used when the scalar API encodes paths as UTF-8. + assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); + int[] seeds = {5, 7, 11, 19, 31, 37, 43, 59}; + for (int i = 0; i < 48; i++) { + String prefix = "区域." + "p".repeat(i) + "."; + Murmur128Hash.PrefixHasher hasher = + new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), seeds, seeds.length); + for (int j = 31; j >= 0; j--) { + String measurement = "é".repeat(j) + "温度"; + hasher.setSuffix(measurement.getBytes(StandardCharsets.UTF_8)); + for (int k = 0; k < seeds.length; k++) { + assertEquals(Murmur128Hash.hash(prefix + measurement, seeds[k]), hasher.hash(k)); + } + } + } + } + + @Test + public void testBatchAgainstExistingFilter() { + // Generated by the snapshot writer for root.d., root.d.s1 and root.d.temp. + assumeTrue(Arrays.equals("root.d.".getBytes(), "root.d.".getBytes(StandardCharsets.US_ASCII))); + BloomFilter filter = + snapshotFilter(256, 4, 8, 51, 90, 96, 128, 157, 192, 193, 209, 229, 234, 237, 242, 245); + BitSet expected = new BitSet(); + expected.set(0, 3); + assertEquals( + expected, + filter.mightContainBatch( + IDeviceID.Factory.DEFAULT_FACTORY.create("root.d"), + Arrays.asList("", "s1", "temp", "absent"))); + } + + @Test + public void testBatchAgainstExistingMultiBlockFilter() { + // Snapshot bits for the time column, 温度 and load under the same multi-block UTF-8 prefix. + assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); + BloomFilter filter = + snapshotFilter( + 1024, 9, 26, 228, 298, 337, 362, 384, 425, 440, 457, 470, 705, 836, 837, 938); + IDeviceID device = + IDeviceID.Factory.DEFAULT_FACTORY.create("root.factory.production_line_009.区域.station_43"); + BitSet expected = new BitSet(); + expected.set(0, 3); + assertEquals( + expected, filter.mightContainBatch(device, Arrays.asList("温度", "load", "", "absent"))); + } + + private static BloomFilter snapshotFilter(int size, int... setBits) { + BitSet bits = new BitSet(size); + for (int bit : setBits) { + bits.set(bit); + } + return BloomFilter.buildBloomFilter(bits.toByteArray(), size, 5); + } } diff --git a/skills/tsfile/references/java.md b/skills/tsfile/references/java.md index dfd10930ce..266f8b5eac 100644 --- a/skills/tsfile/references/java.md +++ b/skills/tsfile/references/java.md @@ -60,6 +60,15 @@ try (ITsFileTreeReader reader = } ``` +## Checking multiple measurements of one device + +Pass an `IDeviceID` and the pending measurement names to +`filter.mightContainBatch(device, measurements)`. Bit positions in the returned +`BitSet` follow the collection's iteration order. A clear bit rules out the +corresponding measurement. A set bit requires checking the file's metadata. +Use an ordered collection when matching positions back to measurement names. +An empty measurement name probes the time column. + ## Guidance - Prefer `Tablet` for batch writes and `TSRecord` for genuinely record-oriented From bf0780d30cdfbaa13776c82c97e77a5659d175f9 Mon Sep 17 00:00:00 2001 From: ColinLeeo Date: Tue, 24 Nov 2026 17:32:06 +0800 Subject: [PATCH 2/4] Keep scalar hashing unchanged for batch Bloom filter lookups --- .../org/apache/tsfile/utils/BloomFilter.java | 8 +- .../apache/tsfile/utils/Murmur128Hash.java | 149 ++++++++++-------- 2 files changed, 86 insertions(+), 71 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java index 13f2f38725..08fc0326d5 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java @@ -210,8 +210,12 @@ private static int hash(String value, int cap, int seed) { return bitIndex(Murmur128Hash.hash(value, seed), cap); } - private static int bitIndex(int hash, int cap) { - return (hash == Integer.MIN_VALUE ? 0 : Math.abs(hash)) % cap; + private static int bitIndex(int res, int cap) { + if (res == Integer.MIN_VALUE) { + res = 0; + } + + return Math.abs(res) % cap; } public int serialize(OutputStream outputStream) throws IOException { diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java index bd155fd521..e6e97fdd57 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java @@ -22,7 +22,6 @@ public class Murmur128Hash { - private static final int BLOCK_BYTES = 16; private static final long C1 = 0x87c37b91114253d5L; private static final long C2 = 0x4cf5ad432745937fL; @@ -38,8 +37,7 @@ private Murmur128Hash() { * @return hashcode of value */ public static int hash(String value, int seed) { - byte[] bytes = value.getBytes(); - return (int) innerHash(bytes, bytes.length, bytes.length, seed, seed); + return (int) innerHash(value.getBytes(), 0, value.getBytes().length, seed); } /** @@ -51,18 +49,18 @@ public static int hash(String value, int seed) { * @return hashcode of value */ public static int hash(String value1, long value2, int seed) { - int length = value1.length() + Long.BYTES; return (int) innerHash( BytesUtils.concatByteArray(value1.getBytes(), BytesUtils.longToBytes(value2)), - length, - length, - seed, + 0, + value1.length() + 8, seed); } /** Methods to perform murmur 128 hash. */ - private static long getBlock(byte[] key, int blockOffset) { + private static long getBlock(byte[] key, int offset, int index) { + int i8 = index << 3; + int blockOffset = offset + i8; return ((long) key[blockOffset] & 0xff) + (((long) key[blockOffset + 1] & 0xff) << 8) + (((long) key[blockOffset + 2] & 0xff) << 16) @@ -86,68 +84,25 @@ private static long fmix(long k) { return k; } - // A complete 16-byte block updates h1 first. The new h1 feeds the update of h2. - private static long mixH1(long h1, long h2, long k1) { - h1 ^= rotl64(k1 * C1, 31) * C2; - return (rotl64(h1, 27) + h2) * 5 + 0x52dce729; - } - - private static long mixH2(long h1, long h2, long k2) { - h2 ^= rotl64(k2 * C2, 33) * C1; - return (rotl64(h2, 31) + h1) * 5 + 0x38495ab5; - } - - /** Hashes multiple suffixes sharing the same prefix, with one state per Bloom filter seed. */ - static final class PrefixHasher { - private final long[] h1; - private final long[] h2; - private final int prefixBlockBytes; - private final int prefixTailBytes; - private byte[] buffer; - private int length; - - PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { - h1 = new long[seedCount]; - h2 = new long[seedCount]; - for (int i = 0; i < seedCount; i++) { - h1[i] = seeds[i]; - h2[i] = seeds[i]; - } - prefixTailBytes = prefix.length % BLOCK_BYTES; - prefixBlockBytes = prefix.length - prefixTailBytes; - for (int offset = 0; offset < prefixBlockBytes; offset += BLOCK_BYTES) { - long k1 = getBlock(prefix, offset); - long k2 = getBlock(prefix, offset + Long.BYTES); - for (int i = 0; i < seedCount; i++) { - h1[i] = mixH1(h1[i], h2[i], k1); - h2[i] = mixH2(h1[i], h2[i], k2); - } - } - // A partial prefix block must be completed with bytes from the current measurement. - buffer = Arrays.copyOfRange(prefix, prefixBlockBytes, prefix.length); - } - - void setSuffix(byte[] suffix) { - length = prefixTailBytes + suffix.length; - if (buffer.length < length) { - buffer = Arrays.copyOf(buffer, length); - } - System.arraycopy(suffix, 0, buffer, prefixTailBytes, suffix.length); - } - - int hash(int seedIndex) { - return (int) - innerHash(buffer, length, prefixBlockBytes + length, h1[seedIndex], h2[seedIndex]); - } + private static long innerHash(byte[] key, int offset, int length, long seed) { + return innerHash(key, offset, length, seed, seed); } - private static long innerHash(byte[] key, int length, int totalLength, long h1, long h2) { - int blockBytes = length - length % BLOCK_BYTES; - int offset = 0; - for (; offset < blockBytes; offset += BLOCK_BYTES) { - h1 = mixH1(h1, h2, getBlock(key, offset)); - h2 = mixH2(h1, h2, getBlock(key, offset + Long.BYTES)); + // offset is the number of complete prefix bytes already mixed into h1 and h2. + private static long innerHash(byte[] key, int offset, int length, long h1, long h2) { + final int nblocks = (length - offset) >> 4; // Process as 128-bit blocks. + // ---------- + // body + for (int i = 0; i < nblocks; i++) { + long k1 = getBlock(key, offset, i * 2); + long k2 = getBlock(key, offset, i * 2 + 1); + h1 = mixH1(h1, h2, k1); + h2 = mixH2(h1, h2, k2); } + // ---------- + // tail + // Advance offset to the unprocessed tail of the data. + offset += nblocks * 16; long k1 = 0; long k2 = 0; switch (length & 15) { @@ -210,8 +165,8 @@ private static long innerHash(byte[] key, int length, int totalLength, long h1, } // ---------- // finalization - h1 ^= totalLength; - h2 ^= totalLength; + h1 ^= length; + h2 ^= length; h1 += h2; h2 += h1; h1 = fmix(h1); @@ -220,4 +175,60 @@ private static long innerHash(byte[] key, int length, int totalLength, long h1, h2 += h1; return h1 + h2; } + + private static long mixH1(long h1, long h2, long k1) { + k1 *= C1; + k1 = rotl64(k1, 31); + k1 *= C2; + h1 ^= k1; + h1 = rotl64(h1, 27); + h1 += h2; + return h1 * 5 + 0x52dce729; + } + + private static long mixH2(long h1, long h2, long k2) { + k2 *= C2; + k2 = rotl64(k2, 33); + k2 *= C1; + h2 ^= k2; + h2 = rotl64(h2, 31); + h2 += h1; + return h2 * 5 + 0x38495ab5; + } + + /** Reuses complete prefix blocks for all measurements in one Bloom filter lookup. */ + static final class PrefixHasher { + private final long[] h1; + private final long[] h2; + private final int prefixLength; + private byte[] buffer; + private int length; + + PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { + buffer = prefix; + prefixLength = prefix.length; + h1 = new long[seedCount]; + h2 = new long[seedCount]; + for (int i = 0; i < seedCount; i++) { + h1[i] = seeds[i]; + h2[i] = seeds[i]; + for (int block = 0; block < prefixLength / 16; block++) { + h1[i] = mixH1(h1[i], h2[i], getBlock(prefix, 0, block * 2)); + h2[i] = mixH2(h1[i], h2[i], getBlock(prefix, 0, block * 2 + 1)); + } + } + } + + void setSuffix(byte[] suffix) { + length = prefixLength + suffix.length; + if (buffer.length < length) { + buffer = Arrays.copyOf(buffer, length); + } + System.arraycopy(suffix, 0, buffer, prefixLength, suffix.length); + } + + int hash(int seedIndex) { + return (int) innerHash(buffer, prefixLength / 16 * 16, length, h1[seedIndex], h2[seedIndex]); + } + } } From 9099af0059ab00e965115fbabadd9ef602219521 Mon Sep 17 00:00:00 2001 From: ColinLeeo Date: Tue, 24 Nov 2026 18:34:05 +0800 Subject: [PATCH 3/4] Handle empty-device Bloom filter paths and defer prefix hashing --- .../org/apache/tsfile/utils/BloomFilter.java | 17 ++++--- .../apache/tsfile/utils/Murmur128Hash.java | 45 +++++++++++-------- .../apache/tsfile/utils/BloomFilterTest.java | 38 ++++++++++++++++ skills/tsfile/references/java.md | 3 +- 4 files changed, 77 insertions(+), 26 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java index 08fc0326d5..5cde1f7f4e 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java @@ -139,14 +139,16 @@ public boolean contains(String value) { /** * Tests measurements of one device against this filter. Bit i in the result corresponds to the * ith measurement in iteration order. A null measurement has a clear bit. An empty measurement - * tests the device's time-column path (including the trailing separator). + * tests the device's time-column path. For an empty device, both path forms (with and without the + * leading separator) are checked. */ public BitSet mightContainBatch(IDeviceID device, Collection measurements) { BitSet matches = new BitSet(measurements.size()); if (measurements.isEmpty()) { return matches; } - String prefix = device.toString() + TsFileConstant.PATH_SEPARATOR; + String deviceName = device.toString(); + String prefix = deviceName + TsFileConstant.PATH_SEPARATOR; // The file's existing hashes use the default charset. Stateful encodings and byte-order marks // can make encoding the prefix and suffix separately differ from encoding the full path. Murmur128Hash.PrefixHasher hasher = @@ -156,11 +158,12 @@ public BitSet mightContainBatch(IDeviceID device, Collection measurement : null; int index = 0; for (String measurement : measurements) { - if (measurement != null - && (hasher == null - ? contains(prefix + measurement) - : mightContain(hasher, measurement))) { - matches.set(index); + if (measurement != null) { + boolean matchesFullPath = + hasher == null ? contains(prefix + measurement) : mightContain(hasher, measurement); + if (matchesFullPath || (deviceName.isEmpty() && contains(measurement))) { + matches.set(index); + } } index++; } diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java index e6e97fdd57..d7a5afa527 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java @@ -198,37 +198,46 @@ private static long mixH2(long h1, long h2, long k2) { /** Reuses complete prefix blocks for all measurements in one Bloom filter lookup. */ static final class PrefixHasher { - private final long[] h1; - private final long[] h2; - private final int prefixLength; + private final long[] prefixH1; + private final long[] prefixH2; + private final byte[] prefix; + private final int[] seeds; + private final boolean[] initialized; private byte[] buffer; private int length; PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { + this.prefix = prefix; + this.seeds = seeds; buffer = prefix; - prefixLength = prefix.length; - h1 = new long[seedCount]; - h2 = new long[seedCount]; - for (int i = 0; i < seedCount; i++) { - h1[i] = seeds[i]; - h2[i] = seeds[i]; - for (int block = 0; block < prefixLength / 16; block++) { - h1[i] = mixH1(h1[i], h2[i], getBlock(prefix, 0, block * 2)); - h2[i] = mixH2(h1[i], h2[i], getBlock(prefix, 0, block * 2 + 1)); - } - } + prefixH1 = new long[seedCount]; + prefixH2 = new long[seedCount]; + initialized = new boolean[seedCount]; } void setSuffix(byte[] suffix) { - length = prefixLength + suffix.length; + length = Math.addExact(prefix.length, suffix.length); if (buffer.length < length) { - buffer = Arrays.copyOf(buffer, length); + int capacity = Math.max(length, buffer.length + (buffer.length >>> 1)); + buffer = Arrays.copyOf(prefix, capacity); } - System.arraycopy(suffix, 0, buffer, prefixLength, suffix.length); + System.arraycopy(suffix, 0, buffer, prefix.length, suffix.length); } int hash(int seedIndex) { - return (int) innerHash(buffer, prefixLength / 16 * 16, length, h1[seedIndex], h2[seedIndex]); + int blocks = prefix.length / 16; + if (!initialized[seedIndex]) { + long h1 = seeds[seedIndex]; + long h2 = h1; + for (int block = 0; block < blocks; block++) { + h1 = mixH1(h1, h2, getBlock(prefix, 0, block * 2)); + h2 = mixH2(h1, h2, getBlock(prefix, 0, block * 2 + 1)); + } + prefixH1[seedIndex] = h1; + prefixH2[seedIndex] = h2; + initialized[seedIndex] = true; + } + return (int) innerHash(buffer, blocks * 16, length, prefixH1[seedIndex], prefixH2[seedIndex]); } } } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java index 5abbe03539..ad2e6c5d3c 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java @@ -20,6 +20,7 @@ import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.read.common.FullPath; +import org.apache.tsfile.read.common.Path; import org.junit.Test; @@ -105,6 +106,25 @@ public void testBatchMatchesIndividualPaths() { } } + @Test + public void testBatchChecksBothEmptyDevicePathForms() { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create(""); + List measurements = Arrays.asList("s1", "", null, "missing", "s1"); + BitSet expected = new BitSet(); + expected.set(0); + expected.set(1); + expected.set(4); + for (boolean useSeparator : new boolean[] {false, true}) { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.01, 100); + for (String measurement : Arrays.asList("s1", "")) { + Path path = + useSeparator ? new FullPath(device, measurement) : new Path("", measurement, true); + filter.add(path); + } + assertEquals(expected, filter.mightContainBatch(device, measurements)); + } + } + private static void assertBatchMatchesSingles( BloomFilter filter, IDeviceID device, Collection measurements) { BitSet expected = new BitSet(); @@ -136,6 +156,24 @@ public void testPrefixHashAtBlockBoundaries() { } } + @Test + public void testGrowingSuffixesWithLateSeedLookup() { + assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); + String prefix = "p".repeat(159) + "."; + int[] seeds = {5, 7}; + Murmur128Hash.PrefixHasher hasher = + new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), seeds, seeds.length); + for (int length = 1; length <= 64; length++) { + String suffix = "s".repeat(length); + hasher.setSuffix(suffix.getBytes(StandardCharsets.UTF_8)); + assertEquals(Murmur128Hash.hash(prefix + suffix, seeds[0]), hasher.hash(0)); + } + hasher.setSuffix(new byte[0]); + assertEquals(Murmur128Hash.hash(prefix, seeds[1]), hasher.hash(1)); + assertEquals(Murmur128Hash.hash(prefix, seeds[0]), hasher.hash(0)); + } + @Test public void testBatchAgainstExistingFilter() { // Generated by the snapshot writer for root.d., root.d.s1 and root.d.temp. diff --git a/skills/tsfile/references/java.md b/skills/tsfile/references/java.md index 266f8b5eac..a112830e44 100644 --- a/skills/tsfile/references/java.md +++ b/skills/tsfile/references/java.md @@ -67,7 +67,8 @@ Pass an `IDeviceID` and the pending measurement names to `BitSet` follow the collection's iteration order. A clear bit rules out the corresponding measurement. A set bit requires checking the file's metadata. Use an ordered collection when matching positions back to measurement names. -An empty measurement name probes the time column. +An empty measurement name probes the time column. For an empty device ID, the +lookup checks both supported path forms, for example `s1` and `.s1`. ## Guidance From 154ce991d4c4f9b61179ca2efaaf2e5ad2ed76c2 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Tue, 1 Dec 2026 11:18:54 +0800 Subject: [PATCH 4/4] Preserve Murmur hash slice semantics in batch Bloom lookups --- .../org/apache/tsfile/utils/BloomFilter.java | 4 ++ .../apache/tsfile/utils/Murmur128Hash.java | 47 ++++++++++++------- .../apache/tsfile/utils/BloomFilterTest.java | 44 +++++++++++++---- skills/tsfile/references/java.md | 7 ++- 4 files changed, 75 insertions(+), 27 deletions(-) diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java index 5cde1f7f4e..810a009db8 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java @@ -141,8 +141,12 @@ public boolean contains(String value) { * ith measurement in iteration order. A null measurement has a clear bit. An empty measurement * tests the device's time-column path. For an empty device, both path forms (with and without the * leading separator) are checked. + * + * @throws NullPointerException if the device or the measurement collection is null */ public BitSet mightContainBatch(IDeviceID device, Collection measurements) { + Objects.requireNonNull(device); + Objects.requireNonNull(measurements); BitSet matches = new BitSet(measurements.size()); if (measurements.isEmpty()) { return matches; diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java index d7a5afa527..d8c17f0184 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java @@ -84,13 +84,14 @@ private static long fmix(long k) { return k; } - private static long innerHash(byte[] key, int offset, int length, long seed) { - return innerHash(key, offset, length, seed, seed); + static long innerHash(byte[] key, int offset, int length, long seed) { + return innerHash(key, offset, length, length, seed, seed); } - // offset is the number of complete prefix bytes already mixed into h1 and h2. - private static long innerHash(byte[] key, int offset, int length, long h1, long h2) { - final int nblocks = (length - offset) >> 4; // Process as 128-bit blocks. + // totalLength includes any complete prefix blocks already mixed into h1 and h2. + private static long innerHash( + byte[] key, int offset, int length, int totalLength, long h1, long h2) { + final int nblocks = length >> 4; // Process as 128-bit blocks. // ---------- // body for (int i = 0; i < nblocks; i++) { @@ -165,8 +166,8 @@ private static long innerHash(byte[] key, int offset, int length, long h1, long } // ---------- // finalization - h1 ^= length; - h2 ^= length; + h1 ^= totalLength; + h2 ^= totalLength; h1 += h2; h2 += h1; h1 = fmix(h1); @@ -201,35 +202,40 @@ static final class PrefixHasher { private final long[] prefixH1; private final long[] prefixH2; private final byte[] prefix; + private final int prefixBlockBytes; private final int[] seeds; private final boolean[] initialized; private byte[] buffer; - private int length; + private int totalLength; PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { this.prefix = prefix; this.seeds = seeds; - buffer = prefix; + prefixBlockBytes = prefix.length - (prefix.length % 16); + totalLength = prefix.length; + buffer = Arrays.copyOfRange(prefix, prefixBlockBytes, prefix.length); prefixH1 = new long[seedCount]; prefixH2 = new long[seedCount]; initialized = new boolean[seedCount]; } void setSuffix(byte[] suffix) { - length = Math.addExact(prefix.length, suffix.length); - if (buffer.length < length) { - int capacity = Math.max(length, buffer.length + (buffer.length >>> 1)); - buffer = Arrays.copyOf(prefix, capacity); + totalLength = Math.addExact(prefix.length, suffix.length); + int remaining = totalLength - prefixBlockBytes; + int prefixTailLength = prefix.length - prefixBlockBytes; + if (buffer.length < remaining) { + int capacity = Math.max(remaining, buffer.length + (buffer.length >>> 1)); + buffer = new byte[capacity]; + System.arraycopy(prefix, prefixBlockBytes, buffer, 0, prefixTailLength); } - System.arraycopy(suffix, 0, buffer, prefix.length, suffix.length); + System.arraycopy(suffix, 0, buffer, prefixTailLength, suffix.length); } int hash(int seedIndex) { - int blocks = prefix.length / 16; if (!initialized[seedIndex]) { long h1 = seeds[seedIndex]; long h2 = h1; - for (int block = 0; block < blocks; block++) { + for (int block = 0; block < prefixBlockBytes / 16; block++) { h1 = mixH1(h1, h2, getBlock(prefix, 0, block * 2)); h2 = mixH2(h1, h2, getBlock(prefix, 0, block * 2 + 1)); } @@ -237,7 +243,14 @@ int hash(int seedIndex) { prefixH2[seedIndex] = h2; initialized[seedIndex] = true; } - return (int) innerHash(buffer, blocks * 16, length, prefixH1[seedIndex], prefixH2[seedIndex]); + return (int) + innerHash( + buffer, + 0, + totalLength - prefixBlockBytes, + totalLength, + prefixH1[seedIndex], + prefixH2[seedIndex]); } } } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java index ad2e6c5d3c..430f5eb55b 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java @@ -34,6 +34,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -106,6 +107,15 @@ public void testBatchMatchesIndividualPaths() { } } + @Test + public void testBatchRejectsNullArguments() { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.05, 10); + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.d"); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(null, List.of())); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(null, List.of("s1"))); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(device, null)); + } + @Test public void testBatchChecksBothEmptyDevicePathForms() { IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create(""); @@ -136,10 +146,24 @@ private static void assertBatchMatchesSingles( assertEquals(expected, filter.mightContainBatch(device, measurements)); } + @Test + public void testHashByteSlices() { + byte[] data = new byte[65]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) (i * 31); + } + for (int offset = 0; offset <= data.length; offset++) { + for (int length = 0; length <= data.length - offset; length++) { + byte[] slice = Arrays.copyOfRange(data, offset, offset + length); + assertEquals( + Murmur128Hash.innerHash(slice, 0, slice.length, 5), + Murmur128Hash.innerHash(data, offset, length, 5)); + } + } + } + @Test public void testPrefixHashAtBlockBoundaries() { - // The optimized reader is used when the scalar API encodes paths as UTF-8. - assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); int[] seeds = {5, 7, 11, 19, 31, 37, 43, 59}; for (int i = 0; i < 48; i++) { String prefix = "区域." + "p".repeat(i) + "."; @@ -147,10 +171,10 @@ public void testPrefixHashAtBlockBoundaries() { new Murmur128Hash.PrefixHasher( prefix.getBytes(StandardCharsets.UTF_8), seeds, seeds.length); for (int j = 31; j >= 0; j--) { - String measurement = "é".repeat(j) + "温度"; + String measurement = "é".repeat(j) + "温度🌡"; hasher.setSuffix(measurement.getBytes(StandardCharsets.UTF_8)); for (int k = 0; k < seeds.length; k++) { - assertEquals(Murmur128Hash.hash(prefix + measurement, seeds[k]), hasher.hash(k)); + assertEquals(hashUtf8(prefix + measurement, seeds[k]), hasher.hash(k)); } } } @@ -158,7 +182,6 @@ public void testPrefixHashAtBlockBoundaries() { @Test public void testGrowingSuffixesWithLateSeedLookup() { - assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); String prefix = "p".repeat(159) + "."; int[] seeds = {5, 7}; Murmur128Hash.PrefixHasher hasher = @@ -167,11 +190,16 @@ public void testGrowingSuffixesWithLateSeedLookup() { for (int length = 1; length <= 64; length++) { String suffix = "s".repeat(length); hasher.setSuffix(suffix.getBytes(StandardCharsets.UTF_8)); - assertEquals(Murmur128Hash.hash(prefix + suffix, seeds[0]), hasher.hash(0)); + assertEquals(hashUtf8(prefix + suffix, seeds[0]), hasher.hash(0)); } hasher.setSuffix(new byte[0]); - assertEquals(Murmur128Hash.hash(prefix, seeds[1]), hasher.hash(1)); - assertEquals(Murmur128Hash.hash(prefix, seeds[0]), hasher.hash(0)); + assertEquals(hashUtf8(prefix, seeds[1]), hasher.hash(1)); + assertEquals(hashUtf8(prefix, seeds[0]), hasher.hash(0)); + } + + private static int hashUtf8(String value, int seed) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + return (int) Murmur128Hash.innerHash(bytes, 0, bytes.length, seed); } @Test diff --git a/skills/tsfile/references/java.md b/skills/tsfile/references/java.md index a112830e44..647c1c49a4 100644 --- a/skills/tsfile/references/java.md +++ b/skills/tsfile/references/java.md @@ -62,8 +62,11 @@ try (ITsFileTreeReader reader = ## Checking multiple measurements of one device -Pass an `IDeviceID` and the pending measurement names to -`filter.mightContainBatch(device, measurements)`. Bit positions in the returned +Use `TsFileSequenceReader.readBloomFilter()` to obtain the file's +`org.apache.tsfile.utils.BloomFilter`. If it returns `null`, check the file's +metadata for all requested measurements. Otherwise, pass a non-null `IDeviceID` +and a non-null collection to `filter.mightContainBatch(device, measurements)`. +An individual `null` name has a clear bit. Bit positions in the returned `BitSet` follow the collection's iteration order. A clear bit rules out the corresponding measurement. A set bit requires checking the file's metadata. Use an ordered collection when matching positions back to measurement names.