mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(dynamodb): vector indexes and SearchVectors (#4215)
* feat(dynamodb): define vector indexes on the table control plane * feat(dynamodb): serve SearchVectors against vector indexes * feat(dynamodb): validate vector attributes on write * feat(dynamodb): report vector write capacity on writes * fix(dynamodb): reject a PartiQL read of a vector index * test(dynamodb): cover vector search in Floci's own suite * fix(dynamodb): match AWS on vector member paths and the f32 number format * fix(dynamodb): match AWS on the vector search validation gaps * perf(dynamodb): stop retaining and recomputing per candidate in vector search * docs(dynamodb): document that indexes are not stored
This commit is contained in:
1 parent
6fadba8d57
commit
133ef62d27
20 files changed
+3014
-9
No files matched your search
@@ -1283,6 +1283,24 @@ public interface EmulatorConfig {
|
||||
interface DynamoDbServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* Seconds a vector index added by UpdateTable spends in the resource allocation phase,
|
||||
* where the table reads UPDATING, the index reads CREATING with Backfilling false, and a
|
||||
* delete of that index is refused.
|
||||
* Env: FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_ALLOCATION_SECONDS
|
||||
*/
|
||||
@WithDefault("4")
|
||||
int vectorIndexAllocationSeconds();
|
||||
|
||||
/**
|
||||
* Seconds the same index then spends backfilling, where the table reads ACTIVE and the
|
||||
* index reads CREATING with Backfilling true. A vector index created by CreateTable skips
|
||||
* both phases and is ACTIVE at once, which is what AWS reports there.
|
||||
* Env: FLOCI_SERVICES_DYNAMODB_VECTOR_INDEX_BACKFILL_SECONDS
|
||||
*/
|
||||
@WithDefault("10")
|
||||
int vectorIndexBackfillSeconds();
|
||||
}
|
||||
|
||||
interface SnsServiceConfig {
|
||||
|
||||
@@ -153,7 +153,7 @@ final class DynamoDbItemSize {
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int utf8Length(String s) {
|
||||
static int utf8Length(String s) {
|
||||
if (s == null) return 0;
|
||||
return s.getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
|
||||
+256
-2
@@ -57,6 +57,7 @@ public class DynamoDbJsonHandler {
|
||||
case "UpdateItem" -> handleUpdateItem(request, region);
|
||||
case "Query" -> handleQuery(request, region);
|
||||
case "Scan" -> handleScan(request, region);
|
||||
case "SearchVectors" -> handleSearchVectors(request, region);
|
||||
case "BatchWriteItem" -> handleBatchWriteItem(request, region);
|
||||
case "BatchGetItem" -> handleBatchGetItem(request, region);
|
||||
case "UpdateTable" -> handleUpdateTable(request, region);
|
||||
@@ -191,6 +192,18 @@ public class DynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
List<DynamoDbService.VectorIndexCreate> vectorIndexes = new ArrayList<>();
|
||||
JsonNode vectorIndexArray = request.path("VectorIndexes");
|
||||
if (vectorIndexArray.isArray()) {
|
||||
int vectorPosition = 0;
|
||||
for (JsonNode vectorIndexNode : vectorIndexArray) {
|
||||
vectorPosition++;
|
||||
String memberPath = "vectorIndexes." + vectorPosition + ".member";
|
||||
vectorIndexes.add(new DynamoDbService.VectorIndexCreate(
|
||||
parseVectorIndex(vectorIndexNode, memberPath), memberPath));
|
||||
}
|
||||
}
|
||||
|
||||
String billingMode = request.has("BillingMode")
|
||||
? request.get("BillingMode").asText() : null;
|
||||
|
||||
@@ -221,7 +234,7 @@ public class DynamoDbJsonHandler {
|
||||
}
|
||||
|
||||
TableDefinition table = dynamoDbService.createTable(tableName, keySchema, attrDefs,
|
||||
readCapacity, writeCapacity, gsis, lsis, region);
|
||||
readCapacity, writeCapacity, gsis, lsis, vectorIndexes, billingMode, region);
|
||||
table.setTableStatus(initialStatus);
|
||||
|
||||
table.setDeletionProtectionEnabled(deletionProtection);
|
||||
@@ -305,6 +318,48 @@ public class DynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a VectorIndex or the CreateVectorIndexAction of a VectorIndexUpdate; same members. */
|
||||
private static VectorIndex parseVectorIndex(JsonNode node, String memberPath) {
|
||||
// An absent VectorAttribute is reported as the member itself, one that is present but
|
||||
// carries no AttributeName as the nested member. Only the request shape tells them apart.
|
||||
JsonNode vectorAttribute = node.path("VectorAttribute");
|
||||
if (vectorAttribute.isObject() && !vectorAttribute.hasNonNull("AttributeName")) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value null at '" + memberPath
|
||||
+ ".vectorAttribute.attributeName' failed to satisfy constraint: "
|
||||
+ "Member must not be null", 400);
|
||||
}
|
||||
List<SearchSchemaElement> searchSchema = new ArrayList<>();
|
||||
JsonNode searchSchemaArray = node.path("SearchSchema");
|
||||
if (searchSchemaArray.isArray()) {
|
||||
for (JsonNode element : searchSchemaArray) {
|
||||
searchSchema.add(new SearchSchemaElement(
|
||||
element.path("AttributeName").asText(null),
|
||||
element.path("SearchSchemaElementType").asText(null)));
|
||||
}
|
||||
}
|
||||
String projectionType = node.hasNonNull("Projection")
|
||||
? node.path("Projection").path("ProjectionType").asText("ALL") : null;
|
||||
List<String> nonKeyAttributes = new ArrayList<>();
|
||||
JsonNode nonKeyAttrArray = node.path("Projection").path("NonKeyAttributes");
|
||||
if (nonKeyAttrArray.isArray()) {
|
||||
for (JsonNode nonKeyAttr : nonKeyAttrArray) {
|
||||
nonKeyAttributes.add(nonKeyAttr.asText());
|
||||
}
|
||||
}
|
||||
rejectEmptyNonKeyAttributes(nonKeyAttrArray, memberPath);
|
||||
validateProjectionSpec(projectionType, nonKeyAttributes);
|
||||
Long dimensions = node.hasNonNull("Dimensions") ? node.get("Dimensions").asLong() : null;
|
||||
return new VectorIndex(
|
||||
node.path("IndexName").asText(null),
|
||||
node.path("VectorAttribute").path("AttributeName").asText(null),
|
||||
searchSchema,
|
||||
projectionType,
|
||||
nonKeyAttributes,
|
||||
dimensions,
|
||||
node.path("DistanceFunction").asText(null));
|
||||
}
|
||||
|
||||
// INCLUDE requires the NonKeyAttributes list; every other projection type forbids it.
|
||||
private static void validateProjectionSpec(String projectionType, List<String> nonKeyAttributes) {
|
||||
if ("INCLUDE".equals(projectionType) && nonKeyAttributes.isEmpty()) {
|
||||
@@ -1180,6 +1235,111 @@ public class DynamoDbJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// The floor AWS reports for a small search. The real figure is non-deterministic there,
|
||||
// so every search reports the floor (measured in eu-west-2, 2026-09-23).
|
||||
private static final double VECTOR_SEARCH_REQUEST_BYTES = 1024;
|
||||
|
||||
private static final int MAX_VECTOR_SEARCH_TOP_K = 100;
|
||||
|
||||
private Response handleSearchVectors(JsonNode request, String region) {
|
||||
requireSearchVectorsMember(request, "SearchVector");
|
||||
requireSearchVectorsMember(request, "IndexName");
|
||||
String tableName = request.path("TableName").asText();
|
||||
String indexName = request.get("IndexName").asText();
|
||||
String rccSearch = request.has("ReturnConsumedCapacity")
|
||||
? request.get("ReturnConsumedCapacity").asText() : null;
|
||||
if (rccSearch != null && !VALID_RETURN_CONSUMED_CAPACITY.contains(rccSearch)) {
|
||||
// No "N validation errors detected" envelope here, unlike every other operation.
|
||||
throw new AwsException("ValidationException",
|
||||
"Value '" + rccSearch + "' at 'returnConsumedCapacity' "
|
||||
+ "failed to satisfy constraint: Member must satisfy enum value set: "
|
||||
+ "[INDEXES, TOTAL, NONE]", 400);
|
||||
}
|
||||
requireSearchVectorsMember(request, "TopK");
|
||||
int topK = request.get("TopK").asInt();
|
||||
if (topK < 1) {
|
||||
// AWS names this member TopK and quotes no value, unlike every other member of this
|
||||
// family. Measured on real DynamoDB, eu-west-2, 2026-09-23.
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value at 'TopK' failed to satisfy "
|
||||
+ "constraint: Member must have value greater than or equal to 1", 400);
|
||||
}
|
||||
// Both bounds answer before the table and the index are resolved: AWS reports the range
|
||||
// even for a table that does not exist.
|
||||
if (topK > MAX_VECTOR_SEARCH_TOP_K) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Provided TopK value '" + topK + "' is out of valid range. "
|
||||
+ "The value must be between 1 and " + MAX_VECTOR_SEARCH_TOP_K + " inclusive", 400);
|
||||
}
|
||||
|
||||
TableDefinition table = dynamoDbService.settledTable(tableName, region);
|
||||
VectorIndex index = requireSearchableVectorIndex(table, indexName);
|
||||
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
List<DynamoDbVectorSearch.Hit> hits = DynamoDbVectorSearch.search(table, index,
|
||||
dynamoDbService.liveItems(table, region),
|
||||
request.path("SearchVector"), topK,
|
||||
request.has("SearchConditionExpression")
|
||||
? request.get("SearchConditionExpression").asText() : null,
|
||||
exprAttrNames, exprAttrValues,
|
||||
request.has("ProjectionExpression") ? request.get("ProjectionExpression").asText() : null);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode searchResults = objectMapper.createArrayNode();
|
||||
for (DynamoDbVectorSearch.Hit hit : hits) {
|
||||
ObjectNode searchResult = objectMapper.createObjectNode();
|
||||
searchResult.set("Item", hit.item());
|
||||
searchResult.put("Score", hit.score());
|
||||
searchResults.add(searchResult);
|
||||
}
|
||||
response.set("SearchResults", searchResults);
|
||||
if (rccSearch != null && !"NONE".equals(rccSearch)) {
|
||||
ObjectNode consumedCapacity = objectMapper.createObjectNode();
|
||||
consumedCapacity.put("VectorSearchRequestBytes", VECTOR_SEARCH_REQUEST_BYTES);
|
||||
response.set("ConsumedCapacity", consumedCapacity);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects an omitted required member of SearchVectors the way the AWS frontend does: as a
|
||||
* deserialisation failure quoting the offset of the body's closing brace, which for the
|
||||
* compact JSON an SDK sends is the body length. Measured in eu-west-2, 2026-09-23.
|
||||
*/
|
||||
private static void requireSearchVectorsMember(JsonNode request, String member) {
|
||||
if (!request.hasNonNull(member)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"missing field `" + member + "` at line 1 column "
|
||||
+ request.toString().length(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The vector index a search may run against.
|
||||
*
|
||||
* <p>An index still in its resource allocation phase answers as if the table did not have it,
|
||||
* which is the wording AWS uses there and what the documented readiness wait retries on.
|
||||
*/
|
||||
private VectorIndex requireSearchableVectorIndex(TableDefinition table, String indexName) {
|
||||
VectorIndex index = table.findVectorIndex(indexName).orElse(null);
|
||||
if (index == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The table does not have the specified index: " + indexName, 400);
|
||||
}
|
||||
if ("CREATING".equals(index.getIndexStatus())) {
|
||||
if (!dynamoDbService.isVectorIndexBackfilling(index)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The table does not have the specified index: " + indexName, 400);
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"Cannot search backfilling vector index: " + indexName, 400);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private Response handleBatchWriteItem(JsonNode request, String region) {
|
||||
JsonNode requestItems = request.get("RequestItems");
|
||||
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()
|
||||
@@ -1467,6 +1627,28 @@ public class DynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
List<DynamoDbService.VectorIndexCreate> vectorCreates = new ArrayList<>();
|
||||
List<String> vectorDeletes = new ArrayList<>();
|
||||
JsonNode vectorIndexUpdates = request.path("VectorIndexUpdates");
|
||||
if (vectorIndexUpdates.isArray()) {
|
||||
// AWS reports a per-member constraint under the position in this array, which a
|
||||
// create shares with the deletes beside it.
|
||||
int updatePosition = 0;
|
||||
for (JsonNode update : vectorIndexUpdates) {
|
||||
updatePosition++;
|
||||
JsonNode createNode = update.path("Create");
|
||||
if (createNode.isObject()) {
|
||||
String memberPath = "vectorIndexUpdates." + updatePosition + ".member.create";
|
||||
vectorCreates.add(new DynamoDbService.VectorIndexCreate(
|
||||
parseVectorIndex(createNode, memberPath), memberPath));
|
||||
}
|
||||
JsonNode deleteNode = update.path("Delete");
|
||||
if (deleteNode.isObject()) {
|
||||
vectorDeletes.add(deleteNode.path("IndexName").asText(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<AttributeDefinition> newAttrDefs = new ArrayList<>();
|
||||
JsonNode attrDefsNode = request.path("AttributeDefinitions");
|
||||
if (!attrDefsNode.isMissingNode() && attrDefsNode.isArray()) {
|
||||
@@ -1495,7 +1677,8 @@ public class DynamoDbJsonHandler {
|
||||
}
|
||||
|
||||
TableDefinition table = dynamoDbService.updateTable(tableName, readCapacity, writeCapacity,
|
||||
gsiCreates, gsiDeletes, newAttrDefs, region);
|
||||
gsiCreates, gsiDeletes, newAttrDefs, vectorCreates, vectorDeletes,
|
||||
billingModeCheck, region);
|
||||
|
||||
for (JsonNode updateNode : gsiUpdatesToApply) {
|
||||
GlobalSecondaryIndex gsi = table.findGsi(updateNode.path("IndexName").asText()).orElseThrow();
|
||||
@@ -2338,10 +2521,24 @@ public class DynamoDbJsonHandler {
|
||||
if (!cost.lsi().isEmpty()) {
|
||||
cc.set("LocalSecondaryIndexes", capacityUnitsMap(cost.lsi(), unitsField));
|
||||
}
|
||||
if (!cost.vectorBytes().isEmpty()) {
|
||||
cc.set("VectorIndexes", vectorWriteBytesMap(cost.vectorBytes()));
|
||||
}
|
||||
}
|
||||
return cc;
|
||||
}
|
||||
|
||||
/** A vector index meters bytes processed, so it carries no CapacityUnits of its own. */
|
||||
private ObjectNode vectorWriteBytesMap(Map<String, Double> bytesByIndex) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
bytesByIndex.forEach((indexName, bytes) -> {
|
||||
ObjectNode entry = objectMapper.createObjectNode();
|
||||
entry.put("VectorWriteRequestBytes", bytes);
|
||||
node.set(indexName, entry);
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode capacityUnitsMap(Map<String, Double> unitsByIndex, String unitsField) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
unitsByIndex.forEach((indexName, units) -> node.set(indexName, capacityUnitsNode(units, unitsField)));
|
||||
@@ -2597,6 +2794,15 @@ public class DynamoDbJsonHandler {
|
||||
node.set("LocalSecondaryIndexes", lsiArray);
|
||||
}
|
||||
|
||||
List<VectorIndex> vectorIndexes = table.getVectorIndexes();
|
||||
if (!vectorIndexes.isEmpty()) {
|
||||
ArrayNode vectorIndexArray = objectMapper.createArrayNode();
|
||||
for (VectorIndex vectorIndex : vectorIndexes) {
|
||||
vectorIndexArray.add(vectorIndexToNode(vectorIndex));
|
||||
}
|
||||
node.set("VectorIndexes", vectorIndexArray);
|
||||
}
|
||||
|
||||
if (table.getStreamArn() != null) {
|
||||
ObjectNode streamSpecNode = objectMapper.createObjectNode();
|
||||
streamSpecNode.put("StreamEnabled", table.isStreamEnabled());
|
||||
@@ -2612,6 +2818,54 @@ public class DynamoDbJsonHandler {
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a VectorIndexDescription. ItemCount and IndexSizeBytes are always 0. AWS refreshes
|
||||
* those two roughly every six hours, so a freshly built index reports 0 for both there too.
|
||||
*/
|
||||
private ObjectNode vectorIndexToNode(VectorIndex vectorIndex) {
|
||||
ObjectNode vectorIndexNode = objectMapper.createObjectNode();
|
||||
vectorIndexNode.put("IndexName", vectorIndex.getIndexName());
|
||||
|
||||
ObjectNode vectorAttribute = objectMapper.createObjectNode();
|
||||
vectorAttribute.put("AttributeName", vectorIndex.getVectorAttributeName());
|
||||
vectorIndexNode.set("VectorAttribute", vectorAttribute);
|
||||
|
||||
List<SearchSchemaElement> searchSchema = vectorIndex.getSearchSchema();
|
||||
if (searchSchema != null && !searchSchema.isEmpty()) {
|
||||
ArrayNode searchSchemaArray = objectMapper.createArrayNode();
|
||||
for (SearchSchemaElement element : searchSchema) {
|
||||
ObjectNode elementNode = objectMapper.createObjectNode();
|
||||
elementNode.put("AttributeName", element.getAttributeName());
|
||||
elementNode.put("SearchSchemaElementType", element.getSearchSchemaElementType());
|
||||
searchSchemaArray.add(elementNode);
|
||||
}
|
||||
vectorIndexNode.set("SearchSchema", searchSchemaArray);
|
||||
}
|
||||
|
||||
ObjectNode projection = objectMapper.createObjectNode();
|
||||
projection.put("ProjectionType",
|
||||
vectorIndex.getProjectionType() != null ? vectorIndex.getProjectionType() : "ALL");
|
||||
if ("INCLUDE".equals(vectorIndex.getProjectionType())) {
|
||||
ArrayNode nonKeyAttributes = objectMapper.createArrayNode();
|
||||
for (String attr : vectorIndex.getNonKeyAttributes()) {
|
||||
nonKeyAttributes.add(attr);
|
||||
}
|
||||
projection.set("NonKeyAttributes", nonKeyAttributes);
|
||||
}
|
||||
vectorIndexNode.set("Projection", projection);
|
||||
|
||||
vectorIndexNode.put("Dimensions", vectorIndex.getDimensions());
|
||||
vectorIndexNode.put("DistanceFunction", vectorIndex.getDistanceFunction());
|
||||
vectorIndexNode.put("IndexStatus", vectorIndex.getIndexStatus());
|
||||
if (dynamoDbService.reportsVectorIndexBackfilling(vectorIndex)) {
|
||||
vectorIndexNode.put("Backfilling", dynamoDbService.isVectorIndexBackfilling(vectorIndex));
|
||||
}
|
||||
vectorIndexNode.put("IndexSizeBytes", 0);
|
||||
vectorIndexNode.put("ItemCount", 0);
|
||||
vectorIndexNode.put("IndexArn", vectorIndex.getIndexArn());
|
||||
return vectorIndexNode;
|
||||
}
|
||||
|
||||
private String defaultKmsMasterKeyArn(String region) {
|
||||
return AwsArnUtils.Arn.of("kms", region, DEFAULT_ACCOUNT_ID,
|
||||
"key/aws-managed-dynamodb").toString();
|
||||
|
||||
@@ -46,6 +46,12 @@ class DynamoDbPartiQLHandler {
|
||||
|
||||
private Result executeSelect(Stmt.Select stmt, PartiQLExecuteContext ctx, String region) {
|
||||
TableDefinition table = service.describeTable(stmt.table(), region);
|
||||
// A vector index is reachable through SearchVectors alone, and PartiQL says so
|
||||
// rather than reporting the index as missing.
|
||||
if (table.findVectorIndex(stmt.index()).isPresent()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Scan operation not supported on this index type", 400);
|
||||
}
|
||||
// ExecuteStatement omits the index name from the missing-index message,
|
||||
// unlike Query/Scan (characterised on real AWS, eu-west-1, 2026-09-02).
|
||||
DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, stmt.index(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -17,6 +18,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
@@ -114,6 +116,26 @@ public class DynamoDbService implements ResourceProvider {
|
||||
|
||||
private static final int MAX_MULTI_ATTRIBUTE_KEY_PART_SIZE = 4;
|
||||
|
||||
private static final int MAX_VECTOR_INDEXES_PER_TABLE = 5;
|
||||
private static final int MAX_VECTOR_DIMENSIONS = 4096;
|
||||
private static final int MIN_VECTOR_INDEX_NAME_LENGTH = 3;
|
||||
// The order AWS prints the enum constraint in, which is neither alphabetical nor the order
|
||||
// the API reference lists.
|
||||
private static final List<String> VECTOR_DISTANCE_FUNCTIONS = List.of(
|
||||
DynamoDbVectorScoring.DOT_PRODUCT,
|
||||
DynamoDbVectorScoring.COSINE,
|
||||
DynamoDbVectorScoring.EUCLIDEAN);
|
||||
|
||||
/**
|
||||
* A vector index a request adds, with the request-model path AWS reports its per-member
|
||||
* constraints under.
|
||||
*
|
||||
* <p>CreateTable and UpdateTable name different members, and an UpdateTable create shares the
|
||||
* {@code VectorIndexUpdates} array with the deletes beside it, so only the caller that read
|
||||
* the request can build the path.
|
||||
*/
|
||||
public record VectorIndexCreate(VectorIndex index, String memberPath) {}
|
||||
|
||||
private record IdempotencyEntry(String requestHash, long insertedAtNanos,
|
||||
CompletableFuture<Map<String, DynamoDbWriteCapacity.Cost>> replayCapacity) {}
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -121,6 +143,8 @@ public class DynamoDbService implements ResourceProvider {
|
||||
private DynamoDbStreamService streamService;
|
||||
private KinesisStreamingForwarder kinesisForwarder;
|
||||
private S3Service s3Service;
|
||||
private final int vectorIndexAllocationSeconds;
|
||||
private final int vectorIndexBackfillSeconds;
|
||||
private static final long MAX_DYNAMODB_LIST_INDEX = 4_294_967_294L;
|
||||
|
||||
@Inject
|
||||
@@ -128,7 +152,8 @@ public class DynamoDbService implements ResourceProvider {
|
||||
DynamoDbStreamService streamService,
|
||||
KinesisStreamingForwarder kinesisForwarder,
|
||||
S3Service s3Service,
|
||||
ObjectMapper objectMapper) {
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
this(storageFactory.create("dynamodb", "dynamodb-tables.json",
|
||||
new TypeReference<Map<String, TableDefinition>>() {}),
|
||||
storageFactory.create("dynamodb", "dynamodb-items.json",
|
||||
@@ -137,7 +162,9 @@ public class DynamoDbService implements ResourceProvider {
|
||||
new TypeReference<Map<String, ExportDescription>>() {}),
|
||||
storageFactory.create("dynamodb", "dynamodb-imports.json",
|
||||
new TypeReference<Map<String, ImportTableDescription>>() {}),
|
||||
regionResolver, streamService, kinesisForwarder, s3Service, objectMapper);
|
||||
regionResolver, streamService, kinesisForwarder, s3Service, objectMapper,
|
||||
config.services().dynamodb().vectorIndexAllocationSeconds(),
|
||||
config.services().dynamodb().vectorIndexBackfillSeconds());
|
||||
}
|
||||
|
||||
/** Package-private constructor for testing. */
|
||||
@@ -172,6 +199,21 @@ public class DynamoDbService implements ResourceProvider {
|
||||
KinesisStreamingForwarder kinesisForwarder,
|
||||
S3Service s3Service,
|
||||
ObjectMapper objectMapper) {
|
||||
this(tableStore, itemStore, exportStore, importStore, regionResolver, streamService,
|
||||
kinesisForwarder, s3Service, objectMapper, 0, 0);
|
||||
}
|
||||
|
||||
DynamoDbService(StorageBackend<String, TableDefinition> tableStore,
|
||||
StorageBackend<String, Map<String, JsonNode>> itemStore,
|
||||
StorageBackend<String, ExportDescription> exportStore,
|
||||
StorageBackend<String, ImportTableDescription> importStore,
|
||||
RegionResolver regionResolver,
|
||||
DynamoDbStreamService streamService,
|
||||
KinesisStreamingForwarder kinesisForwarder,
|
||||
S3Service s3Service,
|
||||
ObjectMapper objectMapper,
|
||||
int vectorIndexAllocationSeconds,
|
||||
int vectorIndexBackfillSeconds) {
|
||||
this.tableStore = tableStore;
|
||||
this.itemStore = itemStore;
|
||||
this.exportStore = exportStore;
|
||||
@@ -181,6 +223,8 @@ public class DynamoDbService implements ResourceProvider {
|
||||
this.kinesisForwarder = kinesisForwarder;
|
||||
this.s3Service = s3Service;
|
||||
this.objectMapper = objectMapper != null ? objectMapper : new ObjectMapper();
|
||||
this.vectorIndexAllocationSeconds = vectorIndexAllocationSeconds;
|
||||
this.vectorIndexBackfillSeconds = vectorIndexBackfillSeconds;
|
||||
loadPersistedItems();
|
||||
recoverInterruptedJobs();
|
||||
}
|
||||
@@ -261,6 +305,19 @@ public class DynamoDbService implements ResourceProvider {
|
||||
List<GlobalSecondaryIndex> gsis,
|
||||
List<LocalSecondaryIndex> lsis,
|
||||
String region) {
|
||||
return createTable(tableName, keySchema, attributeDefinitions, readCapacity, writeCapacity,
|
||||
gsis, lsis, List.of(), null, region);
|
||||
}
|
||||
|
||||
public TableDefinition createTable(String tableName,
|
||||
List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
Long readCapacity, Long writeCapacity,
|
||||
List<GlobalSecondaryIndex> gsis,
|
||||
List<LocalSecondaryIndex> lsis,
|
||||
List<VectorIndexCreate> vectorIndexes,
|
||||
String billingMode,
|
||||
String region) {
|
||||
// Enforce at the service boundary: CreateTable persists its input as the
|
||||
// canonical table name and derives TableArn from it. An ARN-form input
|
||||
// would produce ARN-on-ARN TableArn values. Handler-layer rejection alone
|
||||
@@ -320,6 +377,10 @@ public class DynamoDbService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
List<VectorIndexCreate> vectorIndexCreates = vectorIndexes != null ? vectorIndexes : List.of();
|
||||
validateVectorIndexMembers(vectorIndexCreates);
|
||||
validateVectorIndexes(vectorIndexCreates, List.of(), attributeDefinitions, billingMode);
|
||||
|
||||
Set<String> referencedAttrs = new HashSet<>();
|
||||
keySchema.forEach(k -> referencedAttrs.add(k.getAttributeName()));
|
||||
if (gsis != null) {
|
||||
@@ -328,6 +389,9 @@ public class DynamoDbService implements ResourceProvider {
|
||||
if (lsis != null) {
|
||||
lsis.forEach(l -> l.getKeySchema().forEach(k -> referencedAttrs.add(k.getAttributeName())));
|
||||
}
|
||||
// A SearchSchema attribute counts as used, so the unused-definition rejection below does
|
||||
// not fire for one that only a vector index reads.
|
||||
vectorIndexCreates.forEach(v -> referencedAttrs.addAll(v.index().getSearchSchemaAttributeNames()));
|
||||
Set<String> definedAttrs = attributeDefinitions == null
|
||||
? Set.of()
|
||||
: attributeDefinitions.stream()
|
||||
@@ -372,6 +436,13 @@ public class DynamoDbService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (VectorIndexCreate create : vectorIndexCreates) {
|
||||
if (!indexNames.add(create.index().getIndexName())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Duplicate index name: "
|
||||
+ create.index().getIndexName(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
TableDefinition table = new TableDefinition(tableName, keySchema, attributeDefinitions,
|
||||
region, regionResolver.getAccountId());
|
||||
@@ -407,6 +478,19 @@ public class DynamoDbService implements ResourceProvider {
|
||||
table.setLocalSecondaryIndexes(new ArrayList<>(lsis));
|
||||
}
|
||||
|
||||
// A new VectorIndex is already ACTIVE with no creation timestamp, which is what AWS
|
||||
// reports for one created with the table: Backfilling is never reported for it, and
|
||||
// only the UpdateTable path runs the two timed phases.
|
||||
if (!vectorIndexCreates.isEmpty()) {
|
||||
List<VectorIndex> created = new ArrayList<>();
|
||||
for (VectorIndexCreate create : vectorIndexCreates) {
|
||||
VectorIndex vectorIndex = create.index();
|
||||
vectorIndex.setIndexArn(table.getTableArn() + "/index/" + vectorIndex.getIndexName());
|
||||
created.add(vectorIndex);
|
||||
}
|
||||
table.setVectorIndexes(created);
|
||||
}
|
||||
|
||||
tableStore.put(storageKey, table);
|
||||
itemsByTable.put(scopedItemsKey(storageKey), new ConcurrentSkipListMap<>());
|
||||
LOG.infov("Created table: {0} in region {1}", tableName, region);
|
||||
@@ -430,11 +514,128 @@ public class DynamoDbService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates each vector index a request adds against its own request model, the
|
||||
* "N validation errors detected" family. AWS answers these before every other check on the
|
||||
* request, including the online index limit an UpdateTable is held to.
|
||||
*
|
||||
* @param newIndexes the indexes the request adds, each with its request-model member path
|
||||
*/
|
||||
private static void validateVectorIndexMembers(List<VectorIndexCreate> newIndexes) {
|
||||
// The required members are reported before the length and range constraints.
|
||||
for (VectorIndexCreate create : newIndexes) {
|
||||
VectorIndex index = create.index();
|
||||
String memberPath = create.memberPath();
|
||||
requireVectorIndexMember(index.getDimensions(), memberPath + ".dimensions");
|
||||
requireVectorIndexMember(index.getVectorAttributeName(), memberPath + ".vectorAttribute");
|
||||
requireVectorIndexMember(index.getProjectionType(), memberPath + ".projection");
|
||||
requireVectorIndexMember(index.getDistanceFunction(), memberPath + ".distanceFunction");
|
||||
String indexName = index.getIndexName();
|
||||
if (indexName == null || indexName.length() < MIN_VECTOR_INDEX_NAME_LENGTH) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + indexName + "' at '"
|
||||
+ memberPath + ".indexName' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to " + MIN_VECTOR_INDEX_NAME_LENGTH, 400);
|
||||
}
|
||||
String distanceFunction = index.getDistanceFunction();
|
||||
if (!VECTOR_DISTANCE_FUNCTIONS.contains(distanceFunction)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + distanceFunction + "' at '"
|
||||
+ memberPath + ".distanceFunction' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: " + VECTOR_DISTANCE_FUNCTIONS, 400);
|
||||
}
|
||||
Long dimensions = index.getDimensions();
|
||||
if (dimensions < 1) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + dimensions + "' at '"
|
||||
+ memberPath + ".dimensions' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to 1", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the vector indexes a request adds against the table they join, the
|
||||
* "One or more parameter values were invalid" family. Runs after
|
||||
* {@link #validateVectorIndexMembers}, so every index here carries its required members.
|
||||
*
|
||||
* @param newIndexes the indexes the request adds
|
||||
* @param existingIndexes the indexes already on the table, empty on CreateTable
|
||||
* @param attributeDefinitions every definition a SearchSchema element may resolve against
|
||||
* @param billingMode the billing mode the table will have, null when the request
|
||||
* leaves it at the PROVISIONED default
|
||||
*/
|
||||
private static void validateVectorIndexes(List<VectorIndexCreate> newIndexes,
|
||||
List<VectorIndex> existingIndexes,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
String billingMode) {
|
||||
if (newIndexes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingIndexes.size() + newIndexes.size() > MAX_VECTOR_INDEXES_PER_TABLE) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: VectorIndex count exceeds "
|
||||
+ "the per-table limit of " + MAX_VECTOR_INDEXES_PER_TABLE, 400);
|
||||
}
|
||||
|
||||
if (!"PAY_PER_REQUEST".equals(billingMode)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Vector indexes are only supported "
|
||||
+ "for PAY_PER_REQUEST tables", 400);
|
||||
}
|
||||
|
||||
Set<String> definedAttrs = attributeDefinitions == null
|
||||
? Set.of()
|
||||
: attributeDefinitions.stream()
|
||||
.map(AttributeDefinition::getAttributeName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<String, Long> dimensionsByVectorAttribute = new HashMap<>();
|
||||
for (VectorIndex existing : existingIndexes) {
|
||||
dimensionsByVectorAttribute.put(existing.getVectorAttributeName(), existing.getDimensions());
|
||||
}
|
||||
|
||||
for (VectorIndexCreate create : newIndexes) {
|
||||
VectorIndex index = create.index();
|
||||
Long dimensions = index.getDimensions();
|
||||
if (dimensions > MAX_VECTOR_DIMENSIONS) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Number of dimensions must be "
|
||||
+ "between 1 and " + MAX_VECTOR_DIMENSIONS + " inclusive.", 400);
|
||||
}
|
||||
for (String searchSchemaAttr : index.getSearchSchemaAttributeNames()) {
|
||||
if (!definedAttrs.contains(searchSchemaAttr)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: One element in SearchSchema "
|
||||
+ "is not defined in attribute definitions", 400);
|
||||
}
|
||||
}
|
||||
String vectorAttribute = index.getVectorAttributeName();
|
||||
Long seen = dimensionsByVectorAttribute.putIfAbsent(vectorAttribute, dimensions);
|
||||
if (seen != null && !seen.equals(dimensions)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Conflicting attribute definition "
|
||||
+ "for '" + vectorAttribute + "'. All VectorIndexes on the same vector "
|
||||
+ "attribute must use the same dimensions.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireVectorIndexMember(Object value, String memberPath) {
|
||||
if (value == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value null at '" + memberPath
|
||||
+ "' failed to satisfy constraint: Member must not be null", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public TableDefinition describeTable(String tableName, String region) {
|
||||
String canonicalTableName = canonicalTableName(region, tableName);
|
||||
String storageKey = regionKey(region, canonicalTableName);
|
||||
TableDefinition table = tableStore.get(storageKey)
|
||||
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
|
||||
settleVectorIndexes(storageKey, table);
|
||||
|
||||
// Update dynamic counts
|
||||
var items = itemsByTable.get(scopedItemsKey(storageKey));
|
||||
@@ -444,6 +645,96 @@ public class DynamoDbService implements ResourceProvider {
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances a vector index added by UpdateTable through its two phases on read, the way
|
||||
* {@code AcmService} settles a pending certificate. Nothing else moves the index along, so
|
||||
* a caller polling DescribeTable is what makes it progress.
|
||||
*
|
||||
* <p>The table leaves UPDATING at the allocation/backfill boundary, together with the switch
|
||||
* from {@code Backfilling: false} to {@code Backfilling: true}, which is what AWS reports.
|
||||
*/
|
||||
private void settleVectorIndexes(String storageKey, TableDefinition table) {
|
||||
List<VectorIndex> indexes = table.getVectorIndexes();
|
||||
if (indexes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
boolean changed = false;
|
||||
boolean anySettling = false;
|
||||
boolean anyAllocating = false;
|
||||
for (VectorIndex index : indexes) {
|
||||
if (index.getCreationStartedAt() == null || !"CREATING".equals(index.getIndexStatus())) {
|
||||
continue;
|
||||
}
|
||||
anySettling = true;
|
||||
Instant backfillStart = index.getCreationStartedAt().plusSeconds(vectorIndexAllocationSeconds);
|
||||
Instant activeAt = backfillStart.plusSeconds(vectorIndexBackfillSeconds);
|
||||
if (!now.isBefore(activeAt)) {
|
||||
index.setIndexStatus("ACTIVE");
|
||||
index.setCreationStartedAt(null);
|
||||
changed = true;
|
||||
} else if (now.isBefore(backfillStart)) {
|
||||
anyAllocating = true;
|
||||
}
|
||||
}
|
||||
// Only a table this method is driving may leave UPDATING here: another caller's
|
||||
// UPDATING is not this method's to clear.
|
||||
if (anySettling && !anyAllocating && "UPDATING".equals(table.getTableStatus())) {
|
||||
table.setTableStatus("ACTIVE");
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
tableStore.put(storageKey, table);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the index is past resource allocation and still building, which is the only state
|
||||
* where AWS reports {@code Backfilling} at all. A settle must have run first.
|
||||
*/
|
||||
public boolean isVectorIndexBackfilling(VectorIndex index) {
|
||||
return reportsVectorIndexBackfilling(index) && !Instant.now().isBefore(
|
||||
index.getCreationStartedAt().plusSeconds(vectorIndexAllocationSeconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code Backfilling} is reported for this index at all. A vector index created with
|
||||
* the table never reports it; one added by UpdateTable does until it reaches ACTIVE.
|
||||
*/
|
||||
public boolean reportsVectorIndexBackfilling(VectorIndex index) {
|
||||
return index.getCreationStartedAt() != null && "CREATING".equals(index.getIndexStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* The table a SearchVectors runs against, with its vector indexes settled. Skips the
|
||||
* {@link #describeTable} item-count refresh, which is {@code O(items)} and which the
|
||||
* SearchVectors response never reports.
|
||||
*/
|
||||
public TableDefinition settledTable(String tableName, String region) {
|
||||
String canonicalTableName = canonicalTableName(region, tableName);
|
||||
String storageKey = regionKey(region, canonicalTableName);
|
||||
TableDefinition table = tableStore.get(storageKey)
|
||||
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
|
||||
settleVectorIndexes(storageKey, table);
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every live item of the table, expired ones dropped. SearchVectors reads the whole table:
|
||||
* it has no page boundary and no cursor, so it cannot go through {@link #scan}, which stops
|
||||
* at the 1 MB response cap.
|
||||
*/
|
||||
public List<JsonNode> liveItems(TableDefinition table, String region) {
|
||||
String storageKey = regionKey(region, table.getTableName());
|
||||
ConcurrentSkipListMap<String, JsonNode> items = itemsByTable.get(scopedItemsKey(storageKey));
|
||||
if (items == null) {
|
||||
return List.of();
|
||||
}
|
||||
return items.values().stream()
|
||||
.filter(item -> !isExpired(item, table))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored table definition without the {@link #describeTable} item-count refresh,
|
||||
* which is {@code O(items)} on the item map. For callers that only need static metadata
|
||||
@@ -518,6 +809,12 @@ public class DynamoDbService implements ResourceProvider {
|
||||
var table = tableStore.get(storageKey)
|
||||
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
|
||||
requireNotCreating(table);
|
||||
settleVectorIndexes(storageKey, table);
|
||||
if (table.getVectorIndexes().stream().anyMatch(v -> "CREATING".equals(v.getIndexStatus()))) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Attempt to change a resource which is still in use: Cannot delete table while "
|
||||
+ "indexes are being created, updated, or deleted.", 400);
|
||||
}
|
||||
tableStore.delete(storageKey);
|
||||
itemsByTable.remove(scopedItemsKey(storageKey));
|
||||
itemLocks.remove(scopedItemsKey(storageKey));
|
||||
@@ -1931,11 +2228,21 @@ public class DynamoDbService implements ResourceProvider {
|
||||
public TableDefinition updateTable(String tableName, Long readCapacity, Long writeCapacity,
|
||||
List<GlobalSecondaryIndex> gsiCreates, List<String> gsiDeletes,
|
||||
List<AttributeDefinition> newAttrDefs, String region) {
|
||||
return updateTable(tableName, readCapacity, writeCapacity, gsiCreates, gsiDeletes,
|
||||
newAttrDefs, List.of(), List.of(), null, region);
|
||||
}
|
||||
|
||||
public TableDefinition updateTable(String tableName, Long readCapacity, Long writeCapacity,
|
||||
List<GlobalSecondaryIndex> gsiCreates, List<String> gsiDeletes,
|
||||
List<AttributeDefinition> newAttrDefs,
|
||||
List<VectorIndexCreate> vectorCreates, List<String> vectorDeletes,
|
||||
String billingMode, String region) {
|
||||
String canonicalTableName = canonicalTableName(region, tableName);
|
||||
String storageKey = regionKey(region, canonicalTableName);
|
||||
TableDefinition table = tableStore.get(storageKey)
|
||||
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
|
||||
requireNotCreating(table);
|
||||
settleVectorIndexes(storageKey, table);
|
||||
|
||||
if (readCapacity != null && readCapacity <= 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
@@ -1985,6 +2292,15 @@ public class DynamoDbService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
List<VectorIndexCreate> vectorIndexCreates = vectorCreates != null ? vectorCreates : List.of();
|
||||
List<String> vectorIndexDeletes = vectorDeletes != null ? vectorDeletes : List.of();
|
||||
List<AttributeDefinition> knownAttrDefs = new ArrayList<>(table.getAttributeDefinitions());
|
||||
if (newAttrDefs != null) {
|
||||
knownAttrDefs.addAll(newAttrDefs);
|
||||
}
|
||||
validateVectorIndexUpdates(table, vectorIndexCreates, vectorIndexDeletes, knownAttrDefs,
|
||||
billingMode != null ? billingMode : table.getBillingMode());
|
||||
|
||||
if (readCapacity != null) {
|
||||
table.getProvisionedThroughput().setReadCapacityUnits(readCapacity);
|
||||
}
|
||||
@@ -2001,6 +2317,21 @@ public class DynamoDbService implements ResourceProvider {
|
||||
table.getGlobalSecondaryIndexes().add(gsi);
|
||||
}
|
||||
|
||||
for (String indexName : vectorIndexDeletes) {
|
||||
table.getVectorIndexes().removeIf(v -> indexName.equals(v.getIndexName()));
|
||||
}
|
||||
|
||||
for (VectorIndexCreate create : vectorIndexCreates) {
|
||||
VectorIndex vectorIndex = create.index();
|
||||
vectorIndex.setIndexArn(table.getTableArn() + "/index/" + vectorIndex.getIndexName());
|
||||
vectorIndex.setIndexStatus("CREATING");
|
||||
vectorIndex.setCreationStartedAt(Instant.now());
|
||||
table.getVectorIndexes().add(vectorIndex);
|
||||
}
|
||||
if (!vectorIndexCreates.isEmpty()) {
|
||||
table.setTableStatus("UPDATING");
|
||||
}
|
||||
|
||||
if (newAttrDefs != null && !newAttrDefs.isEmpty()) {
|
||||
List<AttributeDefinition> existing = table.getAttributeDefinitions();
|
||||
for (AttributeDefinition newDef : newAttrDefs) {
|
||||
@@ -2018,6 +2349,69 @@ public class DynamoDbService implements ResourceProvider {
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the {@code VectorIndexUpdates} of an UpdateTable request against the table's
|
||||
* current lifecycle state.
|
||||
*
|
||||
* <p>AWS allows one online index operation per table at a time. That limit binds the table,
|
||||
* not the request, so two creates in one request and a create issued while an earlier index
|
||||
* still builds are refused the same way. Deleting an index that is still in its resource
|
||||
* allocation phase is refused with a different error, and the same delete is accepted once
|
||||
* the index reaches backfilling.
|
||||
*/
|
||||
private void validateVectorIndexUpdates(TableDefinition table, List<VectorIndexCreate> creates,
|
||||
List<String> deletes,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
String billingMode) {
|
||||
validateVectorIndexMembers(creates);
|
||||
// A table that holds a vector index may not leave PAY_PER_REQUEST, whether or not the
|
||||
// request touches its indexes.
|
||||
if (!table.getVectorIndexes().isEmpty() && !"PAY_PER_REQUEST".equals(billingMode)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Vector indexes are only supported "
|
||||
+ "for PAY_PER_REQUEST tables", 400);
|
||||
}
|
||||
if (creates.isEmpty() && deletes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (VectorIndexCreate create : creates) {
|
||||
if (table.findVectorIndex(create.index().getIndexName()).isPresent()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid: Duplicate index name: "
|
||||
+ create.index().getIndexName(), 400);
|
||||
}
|
||||
}
|
||||
int deletesOfBuildingIndexes = 0;
|
||||
for (String indexName : deletes) {
|
||||
VectorIndex target = table.findVectorIndex(indexName)
|
||||
.orElseThrow(() -> new AwsException("ValidationException",
|
||||
"The table does not have the specified index: " + indexName, 400));
|
||||
if (!"CREATING".equals(target.getIndexStatus())) {
|
||||
continue;
|
||||
}
|
||||
if (!isVectorIndexBackfilling(target)) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Attempt to change a resource which is still in use: Index creation is in "
|
||||
+ "resource allocation phase. Retry deletion during backfilling phase or "
|
||||
+ "when the index is active. Table: " + table.getTableName()
|
||||
+ " Index: " + indexName, 400);
|
||||
}
|
||||
deletesOfBuildingIndexes++;
|
||||
}
|
||||
long building = table.getVectorIndexes().stream()
|
||||
.filter(v -> "CREATING".equals(v.getIndexStatus()))
|
||||
.count();
|
||||
// Deleting an index that is still backfilling takes over the slot that index already
|
||||
// holds, so it does not need one of its own.
|
||||
long onlineOperations = building + creates.size() + deletes.size() - deletesOfBuildingIndexes;
|
||||
if (onlineOperations > 1) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"Subscriber limit exceeded: Only 1 online index can be created or deleted "
|
||||
+ "simultaneously per table", 400);
|
||||
}
|
||||
validateVectorIndexes(creates, table.getVectorIndexes(), attributeDefinitions, billingMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateTable keeps only the attribute definitions a key schema still uses. A definition sent
|
||||
* with the request but used by no key is dropped in the same response, and deleting an index
|
||||
@@ -2039,6 +2433,9 @@ public class DynamoDbService implements ResourceProvider {
|
||||
used.add(k.getAttributeName());
|
||||
}
|
||||
}
|
||||
for (VectorIndex vectorIndex : table.getVectorIndexes()) {
|
||||
used.addAll(vectorIndex.getSearchSchemaAttributeNames());
|
||||
}
|
||||
List<AttributeDefinition> kept = table.getAttributeDefinitions().stream()
|
||||
.filter(ad -> used.contains(ad.getAttributeName()))
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
@@ -3609,6 +4006,57 @@ public class DynamoDbService implements ResourceProvider {
|
||||
validateIndexKeySchema(table, item, lsi.getIndexName(), lsi.getKeySchema(), isUpdate);
|
||||
}
|
||||
}
|
||||
for (VectorIndex vectorIndex : table.getVectorIndexes()) {
|
||||
validateVectorIndexWrite(table, item, vectorIndex, isUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
// A vector index constrains the shape of the vector attribute and, through its search
|
||||
// schema, the HASH attribute it partitions on. An item carrying neither is written and
|
||||
// left out of the index; one carrying a vector of the wrong shape is refused.
|
||||
private void validateVectorIndexWrite(TableDefinition table, JsonNode item,
|
||||
VectorIndex index, boolean isUpdate) {
|
||||
JsonNode vector = item.get(index.getVectorAttributeName());
|
||||
if (vector != null) {
|
||||
validateVectorAttribute(vector, index);
|
||||
}
|
||||
String hashAttribute = index.getHashAttributeName();
|
||||
if (hashAttribute != null) {
|
||||
validateIndexKeySchema(table, item, index.getIndexName(),
|
||||
List.of(new KeySchemaElement(hashAttribute, "HASH")), isUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
// AWS punctuates these three inconsistently, which is reproduced here character for
|
||||
// character: "Actual: S." carries a period and "Actual: 2" and "list" do not.
|
||||
private void validateVectorAttribute(JsonNode vector, VectorIndex index) {
|
||||
String attributeName = index.getVectorAttributeName();
|
||||
String indexName = index.getIndexName();
|
||||
validateAttributeValueShape(vector);
|
||||
JsonNode components = vector.get("L");
|
||||
if (components == null || !components.isArray()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid. Invalid type for parameter "
|
||||
+ attributeName + ", Expected: 32-bit floating point number list IndexName: "
|
||||
+ indexName, 400);
|
||||
}
|
||||
Long dimensions = index.getDimensions();
|
||||
if (components.size() != dimensions) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid. Invalid size for parameter "
|
||||
+ attributeName + ", Expected: " + dimensions
|
||||
+ ", Actual: " + components.size() + " IndexName: " + indexName, 400);
|
||||
}
|
||||
for (int i = 0; i < components.size(); i++) {
|
||||
JsonNode component = components.get(i);
|
||||
validateAttributeValueShape(component);
|
||||
if (!component.has("N")) {
|
||||
throw new AwsException("ValidationException",
|
||||
"One or more parameter values were invalid. Invalid type for parameter "
|
||||
+ attributeName + "[" + i + "], Expected: 32-bit floating point number, "
|
||||
+ "Actual: " + component.fieldNames().next() + ". IndexName: " + indexName, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateIndexKeySchema(TableDefinition table, JsonNode item,
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ final class DynamoDbTransactCapacity {
|
||||
|
||||
static DynamoDbWriteCapacity.Cost write(TableDefinition table, JsonNode oldItem, JsonNode newItem) {
|
||||
DynamoDbWriteCapacity.Cost cost = DynamoDbWriteCapacity.forWrite(table, oldItem, newItem);
|
||||
return new DynamoDbWriteCapacity.Cost(cost.table() * 2, cost.gsi(), cost.lsi());
|
||||
return cost.withTable(cost.table() * 2);
|
||||
}
|
||||
|
||||
static DynamoDbWriteCapacity.Cost conditionCheck(JsonNode item) {
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* The numeric core of SearchVectors: the three distance functions and the f32 rendering of a
|
||||
* stored vector.
|
||||
*
|
||||
* <p>AWS computes a score entirely in 32-bit floating point and sums the per-dimension terms with
|
||||
* a pairwise binary-tree reduction. Measured on real DynamoDB in eu-west-2 (2026-09-23): the dot
|
||||
* product of {@code [16777216,1,1,1,1,1,1,1]} with eight ones answers 16777222, and the same
|
||||
* shape at sixteen dimensions answers 16777230. A double accumulator answers 16777224 and
|
||||
* 16777232, a sequential f32 loop answers 16777216 twice, and a four-lane reduction answers
|
||||
* 16777222 and 16777228, so only the tree reproduces both.
|
||||
*/
|
||||
final class DynamoDbVectorScoring {
|
||||
|
||||
// The band AWS writes in plain notation. Outside it the value comes back in scientific form.
|
||||
private static final BigDecimal PLAIN_LOWER_BOUND = new BigDecimal("0.000001");
|
||||
private static final BigDecimal PLAIN_UPPER_BOUND = new BigDecimal("1E+13");
|
||||
|
||||
static final String COSINE = "COSINE";
|
||||
static final String EUCLIDEAN = "EUCLIDEAN";
|
||||
static final String DOT_PRODUCT = "DOT_PRODUCT";
|
||||
|
||||
private DynamoDbVectorScoring() {}
|
||||
|
||||
/**
|
||||
* Scores every candidate of one search against a fixed query vector.
|
||||
*
|
||||
* <p>Everything that depends only on the query is computed once here, and the per-dimension
|
||||
* terms the tree sum consumes are written into a single buffer the scorer owns. A search
|
||||
* scores its candidates one at a time, so that buffer needs no synchronization.
|
||||
*/
|
||||
static final class Scorer {
|
||||
|
||||
private final String distanceFunction;
|
||||
private final float[] query;
|
||||
private final float[] terms;
|
||||
private final double queryNorm;
|
||||
|
||||
Scorer(String distanceFunction, float[] query) {
|
||||
this.distanceFunction = distanceFunction;
|
||||
this.query = query;
|
||||
this.terms = new float[query.length];
|
||||
this.queryNorm = COSINE.equals(distanceFunction) ? Math.sqrt(selfDot(query, terms)) : 0.0;
|
||||
}
|
||||
|
||||
/** The score of one stored vector against the query vector, widened for JSON. */
|
||||
double score(float[] stored) {
|
||||
return switch (distanceFunction) {
|
||||
case COSINE -> cosine(stored);
|
||||
case EUCLIDEAN -> euclidean(stored);
|
||||
case DOT_PRODUCT -> dotProduct(query, stored, terms);
|
||||
// CreateTable and UpdateTable reject an unknown value, so only a missing one
|
||||
// reaches here: answer it rather than letting a null selector throw.
|
||||
case null, default -> throw new AwsException("ValidationException",
|
||||
"Unsupported distance function: " + distanceFunction, 400);
|
||||
};
|
||||
}
|
||||
|
||||
private float cosine(float[] stored) {
|
||||
float dot = dotProduct(query, stored, terms);
|
||||
double denominator = queryNorm * Math.sqrt(selfDot(stored, terms));
|
||||
if (denominator == 0.0) {
|
||||
// A zero vector has no direction. Scoring it 1 keeps the response valid JSON,
|
||||
// which the NaN of a 0/0 division would not.
|
||||
return 1.0f;
|
||||
}
|
||||
return (float) (1.0 - dot / denominator);
|
||||
}
|
||||
|
||||
private float euclidean(float[] stored) {
|
||||
for (int i = 0; i < query.length; i++) {
|
||||
float difference = query[i] - stored[i];
|
||||
terms[i] = difference * difference;
|
||||
}
|
||||
return (float) Math.sqrt(treeSum(terms));
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the higher score is the closer match, which only DOT_PRODUCT reports. */
|
||||
static boolean higherIsCloser(String distanceFunction) {
|
||||
return DOT_PRODUCT.equals(distanceFunction);
|
||||
}
|
||||
|
||||
private static float dotProduct(float[] query, float[] stored, float[] terms) {
|
||||
for (int i = 0; i < query.length; i++) {
|
||||
terms[i] = query[i] * stored[i];
|
||||
}
|
||||
return treeSum(terms);
|
||||
}
|
||||
|
||||
private static float selfDot(float[] vector, float[] terms) {
|
||||
return dotProduct(vector, vector, terms);
|
||||
}
|
||||
|
||||
/** Sums the terms by repeated pairwise halving, all arithmetic in float. Mutates {@code terms}. */
|
||||
private static float treeSum(float[] terms) {
|
||||
int n = terms.length;
|
||||
while (n > 1) {
|
||||
int half = (n + 1) / 2;
|
||||
for (int i = 0; i + 1 < n; i += 2) {
|
||||
terms[i / 2] = terms[i] + terms[i + 1];
|
||||
}
|
||||
if ((n & 1) == 1) {
|
||||
terms[half - 1] = terms[n - 1];
|
||||
}
|
||||
n = half;
|
||||
}
|
||||
return n == 0 ? 0f : terms[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored f32 value as AWS writes it back: the shortest decimal naming that float. Plain
|
||||
* notation with at least one fractional digit inside {@code [1e-6, 1e13)}, and
|
||||
* {@code <mantissa>e<exponent>} outside it, with a lowercase e, no plus and no zero padding.
|
||||
*
|
||||
* <p>Both boundaries were measured on real DynamoDB (eu-west-2, 2026-09-23): 9.9e-7 comes back
|
||||
* scientific and 1e-6 plain, 9e12 comes back plain and 1e13 scientific. 1 comes back as
|
||||
* {@code 1.0} and 16777217 as {@code 16777216.0}.
|
||||
*
|
||||
* <p>{@code Float.toString} supplies the shortest round-tripping decimal, which it is for every
|
||||
* normal float. Subnormals below {@link Float#MIN_NORMAL} are the one exception: AWS writes
|
||||
* {@code Float.MIN_VALUE} as {@code 1e-45} where this renders {@code 1.4e-45}.
|
||||
*/
|
||||
static String render(float value) {
|
||||
if (value == 0f) {
|
||||
return "0.0";
|
||||
}
|
||||
BigDecimal shortest = new BigDecimal(Float.toString(value)).stripTrailingZeros();
|
||||
BigDecimal magnitude = shortest.abs();
|
||||
if (magnitude.compareTo(PLAIN_LOWER_BOUND) >= 0 && magnitude.compareTo(PLAIN_UPPER_BOUND) < 0) {
|
||||
String plain = shortest.toPlainString();
|
||||
return plain.indexOf('.') < 0 ? plain + ".0" : plain;
|
||||
}
|
||||
return scientific(shortest);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mantissa carries the shortest digits with no trailing {@code .0}, so 1e13 is written
|
||||
* {@code 1e13} rather than {@code 1.0e13}.
|
||||
*/
|
||||
private static String scientific(BigDecimal stripped) {
|
||||
String digits = stripped.unscaledValue().abs().toString();
|
||||
int exponent = digits.length() - 1 - stripped.scale();
|
||||
StringBuilder out = new StringBuilder();
|
||||
if (stripped.signum() < 0) {
|
||||
out.append('-');
|
||||
}
|
||||
out.append(digits.charAt(0));
|
||||
if (digits.length() > 1) {
|
||||
out.append('.').append(digits, 1, digits.length());
|
||||
}
|
||||
return out.append('e').append(exponent).toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The read path of a vector index: SearchConditionExpression validation, candidate filtering,
|
||||
* scoring, top-K and result projection.
|
||||
*
|
||||
* <p>No vector index is materialized, the way no secondary index is materialized anywhere else in
|
||||
* Floci. A search reads the table's items and drops the ones the index does not hold.
|
||||
*/
|
||||
final class DynamoDbVectorSearch {
|
||||
|
||||
private DynamoDbVectorSearch() {}
|
||||
|
||||
/** One search result: the projected item and its distance score. */
|
||||
record Hit(ObjectNode item, double score) {}
|
||||
|
||||
/** A scored candidate, before the top-K cut decides whether it is worth projecting. */
|
||||
private record Candidate(JsonNode item, double score) {}
|
||||
|
||||
static List<Hit> search(TableDefinition table, VectorIndex index, List<JsonNode> items,
|
||||
JsonNode searchVector, int topK, String searchConditionExpression,
|
||||
JsonNode exprAttrNames, JsonNode exprAttrValues,
|
||||
String projectionExpression) {
|
||||
float[] query = parseSearchVector(searchVector, index);
|
||||
ExpressionEvaluator.Expr condition = parseSearchCondition(index, searchConditionExpression,
|
||||
exprAttrNames, exprAttrValues);
|
||||
ProjectionEvaluator.validateExpression(projectionExpression);
|
||||
|
||||
String hashAttribute = index.getHashAttributeName();
|
||||
String distanceFunction = index.getDistanceFunction();
|
||||
DynamoDbVectorScoring.Scorer scorer =
|
||||
new DynamoDbVectorScoring.Scorer(distanceFunction, query);
|
||||
List<Candidate> candidates = new ArrayList<>();
|
||||
for (JsonNode item : items) {
|
||||
if (hashAttribute != null && !item.hasNonNull(hashAttribute)) {
|
||||
continue;
|
||||
}
|
||||
if (!ExpressionEvaluator.evaluate(condition, item, exprAttrNames, exprAttrValues)) {
|
||||
continue;
|
||||
}
|
||||
float[] stored = storedVector(item, index);
|
||||
if (stored == null) {
|
||||
continue;
|
||||
}
|
||||
candidates.add(new Candidate(item, scorer.score(stored)));
|
||||
}
|
||||
|
||||
Comparator<Candidate> byScore = Comparator.comparingDouble(Candidate::score);
|
||||
candidates.sort(DynamoDbVectorScoring.higherIsCloser(distanceFunction)
|
||||
? byScore.reversed() : byScore);
|
||||
|
||||
List<Hit> hits = new ArrayList<>();
|
||||
List<Candidate> top = candidates.subList(0, Math.min(topK, candidates.size()));
|
||||
if (top.isEmpty()) {
|
||||
return hits;
|
||||
}
|
||||
Set<String> projectedAttributes = projectedAttributeNames(table, index);
|
||||
boolean rendersVector = projectionExpression != null && !projectionExpression.isBlank()
|
||||
&& ProjectionEvaluator.topLevelAttributes(projectionExpression, exprAttrNames)
|
||||
.contains(index.getVectorAttributeName());
|
||||
for (Candidate candidate : top) {
|
||||
hits.add(new Hit(projectHit(candidate.item(), index, projectedAttributes,
|
||||
projectionExpression, exprAttrNames, rendersVector), candidate.score()));
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
// ── Search vector ──
|
||||
|
||||
private static float[] parseSearchVector(JsonNode searchVector, VectorIndex index) {
|
||||
float[] query = searchVector != null && searchVector.isArray()
|
||||
? toVector(searchVector)
|
||||
: new float[0];
|
||||
if (query == null) {
|
||||
throw invalidSearchVector();
|
||||
}
|
||||
long dimensions = index.getDimensions();
|
||||
if (query.length != dimensions) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Input search vector dimension " + query.length
|
||||
+ " does not match vector index dimension " + dimensions, 400);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private static AwsException invalidSearchVector() {
|
||||
return new AwsException("ValidationException",
|
||||
"Search vector contains invalid values. All values in the search vector must be a "
|
||||
+ "32-bit floating-point number attribute", 400);
|
||||
}
|
||||
|
||||
// ── SearchConditionExpression ──
|
||||
|
||||
/**
|
||||
* Parses and validates the condition, returning null when there is none.
|
||||
*
|
||||
* <p>Only equality is supported, on HASH and INLINE_FILTER elements alike. The comparator is
|
||||
* checked on every clause before any membership check, because AWS answers {@code tenant < :t}
|
||||
* on an index that declares {@code tenant} with the comparator message and {@code tenant = :t}
|
||||
* on an index with no SearchSchema with the membership one.
|
||||
*/
|
||||
private static ExpressionEvaluator.Expr parseSearchCondition(VectorIndex index, String expression,
|
||||
JsonNode exprAttrNames,
|
||||
JsonNode exprAttrValues) {
|
||||
String hashAttribute = index.getHashAttributeName();
|
||||
if (expression == null || expression.isBlank()) {
|
||||
if (hashAttribute != null) {
|
||||
throw missingHashCondition();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
ExpressionEvaluator.validateExpression(expression, "SearchConditionExpression",
|
||||
exprAttrNames, exprAttrValues);
|
||||
|
||||
ExpressionEvaluator.Expr condition = ExpressionEvaluator.parse(expression);
|
||||
List<ExpressionEvaluator.CompareExpr> clauses = new ArrayList<>();
|
||||
collectClauses(condition, clauses);
|
||||
for (ExpressionEvaluator.CompareExpr clause : clauses) {
|
||||
if (clause.op() != ExpressionEvaluator.TokenType.EQ) {
|
||||
throw invalidComparator();
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> schemaAttributes = new HashSet<>(index.getSearchSchemaAttributeNames());
|
||||
boolean hashConstrained = false;
|
||||
for (ExpressionEvaluator.CompareExpr clause : clauses) {
|
||||
String attribute = conditionAttribute(clause, exprAttrNames);
|
||||
if (!schemaAttributes.contains(attribute)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SearchConditionExpression must not contain any attributes that is not in "
|
||||
+ "SearchSchema. Invalid attribute: " + attribute, 400);
|
||||
}
|
||||
hashConstrained |= attribute.equals(hashAttribute);
|
||||
}
|
||||
if (hashAttribute != null && !hashConstrained) {
|
||||
throw missingHashCondition();
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
|
||||
private static void collectClauses(ExpressionEvaluator.Expr expr,
|
||||
List<ExpressionEvaluator.CompareExpr> clauses) {
|
||||
if (expr instanceof ExpressionEvaluator.AndExpr and) {
|
||||
for (ExpressionEvaluator.Expr operand : and.operands()) {
|
||||
collectClauses(operand, clauses);
|
||||
}
|
||||
} else if (expr instanceof ExpressionEvaluator.CompareExpr compare) {
|
||||
clauses.add(compare);
|
||||
} else {
|
||||
throw invalidComparator();
|
||||
}
|
||||
}
|
||||
|
||||
/** The attribute a clause constrains, with any {@code #alias} resolved. */
|
||||
private static String conditionAttribute(ExpressionEvaluator.CompareExpr clause,
|
||||
JsonNode exprAttrNames) {
|
||||
ExpressionEvaluator.Operand operand = clause.left() instanceof ExpressionEvaluator.PathOperand
|
||||
? clause.left() : clause.right();
|
||||
if (!(operand instanceof ExpressionEvaluator.PathOperand path)) {
|
||||
throw invalidComparator();
|
||||
}
|
||||
StringBuilder name = new StringBuilder();
|
||||
for (String segment : path.segments()) {
|
||||
String resolved = segment.startsWith("#") && exprAttrNames != null
|
||||
&& exprAttrNames.hasNonNull(segment)
|
||||
? exprAttrNames.get(segment).asText() : segment;
|
||||
if (!name.isEmpty() && !resolved.startsWith("[")) {
|
||||
name.append('.');
|
||||
}
|
||||
name.append(resolved);
|
||||
}
|
||||
return name.toString();
|
||||
}
|
||||
|
||||
private static AwsException missingHashCondition() {
|
||||
return new AwsException("ValidationException",
|
||||
"SearchConditionExpression must be provided when SearchSchema has a HASH key", 400);
|
||||
}
|
||||
|
||||
private static AwsException invalidComparator() {
|
||||
return new AwsException("ValidationException",
|
||||
"Invalid SearchConditionExpression: Invalid comparator used in "
|
||||
+ "SearchConditionExpression", 400);
|
||||
}
|
||||
|
||||
// ── Candidates ──
|
||||
|
||||
/**
|
||||
* The item's vector narrowed to f32, or null when the item is not in the index at all. A
|
||||
* missing attribute, a non-list value, a member that is not a number and a length other than
|
||||
* the index dimension all leave the item out of the index rather than failing the search.
|
||||
*/
|
||||
private static float[] storedVector(JsonNode item, VectorIndex index) {
|
||||
JsonNode list = item.path(index.getVectorAttributeName()).path("L");
|
||||
if (!list.isArray() || list.size() != index.getDimensions()) {
|
||||
return null;
|
||||
}
|
||||
return toVector(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's members narrowed to f32, or null at the first member that is not a number
|
||||
* attribute. The caller decides what that means: the search vector answers an error, a
|
||||
* stored vector leaves its item out of the index.
|
||||
*/
|
||||
private static float[] toVector(JsonNode list) {
|
||||
float[] values = new float[list.size()];
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
JsonNode number = list.get(i).path("N");
|
||||
if (!number.isValueNode()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
values[i] = Float.parseFloat(number.asText());
|
||||
} catch (NumberFormatException expected) {
|
||||
// Not a number the index can hold, which the caller reports its own way.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
// ── Projection ──
|
||||
|
||||
/**
|
||||
* The attributes a hit carries. The index view is intersected with the ProjectionExpression
|
||||
* when there is one, and the vector attribute is left out unless that expression names it.
|
||||
*/
|
||||
private static ObjectNode projectHit(JsonNode item, VectorIndex index,
|
||||
Set<String> projectedAttributes,
|
||||
String projectionExpression, JsonNode exprAttrNames,
|
||||
boolean rendersVector) {
|
||||
ObjectNode view = "ALL".equals(index.getProjectionType())
|
||||
? shallowCopy((ObjectNode) item)
|
||||
: ProjectionEvaluator.trimToAttributes((ObjectNode) item, projectedAttributes);
|
||||
if (projectionExpression != null && !projectionExpression.isBlank()) {
|
||||
if (rendersVector) {
|
||||
view.set(index.getVectorAttributeName(),
|
||||
renderVector(storedVector(item, index)));
|
||||
}
|
||||
return ProjectionEvaluator.project(view, projectionExpression, exprAttrNames);
|
||||
}
|
||||
view.remove(index.getVectorAttributeName());
|
||||
return view;
|
||||
}
|
||||
|
||||
/** A copy the projection can prune without touching the stored item. Values stay shared. */
|
||||
private static ObjectNode shallowCopy(ObjectNode item) {
|
||||
ObjectNode copy = JsonNodeFactory.instance.objectNode();
|
||||
copy.setAll(item);
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static Set<String> projectedAttributeNames(TableDefinition table, VectorIndex index) {
|
||||
Set<String> projected = new HashSet<>();
|
||||
for (KeySchemaElement key : table.getKeySchema()) {
|
||||
projected.add(key.getAttributeName());
|
||||
}
|
||||
projected.addAll(index.getSearchSchemaAttributeNames());
|
||||
if ("INCLUDE".equals(index.getProjectionType())) {
|
||||
projected.addAll(index.getNonKeyAttributes());
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
/** The index's own f32 copy of the vector, which is what a search returns. */
|
||||
private static ObjectNode renderVector(float[] stored) {
|
||||
ArrayNode list = JsonNodeFactory.instance.arrayNode();
|
||||
for (float value : stored) {
|
||||
ObjectNode element = JsonNodeFactory.instance.objectNode();
|
||||
element.put("N", DynamoDbVectorScoring.render(value));
|
||||
list.add(element);
|
||||
}
|
||||
ObjectNode wrapper = JsonNodeFactory.instance.objectNode();
|
||||
wrapper.set("L", list);
|
||||
return wrapper;
|
||||
}
|
||||
}
|
||||
+101
-3
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -17,15 +19,28 @@ import java.util.Map;
|
||||
* stored view: one view write for an insert, an in-place update or a delete, two view
|
||||
* writes when the index key changes (delete plus insert), and nothing when the stored
|
||||
* view is unchanged or the item never touches the index.
|
||||
*
|
||||
* <p>A vector index is charged on the same delta, but reports bytes rather than units.
|
||||
*/
|
||||
final class DynamoDbWriteCapacity {
|
||||
|
||||
/** The smallest figure VectorWriteRequestBytes reports for an entry a write changes. */
|
||||
private static final double VECTOR_WRITE_FLOOR_BYTES = 1024;
|
||||
|
||||
/** What the index stores per vector component, whatever the written decimal text costs. */
|
||||
private static final int VECTOR_COMPONENT_BYTES = 4;
|
||||
|
||||
private DynamoDbWriteCapacity() {}
|
||||
|
||||
record Cost(double table, Map<String, Double> gsi, Map<String, Double> lsi) {
|
||||
record Cost(double table, Map<String, Double> gsi, Map<String, Double> lsi,
|
||||
Map<String, Double> vectorBytes) {
|
||||
|
||||
private static final Cost ZERO = new Cost(0, Map.of(), Map.of());
|
||||
|
||||
Cost(double table, Map<String, Double> gsi, Map<String, Double> lsi) {
|
||||
this(table, gsi, lsi, Map.of());
|
||||
}
|
||||
|
||||
static Cost zero() {
|
||||
return ZERO;
|
||||
}
|
||||
@@ -37,12 +52,19 @@ final class DynamoDbWriteCapacity {
|
||||
return sum;
|
||||
}
|
||||
|
||||
/** The same cost with the table arm replaced, which a transaction charges at twice the rate. */
|
||||
Cost withTable(double units) {
|
||||
return new Cost(units, gsi, lsi, vectorBytes);
|
||||
}
|
||||
|
||||
Cost plus(Cost other) {
|
||||
var mergedGsi = new LinkedHashMap<>(gsi);
|
||||
other.gsi().forEach((name, units) -> mergedGsi.merge(name, units, Double::sum));
|
||||
var mergedLsi = new LinkedHashMap<>(lsi);
|
||||
other.lsi().forEach((name, units) -> mergedLsi.merge(name, units, Double::sum));
|
||||
return new Cost(table + other.table(), mergedGsi, mergedLsi);
|
||||
LinkedHashMap<String, Double> mergedVector = new LinkedHashMap<>(vectorBytes);
|
||||
other.vectorBytes().forEach((name, bytes) -> mergedVector.merge(name, bytes, Double::sum));
|
||||
return new Cost(table + other.table(), mergedGsi, mergedLsi, mergedVector);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +93,83 @@ final class DynamoDbWriteCapacity {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Cost(tableUnits, gsiUnits, lsiUnits);
|
||||
LinkedHashMap<String, Double> vectorBytes = new LinkedHashMap<>();
|
||||
for (VectorIndex vectorIndex : table.getVectorIndexes()) {
|
||||
double bytes = vectorEntryBytes(vectorIndex,
|
||||
vectorView(table, vectorIndex, oldItem),
|
||||
vectorView(table, vectorIndex, newItem));
|
||||
if (bytes > 0) {
|
||||
vectorBytes.put(vectorIndex.getIndexName(), bytes);
|
||||
}
|
||||
}
|
||||
return new Cost(tableUnits, gsiUnits, lsiUnits, vectorBytes);
|
||||
}
|
||||
|
||||
private static double vectorEntryBytes(VectorIndex index, JsonNode oldView, JsonNode newView) {
|
||||
if (oldView == null) {
|
||||
return newView == null ? 0 : entryBytes(index, newView);
|
||||
}
|
||||
if (newView == null) {
|
||||
return entryBytes(index, oldView);
|
||||
}
|
||||
if (oldView.equals(newView)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(entryBytes(index, oldView), entryBytes(index, newView));
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored entry's size: every projected attribute at its item size, with the vector
|
||||
* itself costing four bytes per component instead of the decimal text the item carries.
|
||||
* The components are never read, only counted.
|
||||
*/
|
||||
private static double entryBytes(VectorIndex index, JsonNode view) {
|
||||
String vectorAttribute = index.getVectorAttributeName();
|
||||
double bytes = DynamoDbItemSize.utf8Length(vectorAttribute)
|
||||
+ VECTOR_COMPONENT_BYTES * index.getDimensions();
|
||||
for (Map.Entry<String, JsonNode> field : view.properties()) {
|
||||
if (!vectorAttribute.equals(field.getKey())) {
|
||||
bytes += DynamoDbItemSize.utf8Length(field.getKey())
|
||||
+ DynamoDbItemSize.attributeValueSize(field.getValue());
|
||||
}
|
||||
}
|
||||
return Math.max(VECTOR_WRITE_FLOOR_BYTES, bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the vector index stores for the item, or null when the item is not in the index:
|
||||
* it carries no vector attribute, or none for the search schema's HASH attribute. Both
|
||||
* leave the item out silently rather than failing the write.
|
||||
*/
|
||||
private static JsonNode vectorView(TableDefinition table, VectorIndex index, JsonNode item) {
|
||||
if (item == null || !item.has(index.getVectorAttributeName())) {
|
||||
return null;
|
||||
}
|
||||
String hashAttribute = index.getHashAttributeName();
|
||||
if (hashAttribute != null && !item.has(hashAttribute)) {
|
||||
return null;
|
||||
}
|
||||
String projectionType = index.getProjectionType();
|
||||
if (projectionType == null || "ALL".equals(projectionType)) {
|
||||
return item;
|
||||
}
|
||||
LinkedHashSet<String> keep = new LinkedHashSet<>();
|
||||
keep.add(table.getPartitionKeyName());
|
||||
if (table.getSortKeyName() != null) {
|
||||
keep.add(table.getSortKeyName());
|
||||
}
|
||||
keep.add(index.getVectorAttributeName());
|
||||
keep.addAll(index.getSearchSchemaAttributeNames());
|
||||
if ("INCLUDE".equals(projectionType)) {
|
||||
keep.addAll(index.getNonKeyAttributes());
|
||||
}
|
||||
ObjectNode view = JsonNodeFactory.instance.objectNode();
|
||||
for (String name : keep) {
|
||||
if (item.has(name)) {
|
||||
view.set(name, item.get(name));
|
||||
}
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private static double indexUnits(TableDefinition table, List<KeySchemaElement> keySchema,
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SearchSchemaElement {
|
||||
|
||||
private String attributeName;
|
||||
private String searchSchemaElementType; // HASH or INLINE_FILTER
|
||||
|
||||
public SearchSchemaElement() {}
|
||||
|
||||
public SearchSchemaElement(String attributeName, String searchSchemaElementType) {
|
||||
this.attributeName = attributeName;
|
||||
this.searchSchemaElementType = searchSchemaElementType;
|
||||
}
|
||||
|
||||
public String getAttributeName() { return attributeName; }
|
||||
public void setAttributeName(String attributeName) { this.attributeName = attributeName; }
|
||||
|
||||
public String getSearchSchemaElementType() { return searchSchemaElementType; }
|
||||
public void setSearchSchemaElementType(String searchSchemaElementType) {
|
||||
this.searchSchemaElementType = searchSchemaElementType;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ public class TableDefinition {
|
||||
private Map<String, String> tags;
|
||||
private List<GlobalSecondaryIndex> globalSecondaryIndexes;
|
||||
private List<LocalSecondaryIndex> localSecondaryIndexes;
|
||||
private List<VectorIndex> vectorIndexes;
|
||||
private String billingMode; // "PROVISIONED" or "PAY_PER_REQUEST"
|
||||
private String ttlAttributeName;
|
||||
private boolean ttlEnabled;
|
||||
@@ -64,6 +65,7 @@ public class TableDefinition {
|
||||
this.tags = new HashMap<>();
|
||||
this.globalSecondaryIndexes = new ArrayList<>();
|
||||
this.localSecondaryIndexes = new ArrayList<>();
|
||||
this.vectorIndexes = new ArrayList<>();
|
||||
this.pointInTimeRecoveryRecoveryPeriodInDays = 35;
|
||||
this.kinesisStreamingDestinations = new ArrayList<>();
|
||||
this.replicaRegions = new ArrayList<>();
|
||||
@@ -92,6 +94,7 @@ public class TableDefinition {
|
||||
this.tags = new HashMap<>();
|
||||
this.globalSecondaryIndexes = new ArrayList<>();
|
||||
this.localSecondaryIndexes = new ArrayList<>();
|
||||
this.vectorIndexes = new ArrayList<>();
|
||||
this.pointInTimeRecoveryRecoveryPeriodInDays = 35;
|
||||
this.kinesisStreamingDestinations = new ArrayList<>();
|
||||
this.replicaRegions = new ArrayList<>();
|
||||
@@ -137,6 +140,16 @@ public class TableDefinition {
|
||||
this.localSecondaryIndexes = localSecondaryIndexes != null ? localSecondaryIndexes : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<VectorIndex> getVectorIndexes() {
|
||||
if (vectorIndexes == null) {
|
||||
vectorIndexes = new ArrayList<>();
|
||||
}
|
||||
return vectorIndexes;
|
||||
}
|
||||
public void setVectorIndexes(List<VectorIndex> vectorIndexes) {
|
||||
this.vectorIndexes = vectorIndexes != null ? vectorIndexes : new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getBillingMode() { return billingMode; }
|
||||
public void setBillingMode(String billingMode) { this.billingMode = billingMode; }
|
||||
|
||||
@@ -279,4 +292,14 @@ public class TableDefinition {
|
||||
.filter(l -> indexName.equals(l.getIndexName()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public Optional<VectorIndex> findVectorIndex(String indexName) {
|
||||
if (vectorIndexes == null || vectorIndexes.isEmpty() || indexName == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return vectorIndexes.stream()
|
||||
.filter(v -> indexName.equals(v.getIndexName()))
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class VectorIndex {
|
||||
|
||||
private static final String HASH = "HASH";
|
||||
|
||||
private String indexName;
|
||||
private String vectorAttributeName;
|
||||
private List<SearchSchemaElement> searchSchema;
|
||||
private String projectionType;
|
||||
private List<String> nonKeyAttributes;
|
||||
private Long dimensions;
|
||||
private String distanceFunction;
|
||||
private String indexArn;
|
||||
private String indexStatus = "ACTIVE";
|
||||
// Set only when the index was added by UpdateTable, which reports the allocation and
|
||||
// backfilling phases; null on the CreateTable path, which reports an ACTIVE index at once.
|
||||
private Instant creationStartedAt;
|
||||
|
||||
public VectorIndex() {
|
||||
this.searchSchema = new ArrayList<>();
|
||||
this.nonKeyAttributes = new ArrayList<>();
|
||||
}
|
||||
|
||||
public VectorIndex(String indexName, String vectorAttributeName,
|
||||
List<SearchSchemaElement> searchSchema, String projectionType,
|
||||
List<String> nonKeyAttributes, Long dimensions, String distanceFunction) {
|
||||
this.indexName = indexName;
|
||||
this.vectorAttributeName = vectorAttributeName;
|
||||
this.searchSchema = searchSchema != null ? searchSchema : new ArrayList<>();
|
||||
// Left null when the request omitted Projection, which is a required member the
|
||||
// CreateTable and UpdateTable validation rejects.
|
||||
this.projectionType = projectionType;
|
||||
this.nonKeyAttributes = nonKeyAttributes != null ? nonKeyAttributes : new ArrayList<>();
|
||||
this.dimensions = dimensions;
|
||||
this.distanceFunction = distanceFunction;
|
||||
}
|
||||
|
||||
public String getIndexName() { return indexName; }
|
||||
public void setIndexName(String indexName) { this.indexName = indexName; }
|
||||
|
||||
public String getVectorAttributeName() { return vectorAttributeName; }
|
||||
public void setVectorAttributeName(String vectorAttributeName) { this.vectorAttributeName = vectorAttributeName; }
|
||||
|
||||
public List<SearchSchemaElement> getSearchSchema() { return searchSchema; }
|
||||
public void setSearchSchema(List<SearchSchemaElement> searchSchema) {
|
||||
this.searchSchema = searchSchema != null ? searchSchema : new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getProjectionType() { return projectionType; }
|
||||
public void setProjectionType(String projectionType) { this.projectionType = projectionType; }
|
||||
|
||||
public List<String> getNonKeyAttributes() { return nonKeyAttributes; }
|
||||
public void setNonKeyAttributes(List<String> nonKeyAttributes) {
|
||||
this.nonKeyAttributes = nonKeyAttributes != null ? nonKeyAttributes : new ArrayList<>();
|
||||
}
|
||||
|
||||
public Long getDimensions() { return dimensions; }
|
||||
public void setDimensions(Long dimensions) { this.dimensions = dimensions; }
|
||||
|
||||
public String getDistanceFunction() { return distanceFunction; }
|
||||
public void setDistanceFunction(String distanceFunction) { this.distanceFunction = distanceFunction; }
|
||||
|
||||
public String getIndexArn() { return indexArn; }
|
||||
public void setIndexArn(String indexArn) { this.indexArn = indexArn; }
|
||||
|
||||
public String getIndexStatus() { return indexStatus; }
|
||||
public void setIndexStatus(String indexStatus) { this.indexStatus = indexStatus; }
|
||||
|
||||
public Instant getCreationStartedAt() { return creationStartedAt; }
|
||||
public void setCreationStartedAt(Instant creationStartedAt) { this.creationStartedAt = creationStartedAt; }
|
||||
|
||||
/**
|
||||
* The attribute names the index filters on, in search-schema order.
|
||||
*
|
||||
* <p>{@code @JsonIgnore}d for the reason {@code TableDefinition.getSortKeyNames()} documents:
|
||||
* it is derived from {@code searchSchema}, and without a backing setter Jackson's
|
||||
* getter-as-setter fallback appends into the immutable list this method returns.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public List<String> getSearchSchemaAttributeNames() {
|
||||
return searchSchema.stream()
|
||||
.map(SearchSchemaElement::getAttributeName)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The attribute the search schema partitions on, or null when the index declares no HASH
|
||||
* element. {@code @JsonIgnore}d for the same reason as
|
||||
* {@link #getSearchSchemaAttributeNames()}: it is derived from {@code searchSchema}.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getHashAttributeName() {
|
||||
for (SearchSchemaElement element : searchSchema) {
|
||||
if (HASH.equals(element.getSearchSchemaElementType())) {
|
||||
return element.getAttributeName();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user