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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 38 additions & 14 deletions ambry-named-mysql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ production settings. Check the client limit as well as MySQL and replication lim
installed the triggers run on ordinary writes even with manifests disabled. A missing definer or missing privileges
can break named PUT, TTL finalization and soft DELETE.

**Before production DDL**, rehearse in staging using the production MySQL version, roles and session isolation for each
operation. Run the same representative PUT workload in three states: before applying the migration, after installing the
triggers with publication disabled, and alongside publication. Compare the first two runs to measure the migration's
cost to ordinary PUTs; compare the last two to measure the additional cost of concurrent publication. After installing
the triggers, also run publication alone as its baseline for the mixed run. Start each publication workload with
equivalently seeded, unpublished named versions: replaying a committed request skips the manifest insert. Record
latency, lock waits, timeouts and other errors separately for each operation. Do not start production DDL if either
operation exceeds its rollout limits. Separately probe unrelated accounts and neighboring keys by holding a PUT and a
retirement open in turn. Report these deliberate waits outside the representative workload measurements.

From `ambry-named-mysql/src/main/resources`, set `DB` to the approved writer's named-blob schema. Use separate mysql
options files: `MYSQL_CNF` for schema DDL and `DEFINER_CNF` for the durable service account that will own the trigger.
The trigger file uses MySQL's implicit `DEFINER=CURRENT_USER`. Before installation, confirm the matched `user@host`
Expand All @@ -62,33 +72,47 @@ timeout for every retry. Do not use a table-copy fallback.
```sh
mysql --defaults-file="$MYSQL_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \
< NamedBlobManifestV1.ddl
mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \
--delimiter='//' -e 'SOURCE NamedBlobRetirementFenceV1.sql'
mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \
--delimiter='//' -e 'SOURCE NamedBlobManifestTupleGuardInsertV1.sql'
mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \
--delimiter='//' -e 'SOURCE NamedBlobManifestTupleGuardUpdateV1.sql'
mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SHOW CREATE TRIGGER named_blob_manifest_tuple_guard_ins_v1\G'
mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SHOW CREATE TRIGGER named_blob_manifest_tuple_guard_upd_v1\G'
```

Compare both guard bodies with the shipped SQL and both definers with the approved service account before installing
the fence. Install the fence last: the publisher checks its effect, but cannot detect a missing tuple guard.

```sh
mysql --defaults-file="$DEFINER_CNF" --database="$DB" --init-command='SET SESSION lock_wait_timeout=5' \
--delimiter='//' -e 'SOURCE NamedBlobRetirementFenceV1.sql'
mysql --defaults-file="$DEFINER_CNF" --database="$DB" -e 'SHOW CREATE TRIGGER named_blob_retirement_fence_v1\G'
```

