Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -25,18 +25,69 @@
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;

@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<String> 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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -37,85 +36,94 @@
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;

public class TableDeviceCacheAttributeGuard {

// Unbounded queue
private final LinkedBlockingDeque<Set<?>> applyQueue = new LinkedBlockingDeque<>();
private final Map<Integer, Pair<Long, String>>
fetchedSchemaRegionIds2LargestVersionAndDatabaseMap = new ConcurrentHashMap<>();
private final Map<Integer, Long> 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<Long> addFetchQueryId(final long queryId) {
public synchronized @Nonnull Set<Long> addFetchQueryId(final long queryId) {
// Register the ID before tryUpdateCache can remove an empty fetch group.
final Set<?> lastSet = applyQueue.peekLast();
final Set<Long> longSet;
if (Objects.isNull(lastSet) || lastSet instanceof HashSet) {
longSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
applyQueue.add(longSet);
} else {
// The elements must be SetFromMap<Long> or HashSet<byte[]>
// Fetch IDs use a concurrent set. Queued cache updates use a HashSet.
longSet = (Set<Long>) lastSet;
}
longSet.add(queryId);
return longSet;
}

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<Runnable> 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<Integer, byte[]> schemaRegionIdContainerBytesPair =
(Pair<Integer, byte[]>) element;
handleContainer(
fetchedSchemaRegionIds2LargestVersionAndDatabaseMap
.get(schemaRegionIdContainerBytesPair.getLeft())
.getRight(),
DeviceAttributeCacheUpdater.getContainer(
schemaRegionIdContainerBytesPair.getRight()));
}
((Set<Runnable>) firstElement).forEach(Runnable::run);
applyQueue.removeFirst();
} else if (firstElement.isEmpty()) {
applyQueue.removeFirst();
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ private void invalidate(final ToLongFunction<UpdateContainer> updateFunction) {

public Pair<Long, Map<TDataNodeLocation, byte[]>> 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
Expand Down Expand Up @@ -183,7 +186,7 @@ public Pair<Long, Map<TDataNodeLocation, byte[]>> getAttributeUpdateInfo(
limit.addAndGet(-5);
updateBytes.put(location, container.getUpdateContent(limit, hasRemaining));
}
return new Pair<>(version.get(), updateBytes);
return new Pair<>(batchVersion, updateBytes);
Comment thread
JackieTien97 marked this conversation as resolved.
Resolved
}

public void commit(final TableDeviceAttributeCommitUpdateNode node) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ protected void executeTask() {
final Pair<Long, Map<TDataNodeLocation, byte[]>> currentResult =
regionLeader.getAttributeUpdateInfo(limit, hasRemaining);
if (currentResult.getRight().isEmpty()) {
break;
continue;
}
attributeUpdateCommitMap.put(regionLeader.getSchemaRegionId(), currentResult);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -48,14 +52,18 @@
import org.junit.BeforeClass;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
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;
Expand Down Expand Up @@ -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<String, Binary> oldValue =
Collections.singletonMap(attributeName1, new Binary("old", TSFileConfig.STRING_CHARSET));
final Map<String, Binary> 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<Long> 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<String, Binary> values) {
final UpdateDetailContainer container = new UpdateDetailContainer();
container.updateAttribute(table1, tags, values);
final byte[] body = container.getUpdateContent(new AtomicInteger(4096), new AtomicBoolean());
final Map<Integer, TSchemaRegionAttributeInfo> 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();
Expand Down
Loading
Loading