Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tile hashing fix #436

Merged
merged 6 commits into from
Jan 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,19 @@ private boolean containsOnlyFillsOrEdges(boolean allowEdges) {
return !empty;
}

public boolean likelyToBeDuplicate() {
msbarry marked this conversation as resolved.
Show resolved Hide resolved
if (layers.size() <= 0) {
return true;
} else if (layers.size() == 1 && layers.values().stream().findFirst().get().encodedFeatures.isEmpty()) {
return true;
}
var result = containsOnlyFillsOrEdges();
if (result) {
return true;
}
return result;
}

msbarry marked this conversation as resolved.
Show resolved Hide resolved
private enum Command {
MOVE_TO(1),
LINE_TO(2),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import com.onthegomap.planetiler.util.CloseableConusmer;
import com.onthegomap.planetiler.util.CommonStringEncoder;
import com.onthegomap.planetiler.util.DiskBacked;
import com.onthegomap.planetiler.util.Hashing;
import com.onthegomap.planetiler.util.LayerStats;
import com.onthegomap.planetiler.worker.Worker;
import java.io.Closeable;
Expand Down Expand Up @@ -368,22 +367,6 @@ public TileCoord tileCoord() {
return tileCoord;
}

/**
* Generates a hash over the feature's relevant data: layer, geometry, and attributes. The coordinates are
* <b>not</b> part of the hash.
* <p>
* Used as an optimization to avoid writing the same (ocean) tiles over and over again.
*/
public long generateContentHash() {
long hash = Hashing.FNV1_64_INIT;
for (var feature : entries) {
byte layerId = extractLayerIdFromKey(feature.key());
hash = Hashing.fnv1a64(hash, layerId);
hash = Hashing.fnv1a64(hash, feature.value());
}
return hash;
}

/**
* Returns true if {@code other} contains features with identical layer, geometry, and attributes, as this tile -
* even if the tiles have separate coordinates.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.onthegomap.planetiler.util.DiskBacked;
import com.onthegomap.planetiler.util.FileUtils;
import com.onthegomap.planetiler.util.Format;
import com.onthegomap.planetiler.util.Hashing;
import com.onthegomap.planetiler.util.LayerStats;
import com.onthegomap.planetiler.worker.WorkQueue;
import com.onthegomap.planetiler.worker.Worker;
Expand Down Expand Up @@ -289,8 +290,8 @@ private void tileEncoder(Iterable<TileBatch> prev, Consumer<TileBatch> next) thr
lastEncoded = encoded;
lastBytes = bytes;
last = tileFeatures;
if (compactDb && en.containsOnlyFillsOrEdges()) {
tileDataHash = tileFeatures.generateContentHash();
if (compactDb && en.likelyToBeDuplicate() && bytes != null) {
tileDataHash = generateContentHash(bytes);
msbarry marked this conversation as resolved.
Show resolved Hide resolved
} else {
tileDataHash = null;
}
Expand Down Expand Up @@ -412,6 +413,17 @@ private long tilesEmitted() {
return Stream.of(tilesByZoom).mapToLong(c -> c.get()).sum();
}

/**
* Generates a hash over encoded and compressed tile.
* <p>
* Used as an optimization to avoid writing the same (mostly ocean) tiles over and over again.
*/
public static long generateContentHash(byte[] bytes) {
long hash = Hashing.FNV1_64_INIT;
hash = Hashing.fnv1a64(hash, bytes);
return hash;
}

msbarry marked this conversation as resolved.
Show resolved Hide resolved
/**
* Container for a batch of tiles to be processed together in the encoder and writer threads.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
Expand All @@ -42,6 +44,7 @@
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.locationtech.jts.algorithm.Orientation;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
Expand Down Expand Up @@ -685,4 +688,33 @@ public static void assertFeatureNear(Mbtiles db, String layer, Map<String, Objec
fail(e);
}
}

public static void assertTileDuplicates(Mbtiles db, int expected) {
try {
Connection connection = (Connection) FieldUtils.readField(db, "connection", true);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT tile_data FROM tiles_data");
ArrayList<byte[]> tilesList = new ArrayList<>();
while (rs.next()) {
tilesList.add(rs.getBytes("tile_data"));
}

var tiles = tilesList.toArray(new byte[0][0]);
Set<Integer> dups = new HashSet<>();
for (int i = 0; i < tiles.length; i++) {
for (int j = i + 1; j < tiles.length; j++) {
if (Arrays.equals(tiles[i], tiles[j])) {
if (!dups.contains(j)) {
dups.add(j);
}
}
}
}

int dupCount = dups.size();
assertEquals(expected, dupCount, "%d duplicates expected, %d found".formatted(expected, dupCount));
} catch (IllegalAccessException | SQLException e) {
fail(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
import com.onthegomap.planetiler.VectorTile;
import com.onthegomap.planetiler.geo.GeometryType;
import com.onthegomap.planetiler.geo.TileCoord;
import com.onthegomap.planetiler.mbtiles.MbtilesWriter;
import com.onthegomap.planetiler.render.RenderedFeature;
import com.onthegomap.planetiler.stats.Stats;
import com.onthegomap.planetiler.util.CloseableConusmer;
import com.onthegomap.planetiler.util.Gzip;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -356,17 +359,22 @@ void testHasSameContents(String testName, boolean expectSame, PuTileArgs args0,

@ParameterizedTest(name = "{0}")
@ArgumentsSource(SameFeatureGroupTestArgs.class)
void testGenerateContentHash(String testName, boolean expectSame, PuTileArgs args0, PuTileArgs args1) {
void testGenerateContentHash(String testName, boolean expectSame, PuTileArgs args0, PuTileArgs args1)
throws IOException {
put(args0);
put(args1);
sorter.sort();
var iter = features.iterator();
var tile0 = iter.next();
var tile1 = iter.next();
var tile0_hash = MbtilesWriter.generateContentHash(
msbarry marked this conversation as resolved.
Show resolved Hide resolved
Gzip.gzip(iter.next().getVectorTileEncoder().encode())
);
var tile1_hash = MbtilesWriter.generateContentHash(
Gzip.gzip(iter.next().getVectorTileEncoder().encode())
);
if (expectSame) {
assertEquals(tile0.generateContentHash(), tile1.generateContentHash());
assertEquals(tile0_hash, tile1_hash);
} else {
assertNotEquals(tile0.generateContentHash(), tile1.generateContentHash());
assertNotEquals(tile0_hash, tile1_hash);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ void integrationTest(@TempDir Path tmpDir) throws Exception {
"name", "EuroVelo 8 - Mediterranean Route - part Monaco",
"ref", "EV8"
), GeoUtils.WORLD_LAT_LON_BOUNDS, 25, LineString.class);

TestUtils.assertTileDuplicates(mbtiles, 0);
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there somewhere in the core module we can put this? I just want to make sure core functionality is verified there in case we remove/change examples in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So far no other UT is triggering the root-cause.

Hence I've tried to make a new UT in planetiler-core but then realized I would need to replicate quite a lot of code from planetiler-examples.

E.g. both options are "bad".

Conclusion so far was to go with "smaller bad", e.g. the current option, since it adds much smaller amount of code.

}
}
}