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
21 changes: 14 additions & 7 deletions engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java
Original file line number Diff line number Diff line change
Expand Up @@ -3810,9 +3810,9 @@ private void propagateSuperTypeIndexes(final LocalDocumentType superType, final
// the caller holds, and does not see the caller's uncommitted writes. Every family can share it since issue #10438,
// which made the vector ones join; the per-index test is kept so a family that cannot has the place to say so.
final DatabaseInternal database = (DatabaseInternal) schema.getDatabase();
// Asked about THIS type's buckets, the ones createSubIndexesFor builds over: a caller that wrote only elsewhere has
// nothing there for the build to see, so the build keeps a transaction of its own (issue #10450).
final boolean callerTransactionHasChanges = IndexBuilder.callerTransactionHasChangesIn(database, buckets);
// Asked about the buckets createSubIndexesFor builds over, this type's and its sub types': a caller that wrote only elsewhere
// has nothing there for the build to see, so the build keeps a transaction of its own (issue #10450).
final boolean callerTransactionHasChanges = IndexBuilder.callerTransactionHasChangesIn(database, cachedPolymorphicBuckets);

// Two lists, because "has to be built later" and "has to be taken away if anything goes wrong" are not the same
// set. An index family that cannot share the caller's transaction is built INLINE during component creation and
Expand Down Expand Up @@ -3909,19 +3909,26 @@ private static int txRetries(final DatabaseInternal database) {
}

/**
* One super-type index, over every bucket of THIS type that does not already carry it.
* One super-type index, over every bucket of THIS type and of the types below it that does not already carry it: the whole
* subtree joins the super type, so its records are the super type's records from now on (issue #12036). A sub type's
* bucket is looked up on the type that owns it, which is the type its sub-indexes are bound to.
*
* @param sharesCallerTransaction when true the component is created without an inline build and is appended to
* {@code toBuild}, so the build can join the caller's transaction later and see its
* pending writes; when false the build runs inline, here and now
*/
private void createSubIndexesFor(final TypeIndex index, final boolean sharesCallerTransaction, final List<Index> created,
final List<Index> toBuild) {
for (int i = 0; i < buckets.size(); i++) {
final Bucket bucket = buckets.get(i);
// THIS type's buckets and, deduplicated, the ones of every type below it: the list a polymorphic read of this type walks
final List<Bucket> subtreeBuckets = cachedPolymorphicBuckets;
for (int i = 0; i < subtreeBuckets.size(); i++) {
final Bucket bucket = subtreeBuckets.get(i);
final LocalDocumentType bucketOwner = schema.getBucketOwner(bucket.getFileId());
// The sub-indexes of a sub type's bucket are bound to the sub type, not to this one, so it is the one to ask
final LocalDocumentType carrier = bucketOwner != null ? bucketOwner : this;

boolean alreadyCreated = false;
for (final IndexInternal idx : getPolymorphicBucketIndexByBucketId(bucket.getFileId(), index.getPropertyNames())) {
for (final IndexInternal idx : carrier.getPolymorphicBucketIndexByBucketId(bucket.getFileId(), index.getPropertyNames())) {
final TypeIndex typeIndex = idx.getTypeIndex();
if (typeIndex != null && typeIndex.equals(index)) {
alreadyCreated = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,353 @@
/*
* Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
* SPDX-License-Identifier: Apache-2.0
*/
package com.arcadedb.schema;

import com.arcadedb.TestHelper;
import com.arcadedb.database.Identifiable;
import com.arcadedb.database.RID;
import com.arcadedb.exception.DuplicatedKeyException;
import com.arcadedb.index.IndexCursor;
import com.arcadedb.index.IndexInternal;
import com.arcadedb.index.TypeIndex;
import com.arcadedb.query.sql.executor.ResultSet;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
* Regression for #12036: {@code ALTER TYPE A SUPERTYPE +W}, where A already has sub types, put W's indexes on A's buckets only.
* The records of the sub types are W records from then on, so every index of W (and of W's super types) has to cover their
* buckets too, for every index kind, and a UNIQUE index has to refuse the change, with nothing changed, when the joining subtree
* holds a key the index already holds, as it does for A's own buckets (#11302).
*/
class SuperTypeSubtreeIndexPropagationTest extends TestHelper {

@Test
void uniqueIndexCoversTheWholeJoiningSubtree() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO W SET s = 'w1'");
database.command("sql", "INSERT INTO A SET s = 'a1'");
database.command("sql", "INSERT INTO X SET s = 'x1'");
database.command("sql", "INSERT INTO Y SET s = 'y1'");
});

database.command("sql", "ALTER TYPE A SUPERTYPE +W");

assertUniqueIndexCoversSubtree();
reopenDatabase();
assertUniqueIndexCoversSubtree();
}

@Test
void indexOfASuperTypeAboveTheNewOneCoversTheSubtree() {
database.command("sql", "CREATE VERTEX TYPE V0");
database.command("sql", "CREATE PROPERTY V0.s STRING");
database.command("sql", "CREATE INDEX ON V0 (s) NOTUNIQUE");
database.command("sql", "CREATE VERTEX TYPE W EXTENDS V0");
createSubtree();
database.transaction(() -> database.command("sql", "INSERT INTO Y SET s = 'y1'"));

database.command("sql", "ALTER TYPE A SUPERTYPE +W");

assertThat(keyRids("V0[s]", "y1")).hasSize(1);
assertThat(subIndexBucketNames("V0[s]")).contains(bucketOf("X"), bucketOf("Y"));
}

@Test
void duplicateInTheSubtreeAgainstTheSuperTypeIsRefusedAndUndone() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO W SET s = 'w1'");
database.command("sql", "INSERT INTO A SET s = 'a1'");
database.command("sql", "INSERT INTO Y SET s = 'w1'");
});

assertThatThrownBy(() -> database.command("sql", "ALTER TYPE A SUPERTYPE +W"))//
.isInstanceOf(DuplicatedKeyException.class)//
.hasMessageContaining("w1");

assertSubtreeIsNotUnderTheSuperType();
reopenDatabase();
assertSubtreeIsNotUnderTheSuperType();
}

@Test
void duplicateBetweenTwoTypesOfTheSubtreeIsRefusedAndUndone() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO A SET s = 'k'");
database.command("sql", "INSERT INTO X SET s = 'k'");
});

assertThatThrownBy(() -> database.command("sql", "ALTER TYPE A SUPERTYPE +W"))//
.isInstanceOf(DuplicatedKeyException.class)//
.hasMessageContaining("k");

assertSubtreeIsNotUnderTheSuperType();
}