The delimiter keeps each compound trigger intact in the mysql client; JDBC installers send each trigger file as
one statement. Verify all three trigger bodies and definers. The tuple guards need locking-read privileges on
`named_blob_manifests_v1`; rehearse using the deployed MySQL version and roles. Every insert checks the manifest
primary key, even when no caller is enabled. Rehearse normal PUT concurrency and watch lock waits before rollout.
On each writer, connect **as the application account** and smoke-test an unfenced update: in one transaction, insert
an approved disposable named version, finalize its TTL using its exact primary key, verify one row changed to READY
with `deleted_ts IS NULL`, and roll back. Verify the fixture row is absent afterward. Do not use a customer row. Stop
on any error; a successful install by the DDL operator is not evidence that application writes still work.
one statement. After installation, complete the [activation checklist](#migration-activation-checklist).

**On any error or lost connection, do not rerun the file.** Each successful DDL statement has already committed.
Wait for any in-flight DDL to finish. Inspect `SHOW CREATE TABLE` for the manifest table and `named_blobs_v2`, and
`SHOW CREATE TRIGGER` if the trigger exists. Compare definitions in installation order: manifest table and composite
primary key, fence column, ordered unfenced-version index, then trigger and definer. Stop on any conflicting
`SHOW CREATE TRIGGER` for each installed trigger. Compare definitions in installation order: manifest table and composite
primary key, fence column, ordered unfenced-version index, insert guard, update guard, then retirement fence. Keep
publication disabled if the fence is already present without both guards. Stop on any conflicting
definition. Fix the cause, resume at the first missing statement using the timeout above, and run only the missing
steps in order. An index build can finish scanning the table and still time out waiting for its final metadata lock.
steps in order. If the fence is missing, install any missing tuple guards, then verify **both** guard bodies and definers
as on a fresh install before creating the fence. An index build can finish scanning the table and still time out waiting
for its final metadata lock.
If the column exists but the index does not, have the owners finish any long-running transactions holding the lock
before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. Then install the trigger, recheck the
definitions, and run the application smoke test.
before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. After resuming, complete the same
[activation checklist](#migration-activation-checklist).

### Migration activation checklist

- On every writer and promotion candidate, compare `SHOW CREATE TRIGGER` for both tuple guards and the retirement fence
with the shipped bodies and approved definer. Keep publication disabled on any mismatch. A successful retirement
does not verify either guard.
- On each writer, connect **as the application account**. In one transaction insert an approved disposable named
version, finalize its TTL by exact primary key, verify one row changed to READY with `deleted_ts IS NULL`, and roll
back. Verify the fixture row is absent afterward. Never use a customer row; stop on any error.

## Before enabling a caller

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ private static void withDatabase(BeforeMigration before, Scenario scenario) thro
before.seed(db);
}
install(ddl, "/NamedBlobManifestV1.ddl");
install(ddl, "/NamedBlobRetirementFenceV1.sql");
install(ddl, "/NamedBlobManifestTupleGuardInsertV1.sql");
install(ddl, "/NamedBlobManifestTupleGuardUpdateV1.sql");
install(ddl, "/NamedBlobRetirementFenceV1.sql");
}
try (MySqlNamedBlobDb named = namedDb(db)) {
scenario.run(db, named);
Expand Down Expand Up @@ -568,10 +568,7 @@ public void testOrdinaryStateUpdateIgnoresExistingManifest() throws Exception {
}

/**
* Deterministically proves non-contention rather than merely hoping two threads race: the first PUT's own AFTER
* INSERT trigger has already run and its transaction is deliberately left open (uncommitted) while a second PUT
* for an unrelated name is attempted. A bounded lock-wait timeout on the second connection turns a reintroduced
* cross-name gap lock into a prompt test failure instead of a hang.
* Holding the first PUT open tests PUT versus PUT; compatible gap locks do not rule out waits against publication.
*/
@Test
public void testConcurrentUnrelatedNamedPutsDoNotContendOnTheGuardTrigger() throws Exception {
Expand Down Expand Up @@ -604,15 +601,66 @@ public void testConcurrentUnrelatedNamedPutsDoNotContendOnTheGuardTrigger() thro
insert.setLong(4, 1);
insert.setBytes(5, rootB.toBytes());
insert.setInt(6, NamedBlobState.READY.ordinal());
// This would fail with InnoDB lock wait timeout (1205) here if the AFTER trigger introduced cross-name
// contention: it only ever locks its own tuple, and only after the base row's own insert lock landed.
assertEquals(1, insert.executeUpdate());
}
first.commit();
}
});
}

@Test
public void testHeldUnrelatedPutBlocksPublicationOnlyWithInsertGuard() throws Exception {
withDatabase((db, named) -> exerciseHeldPut(db, true));
withDatabase((db, named) -> exerciseHeldPut(db, false));
}

private static void exerciseHeldPut(DataSource db, boolean guardInstalled) throws Exception {
BlobId root = blob(BlobId.BlobDataType.METADATA);
insertNamed(db, 1, root, NamedBlobState.READY);
NamedBlobManifestStore.PreparedRetirement request = NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME,
Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1,
Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())));
try (Connection publisher = db.getConnection(); Connection writer = db.getConnection();
Statement setup = publisher.createStatement(); PreparedStatement put = writer.prepareStatement(
"INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)"
+ " VALUES (?,?,?,?,?,?)")) {
publisher.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
writer.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
if (!guardInstalled) {
setup.execute("DROP TRIGGER named_blob_manifest_tuple_guard_ins_v1");
}
setup.execute("SET SESSION innodb_lock_wait_timeout=2");
// Commit a separator so publication's named-table range does not reach the held PUT in ACCOUNT + 2.
put.setInt(1, ACCOUNT + 1);
put.setInt(2, CONTAINER);
put.setString(3, NAME);
put.setLong(4, 1);
put.setBytes(5, blob(BlobId.BlobDataType.METADATA).toBytes());
put.setInt(6, NamedBlobState.READY.ordinal());
assertEquals(1, put.executeUpdate());
writer.setAutoCommit(false);
put.setInt(1, ACCOUNT + 2);
assertEquals(1, put.executeUpdate());
publisher.setAutoCommit(false);
if (guardInstalled) {
try {
NamedBlobManifestStore.retire(publisher, request);
fail("Expected the held PUT's insert guard to block publication");
} catch (SQLException expected) {
assertEquals(expected.getMessage(), 1205, expected.getErrorCode());
}
publisher.rollback();
writer.commit();
}
NamedBlobManifestStore.retire(publisher, request);
publisher.commit();
if (!guardInstalled) {
writer.commit();
}
}
assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1"));
}

/**
* The concretely reported hazard: two unrelated publishers' locking reads against absent manifest keys could
* land in the same InnoDB index gap and deadlock (MySQL error 1213), even though they never touch the same
Expand Down
Loading