diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java index 2086ecc3549e4..b87d718aa45cb 100644 --- a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java @@ -25,11 +25,17 @@ import org.apache.iotdb.itbase.category.TableClusterIT; import org.apache.iotdb.relational.it.schema.fault.MetadataFaultController.Node; +import org.awaitility.Awaitility; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import java.sql.Connection; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -37,6 +43,51 @@ @RunWith(IoTDBTestRunner.class) @Category(TableClusterIT.class) public class IoTDBAttributeUpdateOrderingIT extends TableMetadataPropagationTestBase { + @Test + public void testBroadcastPastIdleSchemaRegion() throws Exception { + // Three single-replica SchemaRegions on two DataNodes put at least two leaders on one node. + final List databases = + Arrays.asList("metadata_broadcast_a", "metadata_broadcast_b", "metadata_broadcast_c"); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + try { + for (String db : databases) { + statement.execute("CREATE DATABASE " + db); + statement.execute( + "CREATE TABLE " + + db + + ".sensor (device STRING TAG, model STRING ATTRIBUTE, reading INT32 FIELD)"); + statement.execute( + "INSERT INTO " + + db + + ".sensor(time, device, model, reading) VALUES (1, 'd0', 'old', 10)"); + } + for (String db : databases) { + assertCachedModel(db, "old"); + } + // Update one region at a time so that the other leaders are idle in any iteration order. + for (String db : databases) { + statement.execute("UPDATE " + db + ".sensor SET model='new' WHERE device='d0'"); + Awaitility.await("attribute broadcast for " + db) + .atMost(20, TimeUnit.SECONDS) + .untilAsserted(() -> assertCachedModel(db, "new")); + } + } finally { + for (String db : databases) { + statement.execute("DROP DATABASE IF EXISTS " + db); + } + } + } + } + + private static void assertCachedModel(String database, String model) { + TestUtils.tableResultSetEqualTestUnordered( + "SELECT model, reading FROM sensor WHERE device='d0'", + new String[] {"model", "reading"}, + new String[] {model + ",10,"}, + database); + } + /** a delayed batch belongs to the dropped column's earlier lifetime. */ @Test public void testOldAttributeBatchAfterDropAndReadd() throws Exception { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java index 7176c1279008f..71b1bf666b96e 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java @@ -25,8 +25,7 @@ import org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateContainer; import org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateDetailContainer; import org.apache.iotdb.mpp.rpc.thrift.TAttributeUpdateReq; - -import org.apache.tsfile.utils.Pair; +import org.apache.iotdb.mpp.rpc.thrift.TSchemaRegionAttributeInfo; import javax.annotation.Nonnull; @@ -37,7 +36,6 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingDeque; -import java.util.stream.Collectors; import static org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceSchemaFetcher.convertTagValuesToDeviceID; @@ -45,29 +43,28 @@ public class TableDeviceCacheAttributeGuard { // Unbounded queue private final LinkedBlockingDeque> applyQueue = new LinkedBlockingDeque<>(); - private final Map> - fetchedSchemaRegionIds2LargestVersionAndDatabaseMap = new ConcurrentHashMap<>(); + private final Map acceptedRegionVersions = new ConcurrentHashMap<>(); private final TableDeviceSchemaCache cache = TableDeviceSchemaCache.getInstance(); public boolean isRegionFetched(final Integer schemaRegionId) { - return fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.containsKey(schemaRegionId); + return acceptedRegionVersions.containsKey(schemaRegionId); } public void addFetchedRegion(final Integer schemaRegionId) { // Later schema reads must not let delayed updates bypass the accepted version. - fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.putIfAbsent( - schemaRegionId, new Pair<>(Long.MIN_VALUE, null)); + acceptedRegionVersions.putIfAbsent(schemaRegionId, Long.MIN_VALUE); } @SuppressWarnings("unchecked") - public @Nonnull Set addFetchQueryId(final long queryId) { + public synchronized @Nonnull Set addFetchQueryId(final long queryId) { + // Register the ID before tryUpdateCache can remove an empty fetch group. final Set lastSet = applyQueue.peekLast(); final Set longSet; if (Objects.isNull(lastSet) || lastSet instanceof HashSet) { longSet = Collections.newSetFromMap(new ConcurrentHashMap<>()); applyQueue.add(longSet); } else { - // The elements must be SetFromMap or HashSet + // Fetch IDs use a concurrent set. Queued cache updates use a HashSet. longSet = (Set) lastSet; } longSet.add(queryId); @@ -75,47 +72,58 @@ public void addFetchedRegion(final Integer schemaRegionId) { } public synchronized void handleAttributeUpdate(final TAttributeUpdateReq updateReq) { - // Trim the schema regions with lower or equal version - // or with this node restarted before fetching + final Set updates = new HashSet<>(); updateReq .getAttributeUpdateMap() .entrySet() .removeIf( entry -> { - if (!fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.containsKey(entry.getKey()) - || entry.getValue().getVersion() - <= fetchedSchemaRegionIds2LargestVersionAndDatabaseMap - .get(entry.getKey()) - .getLeft()) { + final Long acceptedVersion = acceptedRegionVersions.get(entry.getKey()); + final TSchemaRegionAttributeInfo info = entry.getValue(); + if (acceptedVersion == null || info.getVersion() < acceptedVersion) { return true; } - fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.put( - entry.getKey(), - new Pair<>(entry.getValue().getVersion(), entry.getValue().getDatabase())); - return false; + final boolean sameVersion = info.getVersion() == acceptedVersion; + if (!sameVersion) { + acceptedRegionVersions.put(entry.getKey(), info.getVersion()); + } + final String database = info.getDatabase(); + final byte[] body = info.getBody(); + updates.add(() -> applyBatch(database, body, sameVersion)); + return sameVersion; }); - applyQueue.add( - updateReq.getAttributeUpdateMap().entrySet().stream() - .map(entry -> new Pair<>(entry.getKey(), entry.getValue().getBody())) - .collect(Collectors.toSet())); + applyQueue.add(updates); tryUpdateCache(); } + private void applyBatch(final String database, final byte[] body, final boolean sameVersion) { + final UpdateContainer container = DeviceAttributeCacheUpdater.getContainer(body); + if (sameVersion && container instanceof UpdateDetailContainer detail) { + // Several size-limited batches can share one write version. Invalidate the affected + // devices after older fetches finish. This also makes a delayed retry safe when a newer + // value has already been fetched. + detail + .getUpdateMap() + .forEach( + (table, devices) -> + devices + .keySet() + .forEach( + tags -> + cache.invalidateAttributes( + database, + convertTagValuesToDeviceID(table, tags.toArray(new String[0]))))); + } else { + handleContainer(database, container); + } + } + @SuppressWarnings("unchecked") public synchronized void tryUpdateCache() { while (!applyQueue.isEmpty()) { final Set firstElement = applyQueue.peek(); if (firstElement instanceof HashSet) { - for (final Object element : firstElement) { - final Pair schemaRegionIdContainerBytesPair = - (Pair) element; - handleContainer( - fetchedSchemaRegionIds2LargestVersionAndDatabaseMap - .get(schemaRegionIdContainerBytesPair.getLeft()) - .getRight(), - DeviceAttributeCacheUpdater.getContainer( - schemaRegionIdContainerBytesPair.getRight())); - } + ((Set) firstElement).forEach(Runnable::run); applyQueue.removeFirst(); } else if (firstElement.isEmpty()) { applyQueue.removeFirst(); @@ -128,14 +136,8 @@ public synchronized void tryUpdateCache() { // This must be synchronized with "handleUpdate" to avoid unordered execution // with region migration's "handleContainer" and stale "handleUpdate" logic public synchronized void setVersion(final int schemaRegionId, final long newVersion) { - fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.computeIfPresent( - schemaRegionId, - (id, pair) -> { - if (newVersion > pair.getLeft()) { - pair.setLeft(newVersion); - } - return pair; - }); + acceptedRegionVersions.computeIfPresent( + schemaRegionId, (id, version) -> Math.max(version, newVersion)); } public void handleContainer(final String database, final UpdateContainer container) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java index bb753c365c629..8219c3aae08c9 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java @@ -155,6 +155,9 @@ private void invalidate(final ToLongFunction updateFunction) { public Pair> getAttributeUpdateInfo( final @Nonnull AtomicInteger limit, final @Nonnull AtomicBoolean hasRemaining) { + // A write that finishes during serialization may be absent from these bytes. Its version + // belongs to a later batch. + final long batchVersion = version.get(); // Note that the "updateContainerStatistics" is unsafe to use here for whole read of detail // container because the update map is read by GRASS thread, and the container's size may change // during the read process @@ -183,7 +186,7 @@ public Pair> getAttributeUpdateInfo( limit.addAndGet(-5); updateBytes.put(location, container.getUpdateContent(limit, hasRemaining)); } - return new Pair<>(version.get(), updateBytes); + return new Pair<>(batchVersion, updateBytes); } public void commit(final TableDeviceAttributeCommitUpdateNode node) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java index 4f668a1907567..afee10c06453c 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java @@ -114,7 +114,7 @@ protected void executeTask() { final Pair> currentResult = regionLeader.getAttributeUpdateInfo(limit, hasRemaining); if (currentResult.getRight().isEmpty()) { - break; + continue; } attributeUpdateCommitMap.put(regionLeader.getSchemaRegionId(), currentResult); } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java index 30c6c04d913eb..31d9f96762b03 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java @@ -54,6 +54,24 @@ public void testSchemaFetchPreservesAcceptedVersion() { assertFalse(newer.getAttributeUpdateMap().isEmpty()); } + @Test + public void testMigrationOnlyAdvancesFetchedRegionVersion() { + final TableDeviceCacheAttributeGuard guard = new TableDeviceCacheAttributeGuard(); + guard.setVersion(1, 5); + assertFalse(guard.isRegionFetched(1)); + + guard.addFetchedRegion(1); + assertTrue(guard.isRegionFetched(1)); + guard.setVersion(1, 5); + guard.setVersion(1, 3); + final TAttributeUpdateReq stale = update(4); + guard.handleAttributeUpdate(stale); + assertTrue(stale.getAttributeUpdateMap().isEmpty()); + final TAttributeUpdateReq newer = update(6); + guard.handleAttributeUpdate(newer); + assertFalse(newer.getAttributeUpdateMap().isEmpty()); + } + private static TAttributeUpdateReq update(final long version) { final byte[] body = new UpdateDetailContainer().getUpdateContent(new AtomicInteger(1024), new AtomicBoolean()); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java index 9b53a0e34fee8..2b460d5758519 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java @@ -31,7 +31,11 @@ import org.apache.iotdb.commons.schema.table.column.TimeColumnSchema; import org.apache.iotdb.confignode.rpc.thrift.TDatabaseSchema; import org.apache.iotdb.db.queryengine.plan.analyze.cache.partition.PartitionCache; +import org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceCacheAttributeGuard; +import org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateDetailContainer; import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache; +import org.apache.iotdb.mpp.rpc.thrift.TAttributeUpdateReq; +import org.apache.iotdb.mpp.rpc.thrift.TSchemaRegionAttributeInfo; import org.apache.tsfile.common.conf.TSFileConfig; import org.apache.tsfile.enums.TSDataType; @@ -48,6 +52,7 @@ import org.junit.BeforeClass; import org.junit.Test; +import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -55,7 +60,10 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalLong; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import static org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceSchemaFetcher.convertTagValuesToDeviceID; import static org.mockito.ArgumentMatchers.anyInt; @@ -201,6 +209,43 @@ private TableDeviceSchemaCache createTestCache() { return TableDeviceSchemaCache.createForTest(1300L); } + @Test + public void testDifferentAttributeBatchesAtTheSameVersion() { + final TableDeviceSchemaCache cache = TableDeviceSchemaCache.getInstance(); + final TableDeviceCacheAttributeGuard guard = new TableDeviceCacheAttributeGuard(); + guard.addFetchedRegion(1); + final String[] firstTags = {"hebei", "p_1", "d_0"}; + final String[] secondTags = {"hebei", "p_1", "d_1"}; + final IDeviceID first = convertTagValuesToDeviceID(table1, firstTags); + final IDeviceID second = convertTagValuesToDeviceID(table1, secondTags); + final Map oldValue = + Collections.singletonMap(attributeName1, new Binary("old", TSFileConfig.STRING_CHARSET)); + final Map newValue = + Collections.singletonMap(attributeName1, new Binary("new", TSFileConfig.STRING_CHARSET)); + cache.putAttributes(database1, first, oldValue); + cache.putAttributes(database1, second, oldValue); + + guard.handleAttributeUpdate(attributeBatch(firstTags, newValue)); + Assert.assertEquals(newValue, cache.getDeviceAttribute(database1, first)); + final Set fetches = guard.addFetchQueryId(42); + guard.handleAttributeUpdate(attributeBatch(secondTags, newValue)); + // A fetch already in progress can still install its old result. + cache.putAttributes(database1, second, oldValue); + fetches.remove(42L); + guard.tryUpdateCache(); + Assert.assertNull(cache.getDeviceAttribute(database1, second)); + Assert.assertEquals(newValue, cache.getDeviceAttribute(database1, first)); + } + + private static TAttributeUpdateReq attributeBatch(String[] tags, Map values) { + final UpdateDetailContainer container = new UpdateDetailContainer(); + container.updateAttribute(table1, tags, values); + final byte[] body = container.getUpdateContent(new AtomicInteger(4096), new AtomicBoolean()); + final Map updates = new HashMap<>(); + updates.put(1, new TSchemaRegionAttributeInfo(3L, database1, ByteBuffer.wrap(body))); + return new TAttributeUpdateReq(updates); + } + @Test public void testDeviceCache() { final TableDeviceSchemaCache cache = createTestCache(); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java index db72c6c963eb4..23db80b52b4de 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java @@ -19,8 +19,12 @@ package org.apache.iotdb.db.schemaengine.schemaregion.attribute.update; +import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation; +import org.apache.iotdb.db.schemaengine.rescon.MemSchemaRegionStatistics; + import org.apache.tsfile.common.conf.TSFileConfig; import org.apache.tsfile.utils.Binary; +import org.apache.tsfile.utils.Pair; import org.apache.tsfile.utils.ReadWriteIOUtils; import org.junit.Test; @@ -39,9 +43,52 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class UpdateContainerSerializationTest { + @Test + public void testBatchVersionWhenAttributeChangesDuringSerialization() { + final MemSchemaRegionStatistics statistics = mock(MemSchemaRegionStatistics.class); + when(statistics.isAllowToCreateNewSeries()).thenReturn(true); + final DeviceAttributeCacheUpdater updater = new DeviceAttributeCacheUpdater(statistics, "db"); + final TDataNodeLocation remote = new TDataNodeLocation().setDataNodeId(Integer.MAX_VALUE); + updater.addLocation(remote); + final String[] device = {"d1"}; + final Binary updated = new Binary("after", TSFileConfig.STRING_CHARSET); + final Binary initial = + new Binary("before", TSFileConfig.STRING_CHARSET) { + @Override + public byte[] getValues() { + // Complete the next write after the broadcaster has selected the previous value. + updater.update("t", device, Collections.singletonMap("model", updated)); + updater.afterUpdate(); + return super.getValues(); + } + }; + updater.update("t", device, Collections.singletonMap("model", initial)); + updater.afterUpdate(); + + final Pair> first = + updater.getAttributeUpdateInfo(new AtomicInteger(4096), new AtomicBoolean()); + final Pair> second = + updater.getAttributeUpdateInfo(new AtomicInteger(4096), new AtomicBoolean()); + assertEquals( + new Binary("before", TSFileConfig.STRING_CHARSET), + modelInBatch(first.getRight().get(remote))); + assertEquals(updated, modelInBatch(second.getRight().get(remote))); + assertTrue( + "Versions of the two writes: " + first.getLeft() + ", " + second.getLeft(), + first.getLeft() < second.getLeft()); + } + + private static Binary modelInBatch(final byte[] bytes) { + final UpdateDetailContainer container = + (UpdateDetailContainer) DeviceAttributeCacheUpdater.getContainer(bytes); + return container.getUpdateMap().get("t").get(Collections.singletonList("d1")).get("model"); + } + @Test public void testTableAddedDuringSerialization() throws Exception { assertConcurrentUpdateRoundTrip(0);