@Test
void byItemIndexCoversTheSubtree() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.tags LIST OF STRING");
final String indexName;
try (final ResultSet rs = database.command("sql", "CREATE INDEX ON W (tags BY ITEM) NOTUNIQUE")) {
indexName = rs.next().getProperty("name");
}
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO A SET tags = ['alpha']");
database.command("sql", "INSERT INTO X SET tags = ['alpha', 'beta']");
database.command("sql", "INSERT INTO Y SET tags = ['alpha']");
});

database.command("sql", "ALTER TYPE A SUPERTYPE +W");

assertThat(keyRids(indexName, "alpha")).hasSize(3);
assertThat(keyRids(indexName, "beta")).hasSize(1);
}

@Test
void fullTextIndexCoversTheSubtree() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.t STRING");
database.command("sql", "CREATE INDEX ON W (t) FULL_TEXT");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO W SET t = 'alpha'");
database.command("sql", "INSERT INTO A SET t = 'alpha'");
database.command("sql", "INSERT INTO X SET t = 'alpha'");
database.command("sql", "INSERT INTO Y SET t = 'alpha beta'");
});

database.command("sql", "ALTER TYPE A SUPERTYPE +W");
database.transaction(() -> database.command("sql", "INSERT INTO X SET t = 'alpha later'"));

assertThat(typesFound("SELECT FROM W WHERE SEARCH_INDEX('W[t]', 'alpha') = true"))//
.containsExactlyInAnyOrder("W", "A", "X", "Y", "X");
}

@Test
void vectorIndexCoversTheSubtree() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.v ARRAY_OF_FLOATS");
database.command("sql", "CREATE INDEX ON W (v) LSM_VECTOR METADATA {dimensions: 2, similarity: 'EUCLIDEAN'}");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO W SET v = [0.1, 0.2]");
database.command("sql", "INSERT INTO A SET v = [0.3, 0.4]");
database.command("sql", "INSERT INTO X SET v = [0.5, 0.6]");
database.command("sql", "INSERT INTO Y SET v = [0.7, 0.8]");
});

