Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions ambry-named-mysql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,44 @@ Configure the reader data source for `READ COMMITTED` or stronger on every check
A pool shared with the publisher must use `REPEATABLE READ`; readers do not change its isolation. Distinct roots can
reference the same child; finding its ID does not authorize deletion.

## Inspecting recorded manifests

The read-only inventory checks at most 32 supplied version tuples on one database, with one bounded manifest lookup
per tuple. Each connection must use `READ COMMITTED` isolation or stronger. Give the command a private UTF-8 JSON file
containing `[accountId, containerId, blobName, version]` arrays. Use decimal strings for versions to preserve all 64
bits. For example:

```json
[[17, 4, "folder/example", "1234567890123456789"]]
```

Set `AMBRY_INVENTORY_JDBC_URL` to the approved, authoritative database's JDBC URL (include the database name and use
`sslMode=VERIFY_IDENTITY` for remote connections), `AMBRY_INVENTORY_JDBC_USER` to an identity with SELECT access only,
and `AMBRY_INVENTORY_JDBC_PASSWORD` only if required. Do not put credentials in the URL or on the command line. The
command is verified against a local test fixture only. Using it against a TLS endpoint that requires a private CA or
client certificate requires separate validation of the JDBC trust and key store setup.

The JDBC `connectTimeout` and `socketTimeout` default to five seconds each. Connector/J URL properties with those names
override the defaults (values are in milliseconds). They limit connection establishment and socket reads, respectively,
not the duration of a query or the whole run.

```sh
./gradlew --quiet :ambry-named-mysql:manifestInventory \
--args='/path/to/private-tuples.json /path/to/new-report.jsonl'
```

The new report file contains JSON Lines keyed by one-based input position:

- `verified`: the recorded row passed checksum and descriptor-framing checks. The recorded count includes duplicate
IDs. The command does not independently validate child IDs or check that chunks exist.
- `missing`: no exact committed row was observed on the selected database.
- `invalid`: the row failed validation.

Exit zero means the report completed, even if it contains `invalid` rows. A nonzero exit indicates an incomplete run.
If the run is interrupted, rerun the original input into a fresh report to preserve the input positions. The inventory
reads no root or chunk data, changes no rows, discovers no additional versions, and says nothing about reachability or
bytes safe to reclaim.

## Compatibility and limits

These package-private methods have no frontend caller. They require one authoritative InnoDB writer for the name range,
Expand Down
4 changes: 4 additions & 0 deletions ambry-named-mysql/build.gradle
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@

tasks.register('manifestInventory', JavaExec) {
classpath = sourceSets.main.runtimeClasspath
mainClass.set('com.github.ambry.named.NamedBlobManifestInventory')
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Expand All @@ -35,6 +40,7 @@
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.account.Account;
Expand Down Expand Up @@ -75,6 +81,135 @@ public void testDetachedRecoveryAcrossReplacement() throws Exception {
withDatabase(NamedBlobManifestStoreIntegrationTest::exercise);
}

@Test
public void testInventoryVerifiesExactPublishedTuples() throws Exception {
withDatabase((db, named) -> {
BlobId child = blob(BlobId.BlobDataType.DATACHUNK);
long exact = 9_007_199_254_740_993L;
BlobId original = blob(BlobId.BlobDataType.METADATA);
insertNamed(db, exact, original, NamedBlobState.READY);
retireOne(named, exact, original, 2, Arrays.asList(child, child).iterator());
BlobId next = blob(BlobId.BlobDataType.METADATA);
insertNamed(db, exact + 1, next, NamedBlobState.READY);
retireOne(named, exact + 1, next, 1, Collections.singletonList(child).iterator());
try (Connection c = db.getConnection(); PreparedStatement corrupt = c.prepareStatement(
"UPDATE named_blob_manifests_v1 SET payload=REPEAT(X'00',129) WHERE version=?")) {
corrupt.setLong(1, exact + 1);
assertEquals(1, corrupt.executeUpdate());
}
NamedBlobManifestStore store = new NamedBlobManifestStore(db);
expectDataError("Invalid published manifest length",
() -> store.read(store.getPublished(ACCOUNT, CONTAINER, NAME, exact + 1)));
expectDataError("Invalid published manifest length",
() -> store.readVerifiedCount(ACCOUNT, CONTAINER, NAME, exact + 1));

JSONArray tuples = new JSONArray();
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME, Long.toString(exact))));
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME + " ", Long.toString(exact))));
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, NAME, Long.toString(exact + 1))));
for (int i = 3; i < 32; i++) {
tuples.put(tuples.getJSONArray(0));
}
DataSource inventorySource = mock(DataSource.class);
when(inventorySource.getConnection()).thenAnswer(call -> db.getConnection());
String[] lines = inspectInventory(tuples, new NamedBlobManifestStore(inventorySource));
verify(inventorySource, times(tuples.length())).getConnection();
assertEquals(32, lines.length);
JSONObject verified = new JSONObject(lines[0]);
assertEquals(1, verified.getInt("input"));
assertEquals("verified", verified.getString("status"));
assertEquals(2, verified.getInt("recorded_child_count"));
JSONObject missing = new JSONObject(lines[1]);
assertEquals(2, missing.getInt("input"));
assertEquals("missing", missing.getString("status"));
assertFalse(missing.has("recorded_child_count"));
JSONObject invalid = new JSONObject(lines[2]);
assertEquals(3, invalid.getInt("input"));
assertEquals("invalid", invalid.getString("status"));
assertFalse(invalid.has("recorded_child_count"));
JSONObject last = new JSONObject(lines[31]);
assertEquals(32, last.getInt("input"));
assertEquals("verified", last.getString("status"));
});
}

