mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): charge a scan for each partition it reads (#8835)
A Scan, and a PartiQL statement read as a scan, is now charged for each partition it reads, each at its own 4 KB blocks and at least one even when empty. An on-demand table and its indexes have 4 partitions, so a small one's scan costs 2 units, or 4 with ConsistentRead, where Floci charged 0.5; a provisioned table keeps one. An item's partition comes from the key hash of #8798, each partition holding a quarter of its range. The page that ends a scan also charges each empty partition, and the one it resumed in when it read none. An ordered PartiQL statement charges each read on its own; a parallel scan keeps its single read.
This commit is contained in:
1 parent
f511cd8a44
commit
252a6012b3
7 files changed
+272
-19
No files matched your search
@@ -11,9 +11,11 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.ToIntFunction;
|
||||
|
||||
/** The hash DynamoDB places and orders keys by: MD5 over "Outliers" and the bytes of the key values. */
|
||||
final class DynamoDbKeyHash {
|
||||
@@ -41,6 +43,24 @@ final class DynamoDbKeyHash {
|
||||
Arrays::compareUnsigned);
|
||||
}
|
||||
|
||||
/** DynamoDB gives an on-demand table and its indexes 4 partitions, and a table provisioned at 1 unit 1. */
|
||||
static int partitionCount(TableDefinition table) {
|
||||
return "PAY_PER_REQUEST".equals(table.getBillingMode()) ? 4 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the partition of an item, each partition holding an equal range of the hash. A key value
|
||||
* is hashed once, as a scan meets the same partition key again and again.
|
||||
*/
|
||||
static ToIntFunction<JsonNode> partitionLocator(List<String> keyNames, int partitions) {
|
||||
if (partitions == 1) {
|
||||
return item -> 0;
|
||||
}
|
||||
Map<List<JsonNode>, Integer> known = new HashMap<>();
|
||||
return item -> known.computeIfAbsent(Arrays.asList(keyNames.stream().map(item::get).toArray(JsonNode[]::new)),
|
||||
ignored -> (of(item, keyNames)[0] & 0xFF) * partitions / 256);
|
||||
}
|
||||
|
||||
static byte[] of(JsonNode item, List<String> keyNames) {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
bytes.writeBytes(SALT);
|
||||
|
||||
@@ -149,9 +149,7 @@ class DynamoDbPartiQLHandler {
|
||||
private static DynamoDbWriteCapacity.Cost readCapacity(Stmt.Select stmt, TableDefinition table,
|
||||
DynamoDbAccessPath accessPath, Page page,
|
||||
boolean consistentRead) {
|
||||
double units = page.readBytes().stream()
|
||||
.mapToDouble(bytes -> NativeDynamoDbJsonHandler.readCapacityUnits(bytes, consistentRead))
|
||||
.sum();
|
||||
double units = NativeDynamoDbJsonHandler.readCapacityUnits(page.readBytes(), consistentRead);
|
||||
if (!accessPath.isIndex()) {
|
||||
return new DynamoDbWriteCapacity.Cost(units, Map.of(), Map.of());
|
||||
}
|
||||
@@ -243,8 +241,7 @@ class DynamoDbPartiQLHandler {
|
||||
List<JsonNode> matching = partialProjection
|
||||
? matchingIndexView(result.items(), scanFilters, accessPath, table)
|
||||
: result.items();
|
||||
return new Page(matching, result.lastEvaluatedKey(), List.of(result.scannedBytes()),
|
||||
result.scannedItems());
|
||||
return new Page(matching, result.lastEvaluatedKey(), result.readBytes(), result.scannedItems());
|
||||
}
|
||||
if (accessPath.kind() == DynamoDbAccessPath.Kind.TABLE && skName == null
|
||||
&& skCond == null && filterConds.isEmpty()) {
|
||||
@@ -362,14 +359,14 @@ class DynamoDbPartiQLHandler {
|
||||
private Page readOrdered(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,
|
||||
Routing routing, JsonNode after, Integer limit, String region) {
|
||||
List<JsonNode> rows = new ArrayList<>();
|
||||
long scannedBytes = 0;
|
||||
List<Long> readBytes = new ArrayList<>();
|
||||
List<JsonNode> scannedItems = new ArrayList<>();
|
||||
JsonNode lastKey = null;
|
||||
do {
|
||||
JsonNode from = lastKey;
|
||||
Page page = readPage(stmt, table, accessPath, routing, () -> from, null, region);
|
||||
rows.addAll(page.items());
|
||||
scannedBytes += page.readBytes().stream().mapToLong(Long::longValue).sum();
|
||||
readBytes.addAll(page.readBytes());
|
||||
scannedItems.addAll(page.scannedItems());
|
||||
lastKey = page.lastEvaluatedKey();
|
||||
} while (lastKey != null);
|
||||
@@ -384,7 +381,7 @@ class DynamoDbPartiQLHandler {
|
||||
}
|
||||
int end = limit == null ? rows.size() : start + Math.min(rows.size() - start, limit);
|
||||
JsonNode resumeAfter = start < end && end < rows.size() ? orderingKey(rows.get(end - 1), accessPath, table) : null;
|
||||
return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, List.of(scannedBytes), scannedItems);
|
||||
return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, readBytes, scannedItems);
|
||||
}
|
||||
|
||||
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath,
|
||||
|
||||
@@ -80,6 +80,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
@@ -89,7 +90,9 @@ import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.ToIntFunction;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
@@ -1768,9 +1771,14 @@ public class DynamoDbService {
|
||||
TableDefinition table = requireActiveTable(storageKey);
|
||||
|
||||
DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);
|
||||
int partitions = DynamoDbKeyHash.partitionCount(table);
|
||||
boolean segmented = segment != null && totalSegments != null && totalSegments > 1;
|
||||
|
||||
ConcurrentSkipListMap<String, JsonNode> items = itemsByTable.get(scopedItemsKey(storageKey));
|
||||
if (items == null) return new ScanResult(List.of(), 0, 0, null, List.of());
|
||||
if (items == null) {
|
||||
return new ScanResult(List.of(), 0, segmented ? List.of(0L) : Collections.nCopies(partitions, 0L),
|
||||
null, List.of());
|
||||
}
|
||||
|
||||
// ConcurrentSkipListMap keeps items sorted by base item key — no sort needed.
|
||||
// Use tailMap for O(log n) pagination instead of O(n) linear search.
|
||||
@@ -1787,6 +1795,13 @@ public class DynamoDbService {
|
||||
lekPkName = accessPath.partitionKeyName();
|
||||
lekSkName = accessPath.sortKeyName();
|
||||
}
|
||||
String indexPkName = lekPkName;
|
||||
String indexSkName = lekSkName;
|
||||
Predicate<JsonNode> inIndex = item -> !indexScan || (hasNonNullAttribute(item, indexPkName)
|
||||
&& (indexSkName == null || hasNonNullAttribute(item, indexSkName)));
|
||||
ToIntFunction<JsonNode> partitionOf = DynamoDbKeyHash.partitionLocator(
|
||||
accessPath.isGlobalSecondaryIndex() ? accessPath.partitionKeyNames() : List.of(pkName), partitions);
|
||||
Map<Integer, Long> bytesByPartition = new TreeMap<>();
|
||||
|
||||
Collection<JsonNode> source = exclusiveStartKey != null
|
||||
? items.tailMap(buildItemKeyFromNode(exclusiveStartKey, pkName, skName), false).values()
|
||||
@@ -1807,11 +1822,10 @@ public class DynamoDbService {
|
||||
// itself, and base-table items missing any index key attribute do not
|
||||
// exist in the index — they are never read, never counted, and can
|
||||
// never anchor a cursor.
|
||||
if (indexScan && !(hasNonNullAttribute(item, lekPkName)
|
||||
&& (lekSkName == null || hasNonNullAttribute(item, lekSkName)))) {
|
||||
if (!inIndex.test(item)) {
|
||||
continue;
|
||||
}
|
||||
if (segment != null && totalSegments != null && totalSegments > 1) {
|
||||
if (segmented) {
|
||||
JsonNode pkAttr = item.get(lekPkName);
|
||||
if (computeSegment(pkAttr, totalSegments) != segment) {
|
||||
continue;
|
||||
@@ -1832,7 +1846,11 @@ public class DynamoDbService {
|
||||
break;
|
||||
}
|
||||
accSize += sz;
|
||||
billedBytes += billedReadSize(item, accessPath, table, sz);
|
||||
long billed = billedReadSize(item, accessPath, table, sz);
|
||||
billedBytes += billed;
|
||||
if (!segmented) {
|
||||
bytesByPartition.merge(partitionOf.applyAsInt(item), billed, Long::sum);
|
||||
}
|
||||
totalScanned++;
|
||||
scannedItems.add(item);
|
||||
lastScanned = item;
|
||||
@@ -1858,7 +1876,38 @@ public class DynamoDbService {
|
||||
|
||||
LOG.tracev("Scan on {0}: returned={1} scanned={2}",
|
||||
canonicalTableName, results.size(), totalScanned);
|
||||
return new ScanResult(results, totalScanned, billedBytes, lastEvaluatedKey, scannedItems);
|
||||
List<Long> readBytes = segmented ? List.of(billedBytes)
|
||||
: partitionReads(items.values(), inIndex, partitionOf, partitions, bytesByPartition,
|
||||
lastEvaluatedKey == null, totalScanned == 0 ? exclusiveStartKey : null);
|
||||
return new ScanResult(results, totalScanned, readBytes, lastEvaluatedKey, scannedItems);
|
||||
}
|
||||
|
||||
// DynamoDB charges a scan page for each partition it reads, at least one 4 KB block each. The
|
||||
// page that ends the scan also reads each partition that holds nothing, and when it finds no
|
||||
// item left it still reads the partition it resumed in.
|
||||
private static List<Long> partitionReads(Collection<JsonNode> allItems, Predicate<JsonNode> inIndex,
|
||||
ToIntFunction<JsonNode> partitionOf, int partitions,
|
||||
Map<Integer, Long> bytesByPartition, boolean endsScan,
|
||||
JsonNode resumedFrom) {
|
||||
Set<Integer> read = new TreeSet<>(bytesByPartition.keySet());
|
||||
if (endsScan) {
|
||||
Set<Integer> holding = new HashSet<>();
|
||||
for (Iterator<JsonNode> each = allItems.iterator(); each.hasNext() && holding.size() < partitions; ) {
|
||||
JsonNode item = each.next();
|
||||
if (inIndex.test(item)) {
|
||||
holding.add(partitionOf.applyAsInt(item));
|
||||
}
|
||||
}
|
||||
for (int partition = 0; partition < partitions; partition++) {
|
||||
if (!holding.contains(partition)) {
|
||||
read.add(partition);
|
||||
}
|
||||
}
|
||||
if (resumedFrom != null) {
|
||||
read.add(partitionOf.applyAsInt(resumedFrom));
|
||||
}
|
||||
}
|
||||
return read.stream().map(partition -> bytesByPartition.getOrDefault(partition, 0L)).toList();
|
||||
}
|
||||
|
||||
// A read served by a KEYS_ONLY or INCLUDE index is sized on the projection the
|
||||
@@ -5227,9 +5276,10 @@ public class DynamoDbService {
|
||||
|
||||
public record TransactGetResult(List<JsonNode> items, Map<String, DynamoDbWriteCapacity.Cost> capacity) {}
|
||||
|
||||
// scannedBytes carries the pre-filter size of the read items: DynamoDB bills a
|
||||
// Query or Scan on what it read, not on what survived the filter or projection.
|
||||
public record ScanResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey,
|
||||
// scannedBytes and readBytes carry the pre-filter size of the read items: DynamoDB bills a
|
||||
// Query or Scan on what it read, not on what survived the filter or projection. A Scan
|
||||
// charges each partition it reads on its own.
|
||||
public record ScanResult(List<JsonNode> items, int scannedCount, List<Long> readBytes, JsonNode lastEvaluatedKey,
|
||||
List<JsonNode> scannedItems) {}
|
||||
public record QueryResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey,
|
||||
List<JsonNode> scannedItems) {}
|
||||
|
||||
@@ -1634,7 +1634,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
response.set("LastEvaluatedKey", result.lastEvaluatedKey());
|
||||
}
|
||||
addConsumedCapacity(response, request, tableName,
|
||||
readCapacityUnits(result.scannedBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath);
|
||||
readCapacityUnits(result.readBytes(), request.path("ConsistentRead").asBoolean(false)), scanAccessPath);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@@ -3729,6 +3729,11 @@ public class NativeDynamoDbJsonHandler {
|
||||
return consistentRead ? units * 2 : units;
|
||||
}
|
||||
|
||||
/** Each read DynamoDB charges on its own, such as each partition a scan page reads. */
|
||||
static double readCapacityUnits(List<Long> reads, boolean consistentRead) {
|
||||
return reads.stream().mapToDouble(bytes -> readCapacityUnits(bytes, consistentRead)).sum();
|
||||
}
|
||||
|
||||
/**
|
||||
* Write-side ConsumedCapacity with the per-index arms DynamoDB reports under
|
||||
* INDEXES. oldItem and newItem are the stored images around the write; the new
|
||||
|
||||
Reference in new issue
Block a user