database.command("sql", "ALTER TYPE A SUPERTYPE +W");

assertThat(typesFound("SELECT expand(vectorNeighbors('W[v]', [0.5, 0.5], 100))"))//
.containsExactlyInAnyOrder("W", "A", "X", "Y");
}

/** The build joins the caller's transaction when that transaction wrote only into the bucket of a sub type of the joining one. */
@Test
void recordOfASubTypeWrittenInTheCallersTransactionIsIndexed() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();

database.transaction(() -> {
database.command("sql", "INSERT INTO X SET s = 'x1'");
database.getSchema().getType("A").addSuperType("W");
// the caller reads its own write through the index, not only after the commit
assertThat(keyRids("W[s]", "x1")).hasSize(1);
});

assertCallersRecordIsIndexed();
reopenDatabase();
assertCallersRecordIsIndexed();
}

/** A caller that rolls back loses its record and its entry, and leaves the sub-indexes of the whole subtree in place and usable. */
@Test
void rollbackOfTheCallerLeavesTheSubIndexesOfTheSubtreeUsable() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();

database.begin();
database.command("sql", "INSERT INTO X SET s = 'x1'");
database.getSchema().getType("A").addSuperType("W");
database.rollback();

assertThat(database.countType("X", false)).isZero();
assertThat(database.getSchema().getIndexByName("W[s]").countEntries()).isZero();
assertThat(subIndexBucketNames("W[s]")).contains(bucketOf("A"), bucketOf("X"), bucketOf("Y"));

database.transaction(() -> database.command("sql", "INSERT INTO X SET s = 'x1'"));
assertCallersRecordIsIndexed();
}

/** The reverse operation takes the sub-indexes of the sub types' buckets away too, and the constraint of the super type with them. */
@Test
void removingTheSuperTypeAgainTakesTheSubIndexesOfTheWholeSubtreeAway() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
createSubtree();
database.transaction(() -> {
database.command("sql", "INSERT INTO W SET s = 'w1'");
database.command("sql", "INSERT INTO X SET s = 'x1'");
});
database.command("sql", "ALTER TYPE A SUPERTYPE +W");
assertThat(subIndexBucketNames("W[s]")).contains(bucketOf("W"), bucketOf("A"), bucketOf("X"), bucketOf("Y"));

database.command("sql", "ALTER TYPE A SUPERTYPE -W");

assertSubtreeIsNotUnderTheSuperType();
// the key of W is free again for the subtree
database.transaction(() -> database.command("sql", "INSERT INTO Y SET s = 'w1'"));
reopenDatabase();
assertSubtreeIsNotUnderTheSuperType();
}

/** A sub type that already carries the index through another super type keeps the one sub-index it has. */
@Test
void subTypeThatAlreadyCarriesTheIndexThroughAnotherSuperTypeGetsNoSecondSubIndex() {
database.command("sql", "CREATE VERTEX TYPE W");
database.command("sql", "CREATE PROPERTY W.s STRING");
database.command("sql", "CREATE INDEX ON W (s) UNIQUE");
database.command("sql", "CREATE VERTEX TYPE A");
database.command("sql", "CREATE VERTEX TYPE X EXTENDS A");
database.getSchema().getType("X").addSuperType("W");
assertThat(subIndexCountOnBucket("W[s]", bucketOf("X"))).isEqualTo(1);
database.transaction(() -> {
database.command("sql", "INSERT INTO A SET s = 'a1'");
database.command("sql", "INSERT INTO X SET s = 'x1'");
});

database.command("sql", "ALTER TYPE A SUPERTYPE +W");

assertDiamondHasOneSubIndexPerBucket();
reopenDatabase();
assertDiamondHasOneSubIndexPerBucket();
}

/** A, X EXTENDS A, Y EXTENDS X: a subtree two levels deep below the type that joins. */
private void createSubtree() {
database.command("sql", "CREATE VERTEX TYPE A");
database.command("sql", "CREATE VERTEX TYPE X EXTENDS A");
database.command("sql", "CREATE VERTEX TYPE Y EXTENDS X");
}