@Test
public void testInventoryMatchesExactUnicodeNameWithLatin1Reader() throws Exception {
withDatabase((db, named) -> {
String name = NAME + "/\uD83D\uDE80";
BlobId child = blob(BlobId.BlobDataType.DATACHUNK);
for (long version = 1; version <= 2; version++) {
BlobId root = blob(BlobId.BlobDataType.METADATA);
insertNamed(db, name, version, root, NamedBlobState.READY);
retireOneNamed(named, name, version, root, 1, Collections.singletonList(child).iterator());
}
String schema;
try (Connection c = db.getConnection(); Statement s = c.createStatement()) {
schema = c.getCatalog();
assertEquals(1, s.executeUpdate("UPDATE named_blob_manifests_v1 SET child_count=0 WHERE version=2"));
}
MysqlDataSource latin1 = source(schema);
latin1.setCharacterEncoding("ISO-8859-1");
try (Connection c = latin1.getConnection(); Statement s = c.createStatement();
ResultSet state = s.executeQuery("SELECT @@character_set_client")) {
assertTrue(state.next());
assertEquals("latin1", state.getString(1));
}
JSONArray tuples = new JSONArray();
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name, "1")));
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name, "2")));
tuples.put(new JSONArray(Arrays.asList(ACCOUNT, CONTAINER, name + " ", "2")));
String[] lines = inspectInventory(tuples, new NamedBlobManifestStore(latin1));
assertEquals(3, lines.length);
assertEquals("verified", new JSONObject(lines[0]).getString("status"));
assertEquals("invalid", new JSONObject(lines[1]).getString("status"));
assertEquals("missing", new JSONObject(lines[2]).getString("status"));
});
}

@Test
public void testInventoryRejectsInvalidDescriptorFraming() throws Exception {
withDatabase((db, named) -> {
BlobId root = blob(BlobId.BlobDataType.METADATA);
long version = 1;
insertNamed(db, version, root, NamedBlobState.READY);
retireOne(named, version, root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator());

byte[] name = NAME.getBytes(StandardCharsets.UTF_8);
byte[] hashHeader = ByteBuffer.allocate(2 * Short.BYTES + Long.BYTES + 2 * Integer.BYTES)
.putShort(ACCOUNT).putShort(CONTAINER).putLong(version).putInt(1).putInt(name.length).array();
NamedBlobManifestStore store = new NamedBlobManifestStore(db);
NamedBlobManifestStore.Manifest manifest = store.getPublished(ACCOUNT, CONTAINER, NAME, version);
// Recompute the checksum so only the malformed descriptor framing can reject these rows.
byte[][] payloads = {{2, 1}, {1, 1, 1}};
String[] errors = {"Invalid published child descriptor", "Trailing bytes on published manifest"};
for (int i = 0; i < payloads.length; i++) {
byte[] payload = payloads[i];
MessageDigest hash = MessageDigest.getInstance("SHA-256");
hash.update(hashHeader);
hash.update(name);
hash.update(root.getID().getBytes(StandardCharsets.US_ASCII));
hash.update((byte) 0);
try (Connection c = db.getConnection(); PreparedStatement corrupt = c.prepareStatement(
"UPDATE named_blob_manifests_v1 SET payload=?,payload_hash=? WHERE version=?")) {
corrupt.setBytes(1, payload);
corrupt.setBytes(2, hash.digest(payload));
corrupt.setLong(3, version);
assertEquals(1, corrupt.executeUpdate());
}
expectDataError(errors[i], () -> store.read(manifest));
expectDataError(errors[i], () -> store.readVerifiedCount(ACCOUNT, CONTAINER, NAME, version));
}
});
}

private static String[] inspectInventory(JSONArray tuples, NamedBlobManifestStore store) throws Exception {
StringWriter output = new StringWriter();
NamedBlobManifestInventory.inspect(new ByteArrayInputStream(tuples.toString().getBytes(StandardCharsets.UTF_8)),
store, output);
return output.toString().split("\\R");
}

