diff --git a/crates/core/src/validation/warm_throughput.rs b/crates/core/src/validation/warm_throughput.rs index 75502195e..da7591966 100644 --- a/crates/core/src/validation/warm_throughput.rs +++ b/crates/core/src/validation/warm_throughput.rs @@ -257,12 +257,13 @@ pub fn validate_warm_throughput_on_update( /// `ResourceNotFoundException` (S10, T5a, T5c). /// /// TableClass, DeletionProtection and SSE have the same "only operation" rule -/// on their own, without WarmThroughput (measured), but ExtendDB does not apply -/// it elsewhere yet; here the companion's own sentence is used only when -/// WarmThroughput is present, so a request without WarmThroughput is never -/// refused by this function. `VectorIndexUpdates` is an ExtendDB extension and -/// is grouped with the WarmThroughput sentence, unmeasured. `AttributeDefinitions` -/// is not an operation. +/// on their own, without WarmThroughput (measured); ExtendDB applies it +/// elsewhere only to TableClass and DeletionProtection beside a stream change, +/// in the engine's UpdateTable handler. Here the companion's own sentence is +/// used only when WarmThroughput is present, so a request without +/// WarmThroughput is never refused by this function. `VectorIndexUpdates` is +/// an ExtendDB extension and is grouped with the WarmThroughput sentence, +/// unmeasured. `AttributeDefinitions` is not an operation. /// /// # Errors /// diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index fdc2191ab..1c6a083ab 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -161,39 +161,24 @@ pub async fn handle_update_table( crate::gsi_updates::validate_gsi_updates(&input)?; - // A stream change travels alone. Measured 2026-10-24: beside BillingMode or - // ProvisionedThroughput the service refuses with the IOPS sentence, beside - // any GlobalSecondaryIndexUpdates entry with the index sentence, and - // applies nothing. The per-index definition checks above come first, and - // the already-enabled refusal (`Table already has an enabled stream`) comes - // before the IOPS sentence, so the table's stored specification is read - // here when a companion change is present. DeletionProtectionEnabled beside - // a stream change is refused with the service's only-operation sentence - // (measured 2026-10-24); the general rule for DeletionProtection beside any - // other change is PR #474's and is not claimed here. TableClass and - // OnDemandThroughput beside a stream change are not measured and stay - // accepted. - if let Some(companion) = stream_change_companion(&input) { - let existing = ctx - .storage - .describe_table( - &ctx.account_id, - extenddb_core::types::DescribeTableInput { - table_name: input.table_name.clone(), - }, - ) - .await - .map_err(|e| update_table_err_to_dynamo(e, &input.table_name))?; - if let Some(spec) = &input.stream_specification { - extenddb_storage::stream_lineage::stream_change( - &input.table_name, - existing.stream_specification.as_ref(), - spec, - ) - .map_err(|e| update_table_err_to_dynamo(e, &input.table_name))?; - } - return Err(DynamoDbError::ValidationException(companion.to_owned())); + // A stream change is refused beside some other changes, and nothing + // applies (measured 2026-10-24 and 2026-11-11). TableClass gets its + // only-operation sentence before the table is read, as the service answers + // for a missing table. Billing or throughput (the IOPS sentence), an index + // Create or Delete (the index sentence), and an index WarmThroughput or + // DeletionProtection (their only-operation sentences) are refused by + // `stream_change_companion`, after the index checks above and the stream + // state check below. Not measured: the order of TableClass against those; + // the order of the stream state refusals against the index, WarmThroughput + // and DeletionProtection sentences (measured against the IOPS sentence and + // a bare index Update only); and OnDemandThroughput beside a stream change, + // which stays accepted. + if input.stream_specification.is_some() && input.table_class.is_some() { + return Err(DynamoDbError::ValidationException( + extenddb_core::validation::TABLE_CLASS_MUST_BE_ONLY_OPERATION.to_owned(), + )); } + let companion = stream_change_companion(&input); // A created GSI's projected attributes count toward the table's limit // together with the indexes it already has: the total CreateTable checks, @@ -219,7 +204,12 @@ pub async fn handle_update_table( // A switch to PAY_PER_REQUEST stores the on-demand minimum as the warm // throughput of a provisioned table that is below it, so it needs the table. let switches_to_on_demand = matches!(input.billing_mode, Some(BillingMode::PayPerRequest)); - if projects_attributes || touches_warm || bare_update || switches_to_on_demand { + if companion.is_some() + || projects_attributes + || touches_warm + || bare_update + || switches_to_on_demand + { let existing = ctx .storage .describe_table( @@ -230,6 +220,21 @@ pub async fn handle_update_table( ) .await .map_err(|e| update_table_err_to_dynamo(e, &input.table_name))?; + // The stream state refusals (`Table already has an enabled stream`, + // `Table has no stream to disable`) come before the companion sentence + // (measured for the IOPS one, 2026-10-24) and before a bare index + // Update's (measured 2026-11-11). + if let Some(spec) = &input.stream_specification { + extenddb_storage::stream_lineage::stream_change( + &input.table_name, + existing.stream_specification.as_ref(), + spec, + ) + .map_err(|e| update_table_err_to_dynamo(e, &input.table_name))?; + } + if let Some(companion) = companion { + return Err(DynamoDbError::ValidationException(companion.to_owned())); + } if let Some(updates) = &input.global_secondary_index_updates && projects_attributes { @@ -290,12 +295,17 @@ pub async fn handle_update_table( /// The sentence the service refuses a stream change with when the same /// `UpdateTable` also changes the table's billing or throughput, creates or -/// deletes an index, or changes deletion protection. `None` when the request -/// carries no stream change or no such companion. With both the billing and -/// the index companion present the IOPS sentence is answered (measured); the -/// deletion-protection sentence's order against the other two is not measured -/// and comes last. +/// deletes an index, sets an index's `WarmThroughput`, or changes deletion +/// protection. `None` when the request carries no stream change or no such +/// companion; an index `Update` without `WarmThroughput` is not one (measured +/// 2026-11-11). With both the billing and the index companion present the +/// IOPS sentence is answered (measured); the order of the WarmThroughput and +/// deletion-protection sentences against the others is not measured. fn stream_change_companion(input: &UpdateTableInput) -> Option<&'static str> { + use extenddb_core::validation::{ + DELETION_PROTECTION_MUST_BE_ONLY_OPERATION, INDEX_CHANGE_WITH_STREAM_CHANGE, + WARM_THROUGHPUT_MUST_BE_ONLY_OPERATION, + }; input.stream_specification.as_ref()?; if input.billing_mode.is_some() || input.provisioned_throughput.is_some() { return Some( @@ -304,17 +314,20 @@ fn stream_change_companion(input: &UpdateTableInput) -> Option<&'static str> { } if input .global_secondary_index_updates - .as_ref() - .is_some_and(|u| !u.is_empty()) + .iter() + .flatten() + .any(|u| u.create.is_some() || u.delete.is_some()) { - return Some( - "One or more parameter values were invalid: You cannot create or delete index while changing stream status", - ); + return Some(INDEX_CHANGE_WITH_STREAM_CHANGE); + } + // An index Update's, since a Create answered above; a table-level + // WarmThroughput beside a stream change is refused earlier, by + // `validate_warm_throughput_is_only_operation`. + if crate::warm_throughput::touches_warm_throughput(input) { + return Some(WARM_THROUGHPUT_MUST_BE_ONLY_OPERATION); } if input.deletion_protection_enabled.is_some() { - return Some( - "One or more parameter values were invalid: DeletionProtection modification must be the only operation in the request", - ); + return Some(DELETION_PROTECTION_MUST_BE_ONLY_OPERATION); } None } diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs index c31c3bfbd..0670fe366 100644 --- a/crates/engine/src/update_table_tests.rs +++ b/crates/engine/src/update_table_tests.rs @@ -7,11 +7,16 @@ use super::*; use extenddb_storage::error::StorageError; /// Measured 2026-10-24: a stream change beside a billing or throughput -/// change, beside an index create or delete, or beside a deletion protection -/// change is refused with its own sentence; alone it is not. +/// change, beside an index create, or beside a deletion protection change is +/// refused with its own sentence; alone it is not. Measured 2026-11-11: +/// beside an index delete it answers the index sentence, beside an index +/// Update carrying WarmThroughput the WarmThroughput sentence, and beside an +/// index Update of ProvisionedThroughput it is not refused. A Create beside an +/// Update (not measured) answers the index sentence: any Create or Delete +/// decides it. #[test] -fn a_stream_change_travels_alone() { - let with = |extra: Value| -> UpdateTableInput { +fn a_stream_change_refuses_its_companions() { + let with = |extra: &Value| -> UpdateTableInput { let mut body = serde_json::json!({ "TableName": "t", "StreamSpecification": {"StreamEnabled": false}, @@ -23,41 +28,55 @@ fn a_stream_change_travels_alone() { }; let iops = "One or more parameter values were invalid: You cannot modify stream status while updating table IOPS"; let index = "One or more parameter values were invalid: You cannot create or delete index while changing stream status"; - assert_eq!( - stream_change_companion(&with(serde_json::json!({"BillingMode": "PROVISIONED"}))), - Some(iops) - ); - assert_eq!( - stream_change_companion(&with(serde_json::json!({ - "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5} - }))), - Some(iops) - ); - assert_eq!( - stream_change_companion(&with(serde_json::json!({ - "GlobalSecondaryIndexUpdates": [{"Delete": {"IndexName": "g"}}] - }))), - Some(index) - ); - assert_eq!( - stream_change_companion(&with(serde_json::json!({ - "GlobalSecondaryIndexUpdates": [{"Create": { + let warm = "One or more parameter values were invalid: WarmThroughput must be the only operation in the request"; + let protection = "One or more parameter values were invalid: DeletionProtection modification must be the only operation in the request"; + let units = serde_json::json!({"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}); + let create = serde_json::json!({"Create": { + "IndexName": "g", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"} + }}); + let gsi = |update: Value| serde_json::json!({"GlobalSecondaryIndexUpdates": [update]}); + for (extra, expected) in [ + ( + serde_json::json!({"BillingMode": "PROVISIONED"}), + Some(iops), + ), + ( + serde_json::json!({"ProvisionedThroughput": units}), + Some(iops), + ), + ( + gsi(serde_json::json!({"Delete": {"IndexName": "g"}})), + Some(index), + ), + (gsi(create.clone()), Some(index)), + ( + serde_json::json!({"GlobalSecondaryIndexUpdates": [ + create, + {"Update": {"IndexName": "h", "ProvisionedThroughput": units}} + ]}), + Some(index), + ), + ( + gsi(serde_json::json!({"Update": {"IndexName": "g", "ProvisionedThroughput": units}})), + None, + ), + ( + gsi(serde_json::json!({"Update": { "IndexName": "g", - "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], - "Projection": {"ProjectionType": "ALL"} - }}] - }))), - Some(index) - ); - assert_eq!(stream_change_companion(&with(serde_json::json!({}))), None); - assert_eq!( - stream_change_companion(&with( - serde_json::json!({"DeletionProtectionEnabled": true}) - )), - Some( - "One or more parameter values were invalid: DeletionProtection modification must be the only operation in the request" - ) - ); + "WarmThroughput": {"ReadUnitsPerSecond": 5, "WriteUnitsPerSecond": 5} + }})), + Some(warm), + ), + ( + serde_json::json!({"DeletionProtectionEnabled": true}), + Some(protection), + ), + (serde_json::json!({}), None), + ] { + assert_eq!(stream_change_companion(&with(&extra)), expected, "{extra}"); + } let no_stream: UpdateTableInput = serde_json::from_value(serde_json::json!({"TableName": "t", "BillingMode": "PROVISIONED"})) .unwrap(); diff --git a/crates/storage-sqlite/src/stream_lifecycle_tests.rs b/crates/storage-sqlite/src/stream_lifecycle_tests.rs index d35b88da5..77cf38b39 100644 --- a/crates/storage-sqlite/src/stream_lifecycle_tests.rs +++ b/crates/storage-sqlite/src/stream_lifecycle_tests.rs @@ -480,3 +480,42 @@ async fn a_disable_refused_on_a_disabled_stream_closes_the_shards_it_left_open() assert_eq!(closed_by_enable, 4); engine.pool.close().await; } + +/// A refused disable writes none of the request's other members, on a table +/// that never had a stream (the transaction rolls back) and on one whose +/// stream is already disabled (the transaction commits the shard close). The +/// engine refuses TableClass beside a stream change before storage is +/// reached; OnDemandThroughput reaches this path through it. +#[tokio::test] +async fn a_refused_disable_writes_no_other_member() { + let engine = engine().await; + create(&engine, "never", false).await; + create(&engine, "off", true).await; + set_stream(&engine, "off", serde_json::json!({"StreamEnabled": false})) + .await + .unwrap(); + for name in ["never", "off"] { + let input = serde_json::json!({ + "TableName": name, + "StreamSpecification": {"StreamEnabled": false}, + "TableClass": "STANDARD_INFREQUENT_ACCESS", + "OnDemandThroughput": {"MaxReadRequestUnits": 100, "MaxWriteRequestUnits": 100}, + }); + match engine + .update_table(ACCOUNT, serde_json::from_value(input).unwrap()) + .await + { + Err(StorageError::Validation(m)) => { + assert_eq!( + m, + format!("Table has no stream to disable: TableName: {name}") + ); + } + other => panic!("{name}: {other:?}"), + } + let table = describe_table(&engine, name).await; + assert_eq!(table.table_class_summary, None, "{name}"); + assert_eq!(table.on_demand_throughput, None, "{name}"); + } + engine.pool.close().await; +} diff --git a/crates/storage-sqlite/src/update_table.rs b/crates/storage-sqlite/src/update_table.rs index 3c8878139..7e706674b 100644 --- a/crates/storage-sqlite/src/update_table.rs +++ b/crates/storage-sqlite/src/update_table.rs @@ -269,6 +269,26 @@ impl SqliteEngine { } } + // The stream change is decided before any other column is written, so a + // refused one writes nothing else. A disable of an already disabled + // stream is refused, and the transaction then holds only the close of + // the shards the first disable left open, which is committed. + if let Some(spec) = &input.stream_specification + && let Some(refusal) = Self::apply_stream_specification( + &mut tx, + account_id, + &input.table_name, + &table_id, + spec, + ) + .await? + { + tx.commit() + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + return Err(refusal); + } + if let Some(bm) = &input.billing_mode { let s = match bm { BillingMode::Provisioned => "PROVISIONED", @@ -314,24 +334,6 @@ impl SqliteEngine { ) .await?; } - if let Some(spec) = &input.stream_specification - && let Some(refusal) = Self::apply_stream_specification( - &mut tx, - account_id, - &input.table_name, - &table_id, - spec, - ) - .await? - { - // A disable of an already disabled stream: the request is refused, - // and the transaction holds only the close of the shards the first - // disable left open (a stream change travels alone in the request). - tx.commit() - .await - .map_err(|e| StorageError::Internal(e.to_string()))?; - return Err(refusal); - } // WarmThroughput on the table and on updated indexes: stored as sent, // nothing acts on it. Validated by the engine against the current values. diff --git a/docs/design/07-component-streams.md b/docs/design/07-component-streams.md index 47d7bdeb1..55a2caf93 100755 --- a/docs/design/07-component-streams.md +++ b/docs/design/07-component-streams.md @@ -99,7 +99,7 @@ Each stream's identity is carried in its shard ids, `shardId-{table_id}-{label_m On Cassandra the write paths compute a record's partition from the table id and partition key alone, inside the data write's LOGGED BATCH, so records stay in one partition per shard index and a stream's shard is a range of that partition: after its `StartingSequenceNumber`, up to its `EndingSequenceNumber` once closed. A new stream's shards start one above the larger of the enabling server's next clock value and the last `EndingSequenceNumber` among the table's shards. -A stream change travels alone: an `UpdateTable` that carries `StreamSpecification` beside `BillingMode` or `ProvisionedThroughput` is refused with `You cannot modify stream status while updating table IOPS`, beside any `GlobalSecondaryIndexUpdates` entry with `You cannot create or delete index while changing stream status`, and nothing is applied. A table created with `StreamSpecification {StreamEnabled: false}` stores nothing of it. +A stream change travels alone: an `UpdateTable` that carries `StreamSpecification` beside `BillingMode` or `ProvisionedThroughput` is refused with `You cannot modify stream status while updating table IOPS`, beside an index `Create` or `Delete` with `You cannot create or delete index while changing stream status`, beside an index `Update` that carries `WarmThroughput` with `WarmThroughput must be the only operation in the request`, and beside `TableClass` with `TableClass modification must be the only operation in the request`; nothing is applied. The service accepts an index `Update` of `ProvisionedThroughput` beside a stream change; ExtendDB answers that request as it answers the Update alone (#716). A table created with `StreamSpecification {StreamEnabled: false}` stores nothing of it. Writes racing a disable. The service's rule (measured 2026-10-24, 569 writes against one disable): every write accepted before the stream reports `DISABLED` lands in the closed stream before its shard's `EndingSequenceNumber`, and a write after that records nothing. ExtendDB closes the shards in the `UpdateTable` call. On SQLite the engine write lock serialises the close against every write. On PostgreSQL the write path reads the open shards without a lock. It locks the one shard its record goes to `FOR KEY SHARE`, re-checks that the shard is still open, and stores the record in `stream_pending`. The record gets its sequence number after the write commits. The close runs in one READ COMMITTED data transaction. It locks the open rows `FOR UPDATE`, numbers the pending records of each shard it locked, and then takes the ending numbers. The record of a write that locked its row before the close therefore gets a number at or below the ending number. A later write finds the row closed and records nothing. Before that transaction, the close numbers each shard's backlog in the numbering worker's batches. Writers do not wait for the row lock of those batches, so a write waits only while the close numbers the records committed in between. The close locks the rows in shard id order, and `TransactWriteItems` stores its records in the same order, so the two cannot deadlock. On Cassandra a new stream's shards start one above the larger of the enabling server's next clock value and the last `EndingSequenceNumber` among the table's shards, so on one server a write of the closed stream that commits after the close falls between the old shard's ending number and the new shard's starting number and is read by neither stream (the sequence is drawn in the write's LOGGED BATCH, which the close cannot wait for). A record of the old stream committed before the close by a server whose clock is ahead of the enabling server's is in the closed shard's ending number, so it is below the start and in one stream only; with several servers, a raced record from a server whose clock is ahead can land above the start, in the new stream. A server whose clock is behind the start can write a new-stream record below it, which no stream reads. Both cases are part of the deferred cross-instance consistency item below. On MongoDB the window is one write transaction wide: a write whose transaction read the shard as open and commits after the close lands past the ending number; closing the gap needs the write transaction to touch the shard document and the stream path to classify the resulting write conflict as retryable, which it does not today. On every backend a write that found no open shard because its key info pre-dated the disable is acknowledged and recorded in no stream; the service records every write it acknowledges while the disable is in progress. A table toggled many times accumulates four closed shard rows per cycle; nothing sweeps a live table's closed shards. On PostgreSQL, MongoDB and Cassandra an enable commits its catalog row before inserting its shards, so a disable that reads the row in between closes whatever shards exist at that instant; the enable re-reads the row after its inserts and closes its own shards when the row no longer says enabled with its label, so a stream never reports `DISABLED` with open shards. diff --git a/tests/python/test_stream_disable_fold.py b/tests/python/test_stream_disable_fold.py index 9620a0954..a99807d56 100644 --- a/tests/python/test_stream_disable_fold.py +++ b/tests/python/test_stream_disable_fold.py @@ -7,7 +7,8 @@ paging over a table with two streams; GetShardIterator on an unknown shard or stream; a table created with StreamSpecification {StreamEnabled: false}. Companion to test_stream_disable.py. One module fixture runs the measured -sequence once; each test asserts one row. +sequence once; each test asserts one row. F5, measured on 2026-11-11, is one +data table run against a provisioned table of its own. """ from __future__ import annotations @@ -21,11 +22,13 @@ from botocore.exceptions import ClientError from helpers import unique_name, wait_for_active, wait_for_deleted +from warm_throughput_helpers import ONLY_OPERATION, TABLE_CLASS_ONLY, _wait_all_active KEYS_ONLY = {"StreamEnabled": True, "StreamViewType": "KEYS_ONLY"} NEW_IMAGE = {"StreamEnabled": True, "StreamViewType": "NEW_IMAGE"} DISABLED = {"StreamEnabled": False} INVALID = "One or more parameter values were invalid: " +INDEX_CHANGE = INVALID + "You cannot create or delete index while changing stream status" ON_SERVICE = not os.environ.get("DYNAMODB_ENDPOINT", "").strip() @@ -201,11 +204,7 @@ def test_a_stream_change_beside_a_billing_change_is_refused(run): def test_a_stream_change_beside_an_index_create_is_refused(run): - _refused( - run["disable_plus_gsi"], - "ValidationException", - INVALID + "You cannot create or delete index while changing stream status", - ) + _refused(run["disable_plus_gsi"], "ValidationException", INDEX_CHANGE) def test_the_index_definition_check_precedes_the_companion_rule(run): @@ -327,3 +326,131 @@ def test_enabling_it_creates_the_first_stream(run): after = run["off_after_enable"] assert after["StreamSpecification"] == KEYS_ONLY assert after["LatestStreamArn"] == desc["LatestStreamArn"] + + +# F5: a stream change beside an index or table class change, measured on +# 2026-11-11 on a PROVISIONED 1/1 table with one GSI (1/1) and a KEYS_ONLY +# stream. Each row brings the stream to the state it was measured in, sends +# the request, and checks the answer and the table once it is ACTIVE. + +NO_INDEX_THROUGHPUT = pytest.mark.xfail( + not ON_SERVICE, + strict=True, + reason="ExtendDB does not change an index's ProvisionedThroughput " + "(UpdateGlobalSecondaryIndex is not yet supported)", +) + +# (stream enabled before, StreamSpecification sent, change beside it, refusal +# with {name} for the table, or None when the service accepts the request and +# applies both changes) +COMPANION_ROWS = [ + pytest.param(True, DISABLED, "index delete", INDEX_CHANGE, id="index-delete"), + pytest.param(True, DISABLED, "table class", TABLE_CLASS_ONLY, id="table-class"), + pytest.param( + False, DISABLED, "table class", TABLE_CLASS_ONLY, id="table-class-already-disabled" + ), + pytest.param(True, DISABLED, "index warm", ONLY_OPERATION, id="index-warm-disable"), + pytest.param(False, NEW_IMAGE, "index warm", ONLY_OPERATION, id="index-warm-enable"), + pytest.param( + True, DISABLED, "index units", None, id="index-units-disable", marks=NO_INDEX_THROUGHPUT + ), + pytest.param( + False, NEW_IMAGE, "index units", None, id="index-units-enable", marks=NO_INDEX_THROUGHPUT + ), + pytest.param( + False, DISABLED, "index units", "Table has no stream to disable: TableName: {name}", + id="index-units-no-stream-to-disable", + ), + pytest.param( + True, NEW_IMAGE, "index units", "Table already has an enabled stream: TableName: {name}", + id="index-units-already-enabled", + ), +] + + +@pytest.fixture(scope="module") +def provisioned(dynamodb_client): + ddb = dynamodb_client + name = unique_name("f515") + units = {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1} + ddb.create_table( + TableName=name, + AttributeDefinitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, + ], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PROVISIONED", + ProvisionedThroughput=units, + GlobalSecondaryIndexes=[{ + "IndexName": "gsi", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + "ProvisionedThroughput": units, + }], + StreamSpecification=KEYS_ONLY, + ) + _wait_all_active(ddb, name) + try: + yield name + finally: + try: + ddb.delete_table(TableName=name) + wait_for_deleted(ddb, name) + except ClientError: + pass + + +def _stream_enabled(table: dict) -> bool: + return table.get("StreamSpecification", {}).get("StreamEnabled", False) + + +def _table_class(table: dict) -> str: + return table.get("TableClassSummary", {}).get("TableClass", "STANDARD") + + +def _index_units(table: dict) -> list: + return [(g["IndexName"], g["ProvisionedThroughput"]) for g in table["GlobalSecondaryIndexes"]] + + +def _change(change: str, gsi: dict) -> dict: + """The request members of `change`, from the index as it is now: the + current WarmThroughput, or one more read and write unit.""" + if change == "table class": + return {"TableClass": "STANDARD_INFREQUENT_ACCESS"} + if change == "index delete": + return {"GlobalSecondaryIndexUpdates": [{"Delete": {"IndexName": "gsi"}}]} + if change == "index warm": + warm = gsi["WarmThroughput"] + update = {"WarmThroughput": {k: warm[k] for k in ("ReadUnitsPerSecond", "WriteUnitsPerSecond")}} + else: + n = gsi["ProvisionedThroughput"]["ReadCapacityUnits"] + 1 + update = {"ProvisionedThroughput": {"ReadCapacityUnits": n, "WriteCapacityUnits": n}} + return {"GlobalSecondaryIndexUpdates": [{"Update": {"IndexName": "gsi", **update}}]} + + +@pytest.mark.parametrize("before, stream, change, refusal", COMPANION_ROWS) +def test_a_stream_change_beside_an_index_or_table_class_change( + dynamodb_client, provisioned, before, stream, change, refusal +): + ddb = dynamodb_client + table = _wait_all_active(ddb, provisioned) + if _stream_enabled(table) != before: + _set_stream(ddb, provisioned, KEYS_ONLY if before else DISABLED) + table = _wait_all_active(ddb, provisioned) + if _table_class(table) != "STANDARD": + ddb.update_table(TableName=provisioned, TableClass="STANDARD") + table = _wait_all_active(ddb, provisioned) + members = _change(change, table["GlobalSecondaryIndexes"][0]) + row = _call(ddb.update_table, TableName=provisioned, StreamSpecification=stream, **members) + after = _wait_all_active(ddb, provisioned) + if refusal is not None: + _refused(row, "ValidationException", refusal.format(name=provisioned)) + assert _stream_enabled(after) == before + assert _index_units(after) == _index_units(table) + assert _table_class(after) == "STANDARD" + return + assert row["status"] == 200, row + assert _stream_enabled(after) == stream["StreamEnabled"] + sent = members["GlobalSecondaryIndexUpdates"][0]["Update"]["ProvisionedThroughput"] + assert {k: after["GlobalSecondaryIndexes"][0]["ProvisionedThroughput"][k] for k in sent} == sent