private void assertUniqueIndexCoversSubtree() {
assertThat(keyRids("W[s]", "x1")).hasSize(1);
assertThat(keyRids("W[s]", "y1")).hasSize(1);
assertThat(subIndexBucketNames("W[s]")).contains(bucketOf("A"), bucketOf("X"), bucketOf("Y"));

for (final String statement : List.of("INSERT INTO X SET s = 'w1'", "INSERT INTO Y SET s = 'x1'", "INSERT INTO A SET s = 'y1'",
"INSERT INTO X SET s = 'x1'"))
assertThatThrownBy(() -> database.transaction(() -> database.command("sql", statement)))//
.as(statement)//
.isInstanceOf(DuplicatedKeyException.class);

try (final ResultSet rs = database.query("sql", "SELECT count(*) AS n FROM W")) {
assertThat(rs.next().<Long>getProperty("n")).isEqualTo(4L);
}
}

private void assertCallersRecordIsIndexed() {
assertThat(keyRids("W[s]", "x1")).hasSize(1);
assertThat(subIndexBucketNames("W[s]")).contains(bucketOf("A"), bucketOf("X"), bucketOf("Y"));
assertThatThrownBy(() -> database.transaction(() -> database.command("sql", "INSERT INTO Y SET s = 'x1'")))//
.isInstanceOf(DuplicatedKeyException.class);
}

private void assertDiamondHasOneSubIndexPerBucket() {
for (final String type : List.of("A", "X"))
assertThat(subIndexCountOnBucket("W[s]", bucketOf(type))).as("sub-indexes on the bucket of " + type).isEqualTo(1);

assertThat(keyRids("W[s]", "a1")).hasSize(1);
assertThat(keyRids("W[s]", "x1")).hasSize(1);
assertThatThrownBy(() -> database.transaction(() -> database.command("sql", "INSERT INTO X SET s = 'a1'")))//
.isInstanceOf(DuplicatedKeyException.class);
}

/** The subtree is not under W: not a sub type of it, and no sub-index of W's index on any of its buckets. */
private void assertSubtreeIsNotUnderTheSuperType() {
assertThat(database.getSchema().getType("A").isSubTypeOf("W")).isFalse();
assertThat(database.getSchema().getType("Y").isSubTypeOf("W")).isFalse();
assertThat(subIndexBucketNames("W[s]")).containsExactly(bucketOf("W"));
for (final String type : List.of("A", "X", "Y"))
for (final IndexInternal idx : database.getSchema().getType(type).getPolymorphicBucketIndexByBucketId(
database.getSchema().getBucketByName(bucketOf(type)).getFileId(), null))
assertThat(idx.getTypeIndex().getName()).isNotEqualTo("W[s]");
}

private String bucketOf(final String type) {
return database.getSchema().getType(type).getBuckets(false).getFirst().getName();
}

private long subIndexCountOnBucket(final String indexName, final String bucketName) {
final int bucketId = database.getSchema().getBucketByName(bucketName).getFileId();
long count = 0;
for (final IndexInternal idx : ((TypeIndex) database.getSchema().getIndexByName(indexName)).getIndexesOnBuckets())
if (idx.getAssociatedBucketId() == bucketId)
count++;
return count;
}

private Set<String> subIndexBucketNames(final String indexName) {
final Set<String> names = new HashSet<>();
for (final IndexInternal idx : ((TypeIndex) database.getSchema().getIndexByName(indexName)).getIndexesOnBuckets())
names.add(database.getSchema().getBucketById(idx.getAssociatedBucketId()).getName());
return names;
}

private List<RID> keyRids(final String indexName, final Object key) {
final IndexCursor cursor = database.getSchema().getIndexByName(indexName).get(new Object[] { key });
final List<RID> rids = new ArrayList<>();
while (cursor.hasNext())
rids.add(cursor.next().getIdentity());
return rids;
}

private List<String> typesFound(final String query) {
try (final ResultSet rs = database.query("sql", query)) {
// an expanded vectorNeighbors row carries the record under 'record'
return rs.stream().map(r -> r.getElement().orElseGet(() -> ((Identifiable) r.getProperty("record")).asDocument()).getTypeName())
.toList();
}
}
}
Loading