private interface Scenario {
void run(DataSource source, MySqlNamedBlobDb named) throws Exception;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* Copyright 2026 LinkedIn Corp. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.github.ambry.named;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.sql.SQLException;
import java.sql.SQLDataException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.mysql.cj.jdbc.MysqlDataSource;

/** On-demand inspection of explicitly supplied, exact named-version manifest keys. */
public final class NamedBlobManifestInventory {
private static final JsonFactory JSON = new JsonFactory();
private static final int MAX_TUPLES = 32;
// Allows worst-case JSON escaping of 350 unicode characters per name, without accepting an unbounded file.
private static final int MAX_INPUT_BYTES = 160 * 1024;
private static final int DEFAULT_JDBC_TIMEOUT_MS = 5_000;

private NamedBlobManifestInventory() {
}

public static void main(String[] args) {
String url = System.getenv("AMBRY_INVENTORY_JDBC_URL");
String user = System.getenv("AMBRY_INVENTORY_JDBC_USER");
if (args.length != 2 || url == null || url.isEmpty() || user == null || user.isEmpty()) {
System.err.println("Supply a JSON tuple file and a new report path; set AMBRY_INVENTORY_JDBC_URL and"
+ " AMBRY_INVENTORY_JDBC_USER.");
System.exit(2);
return;
}

MysqlDataSource source = new MysqlDataSource();
source.setURL(url);
source.setUser(user);
source.setPassword(System.getenv("AMBRY_INVENTORY_JDBC_PASSWORD"));
try (InputStream input = Files.newInputStream(Paths.get(args[0]));
Writer output = Files.newBufferedWriter(Paths.get(args[1]), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE)) {
source.setConnectTimeout(DEFAULT_JDBC_TIMEOUT_MS);
source.setSocketTimeout(DEFAULT_JDBC_TIMEOUT_MS);
inspect(input, new NamedBlobManifestStore(source), output);
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
System.err.println("Inventory stopped: invalid input, unsupported reader isolation, or an I/O failure.");
System.exit(1);
} catch (SQLException e) {
System.err.println("Inventory stopped: database error " + e.getErrorCode() + ".");
System.exit(1);
}
}

static void inspect(InputStream input, NamedBlobManifestStore store, Writer output) throws IOException, SQLException {
List<Key> keys = readKeys(input);
for (int i = 0; i < keys.size(); i++) {
Key key = keys.get(i);
JSONObject result = new JSONObject().put("input", i + 1);
try {
Integer count = store.readVerifiedCount(key.account, key.container, key.name, key.version);
if (count == null) {
result.put("status", "missing");
} else {
result.put("status", "verified").put("recorded_child_count", count);
}
} catch (SQLDataException e) {
result.put("status", "invalid");
}
output.write(result.toString());
output.write('\n');
output.flush();
}
}

private static List<Key> readKeys(InputStream input) throws IOException {
byte[] bytes = new byte[MAX_INPUT_BYTES + 1];
int size = 0;
while (size < bytes.length) {
int n = input.read(bytes, size, bytes.length - size);
if (n == -1) {
break;
}
size += n;
}
if (size > MAX_INPUT_BYTES) {
throw new IllegalArgumentException("Tuple file too large");
}
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes, 0, size)).toString();
try (JsonParser parser = JSON.createParser(text)) {
requireToken(parser.nextToken(), JsonToken.START_ARRAY);
List<Key> keys = new ArrayList<>();
for (JsonToken token = parser.nextToken(); token != JsonToken.END_ARRAY; token = parser.nextToken()) {
requireToken(token, JsonToken.START_ARRAY);
if (keys.size() == MAX_TUPLES) {
throw new IllegalArgumentException("Too many tuples");
}
short account = Short.parseShort(readDecimal(parser));
short container = Short.parseShort(readDecimal(parser));
requireToken(parser.nextToken(), JsonToken.VALUE_STRING);
String name = parser.getText();
if (name.isEmpty() || name.codePointCount(0, name.length()) > 350 || !StandardCharsets.UTF_8.newEncoder()
.canEncode(name)) {
throw new IllegalArgumentException("Invalid blob name");
}
long version = Long.parseLong(readDecimal(parser));
requireToken(parser.nextToken(), JsonToken.END_ARRAY);
keys.add(new Key(account, container, name, version));
}
if (keys.isEmpty() || parser.nextToken() != null) {
throw new IllegalArgumentException("Expected 1 to " + MAX_TUPLES + " exact tuples");
}
return keys;
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Invalid tuple file", e);
}
}

private static void requireToken(JsonToken actual, JsonToken expected) {
if (actual != expected) {
throw new IllegalArgumentException("Expected " + expected);
}
}

private static String readDecimal(JsonParser parser) throws IOException {
JsonToken token = parser.nextToken();
if (token != JsonToken.VALUE_NUMBER_INT && token != JsonToken.VALUE_STRING) {
throw new IllegalArgumentException("Expected an integer");
}
return parser.getText();
}

private static final class Key {
final short account;
final short container;
final String name;
final long version;

Key(short account, short container, String name, long version) {
this.account = account;
this.container = container;
this.name = name;
this.version = version;
}
}
}
Loading
Loading