From 19809410e9cadeced187a94a2eca23117f0d764f Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Mon, 29 Jun 2026 19:49:45 +0000 Subject: [PATCH 01/11] docs: add RFC draft for Cloud Bigtable storage backend Proposes the design of a production-grade Cloud Bigtable storage backend for ExtendDB. Key items include a Lock-then-Read 2PC transaction flow, sharded TTL indexing shadow table, GSI projection enforcement, and secure GCP authentication config. --- docs/rfcs/0000-bigtable-backend.md | 168 +++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 docs/rfcs/0000-bigtable-backend.md diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md new file mode 100644 index 000000000..a7f4c172c --- /dev/null +++ b/docs/rfcs/0000-bigtable-backend.md @@ -0,0 +1,168 @@ +# RFC-0003: Cloud Bigtable Storage Backend for ExtendDB + +- Status: Draft +- Author: @annguy3n +- Created: 2026-06-29 +- Tracking issue: #185 + +## Summary + +This RFC defines the design and implementation of a production-grade Cloud Bigtable storage backend for ExtendDB. It addresses critical architectural requirements for this new backend: transaction isolation, stream emissions in transactions, Global Secondary Index (GSI) projections, GSI write consistency, Time-to-Live (TTL) eviction scalability, and secure Google Cloud Platform (GCP) connectivity. + +## Motivation + +A naive mapping of DynamoDB structures to Bigtable introduces several architectural challenges that must be addressed to ensure production-readiness: +1. **Transaction Isolation Leak:** Non-transactional (single-row) writes bypass 2-Phase Commit (2PC) locks (intents), enabling dirty writes and lost updates. +2. **2PC Race Condition (Read-then-Lock):** The 2PC coordinator reads row data before placing locks, exposing the system to Time-of-Check to Time-of-Use (TOCTOU) races. +3. **Missing Transaction Streams:** Multi-row transactions (`TransactWriteItems`) do not emit DynamoDB Stream records. +4. **Inefficient TTL Eviction:** The TTL worker performs full-table scans to identify expired items, which degrades performance on large datasets. +5. **GSI Consistency Gap:** GSI shadow table write failures are logged without retry or repair, causing permanent base-to-shadow divergence. +6. **Auth Configuration Constraints:** Lack of support for explicit credentials file configuration. + +This RFC provides the technical specification to resolve these challenges. + +## Detailed Design + +### 1. Table Mapping & Naming Constraints + +* **Catalog:** System metadata, accounts, and policies are stored in a single table named `__extenddb_catalog__`. +* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is a 32-character hex UUID). Data attributes are stored in column family `d`. +* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name). +* **Transaction Intents:** Column family `m` in data tables stores lock/intent cells. +* **TTL Markers:** Column family `t` (reserved). + +> [!NOTE] +> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (43 characters total) rather than reproducing the full index name. + +### 2. Transaction Isolation & 2PC Refactoring + +#### A. Lock-then-Read 2PC Flow +Refactor the `TransactWriteItems` coordinator to acquire locks *before* reading data and evaluating condition expressions. + +```mermaid +sequenceDiagram + participant C as Coordinator (ExtendDB) + participant B as Bigtable + + C->>B: Phase 1: Open Transaction (Write PENDING to __extenddb_txn_log__) + Note over C,B: Place Intents (Locks) + loop For each participant row + C->>B: Place Intent (CheckAndMutateRow: fail if other fresh intent exists) + end + alt Any Lock Fails + C->>B: Rollback (Clear placed intents, drop txn row) + Note over C: Return TransactionConflict + end + Note over C,B: Read & Verify + C->>B: Read participant rows (now locked by us) + Note over C: Evaluate Condition Expressions + alt Any Condition Fails + C->>B: Rollback (Clear intents, drop txn row) + Note over C: Return TransactionCanceled + end + C->>B: Phase 2: Commit Transaction (Write COMMITTED to __extenddb_txn_log__) + Note over C,B: Apply Mutations + loop For each participant row + C->>B: Apply Data Mutations & Clear Intent (Atomic MutateRow) + end + C->>B: Phase 3: Clean up (Write CLEANED to log, then drop txn row) +``` + +#### B. Guarding Single-Row Writes +All single-row mutations (`PutItem`, `UpdateItem`, `DeleteItem`) must run via `CheckAndMutateRow` to prevent overwriting active 2PC locks: +* **Predicate:** Matches if a cell exists in family `m` with qualifier `intent:*` and a timestamp $\ge$ `now - intent_timeout`. +* **False Mutations (No Lock):** Execute the mutation. +* **True Mutations (Locked):** None. Returns `TransactionConflict` (client retries). +* **Deletes:** Use `DeleteFromFamily(d)` instead of `DeleteFromRow` to preserve the intent family `m`. + +#### C. Recovery Sweeper +A background worker periodically scans `__extenddb_txn_log__` for transactions older than `intent_timeout`: +* **`PENDING` State:** Clear intents on participant rows and delete the coordinator row (rollback). +* **`COMMITTED` State:** Re-apply mutations to participant rows, write stream records, clear intents, and delete the coordinator row (roll-forward). + +### 3. Stream Emissions in Transactions + +To ensure stream record atomicity: +1. **Phase 1 Resolution:** Fetch the full `TableDescription` (including `StreamSpecification` and `latest_stream_arn`) and pre-generate the `StreamRecord` payloads. +2. **Log Enrichment:** Store the pre-generated stream record payloads in the coordinator row of `__extenddb_txn_log__` in Phase 2. +3. **Phase 5 Commit:** Write the pre-generated stream records to the stream table alongside the data mutations. +4. **Recovery:** The recovery sweeper uses the payloads stored in the log to roll forward stream writes on crash. + +### 4. Scalable TTL Indexing + +Avoid full-table scans by introducing a sharded TTL index table. + +#### A. TTL Index Table Schema +* **Table Name:** `__extenddb_ttl_index__` +* **Row Key format (Binary):** `[shard_id:1] [expiry_timestamp_be:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` + * `shard_id` (1 byte): `hash(base_row_key) % 16` (prevents write hotspotting). + * `expiry_timestamp_be` (8 bytes): Big-Endian `u64` representing the TTL epoch second. + * `encoded_base_row_key` (variable): Raw row key of the target item. +* **Payload:** None (empty values). + +#### B. Maintenance +* **Writes:** Insert an empty row in `__extenddb_ttl_index__` when writing an item with a TTL attribute. +* **Updates/Deletes:** Delete the old index entry using the item's prior image. + +#### C. Sweeper Flow +1. Perform parallel range scans across all 16 shards from `start_key = [S] [0]` to `end_key = [S] [current_time_epoch_s + 1]`. +2. For each expired entry, read the base row and verify its current TTL matches the index entry. +3. If valid, execute `delete_item` on the base table. +4. If invalid (stale index), delete the index entry. + +### 5. GSI Projections & Consistency + +#### A. Projection Validation +Enforce DynamoDB GSI projection behavior: +* **Read Path:** Queries on GSIs with `KEYS_ONLY` or `INCLUDE` projections return only the projected attributes. +* **Validation:** If the client requests `Select: ALL_ATTRIBUTES` (or requests non-projected attributes) on a non-`ALL` GSI, return `ValidationException`. Do not perform base table fetches. +* **Defaulting:** If `Select` is omitted in a GSI query, default to `Select::AllProjectedAttributes`. + +#### B. Background Reconciler +Implement a reconciler as an internal background worker spawned via `RuntimeHooks`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows. + +### 6. GCP Credentials Configuration + +Extend `BigtableStorageConfig` to support explicit service account files: + +```toml +[storage.bigtable] +project_id = "my-project" +instance_id = "my-instance" +data_instance_id = "my-data-instance" # Optional +credentials_path = "/path/to/sa-key.json" # Optional +pool_size = 20 +``` + +* **Behavior:** If `credentials_path` is specified, the server programmatically sets the `GOOGLE_APPLICATION_CREDENTIALS` environment variable before client initialization. Configure `tonic` channels with `ClientTlsConfig` using native system roots. + +### 7. Implementation Sketch + +* **`config.rs`**: Add `credentials_path` and `data_instance_id` to config. +* **`client.rs` & `admin.rs`**: Configure TLS and inject bearer tokens. +* **`item_ops.rs`**: Update mutations to use `CheckAndMutateRow` and target deletes to the `d` family. +* **`transact.rs`**: Refactor `TxnCoordinator` to Lock-then-Read and implement the recovery sweeper. +* **`engine.rs`**: Update `transact_write_items`, GSI retry tasks, and stream record writes. +* **`ttl_worker.rs`**: Implement sharded TTL sweeps. +* **`gsi_reconciler.rs`**: Implement background GSI reconciliation. + +## Testing Strategy + +1. **Unit Tests (Emulator-based):** + * Verify type encoding/decoding and lexicographical sorting of numeric keys. + * Mock Bigtable client to verify 2PC coordinator state transitions. + * Assert `ValidationException` is returned for invalid GSI attribute requests. +2. **Failure Integration Tests (Real Bigtable & Emulator):** + * Inject crashes during the 2PC flow and assert that the recovery sweeper rolls forward/back and preserves stream record writes. + * Run concurrent mixed workloads to verify transactional serializability. + * Verify GSI reconciler heals base-to-shadow mismatches. + * Verify TTL sweeper ignores updated items with old index entries. +3. **E2E & Chaos Tests:** + * Run the Python integration suite (`devtools/run-tests --extenddb --pytest`) against production Bigtable. + * Inject network partitions during `TransactWriteItems` to verify 2PC resilience. + +## Alternatives Considered + +* **Unprotected Single-Row Writes:** Bypassing intent checks for single-row writes allows dirty writes, violating serializability. Rejected. +* **Scan-Based TTL Sweeper:** Scanning the entire base table to evict items degrades performance at scale. Rejected. +* **Cloud Spanner Backend:** Cloud Spanner supports multi-row transactions natively, eliminating the need for application-layer 2PC. This is a viable alternative to be explored as a separate backend connector. From 78e1f77e2458f7319f8a021fd2e5ab1fcd73a49a Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Tue, 11 Aug 2026 13:13:04 +0000 Subject: [PATCH 02/11] docs(rfc): update RFC with maintainer feedback clarifications - Promoted exact decimal number key encoding to core design specification. - Documented TransactWriteItems ClientRequestToken idempotency (10m) and duplicate item rejection rules. - Clarified read isolation guarantees (no dirty reads via CF 'd' snapshot writes and serializable TransactGetItems). - Documented TTL sweeper REMOVE stream emission with service principal identity. - Added explicit ConsistentRead=true rejection on GSIs. - Called out cross-row visibility in apply window and PITR retention differences. --- docs/rfcs/0000-bigtable-backend.md | 64 +++++++++++++++++++----------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index a7f4c172c..dc59fd6e3 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -23,8 +23,9 @@ This RFC provides the technical specification to resolve these challenges. ## Detailed Design -### 1. Table Mapping & Naming Constraints +### 1. Table Mapping & Key Encoding +#### A. Table Structure & Naming * **Catalog:** System metadata, accounts, and policies are stored in a single table named `__extenddb_catalog__`. * **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is a 32-character hex UUID). Data attributes are stored in column family `d`. * **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name). @@ -34,10 +35,23 @@ This RFC provides the technical specification to resolve these challenges. > [!NOTE] > **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (43 characters total) rather than reproducing the full index name. -### 2. Transaction Isolation & 2PC Refactoring +#### B. Exact Decimal & Order-Preserving Key Encoding +Cloud Bigtable sorts row keys by raw byte lexicographical order. To maintain exact DynamoDB semantics: +* **String & Binary Keys:** Encoded verbatim with null-byte / length-prefixed terminators to preserve lexicographical sort order. +* **Number Keys:** DynamoDB supports numeric values with up to 38 significant digits and requires numerical sorting (e.g., `-10 < -2 < 0 < 1.5 < 2 < 100`). Numbers are stored as exact arbitrary-precision decimals (never floating point floats) using an order-preserving byte encoding: + * **Negative numbers:** Sign byte `0x00`, followed by bit-inverted exponent and complement mantissa bytes. + * **Zero:** Exactly `[0x80]`. + * **Positive numbers:** Sign byte `0x81`, followed by big-endian exponent bytes and binary-coded decimal mantissa bytes. +* **GSI Index Row Keys:** Primary keys in GSI shadow tables are formatted as `[pk_val]\0[sk_val]\0[base_pk_val]\0[base_sk_val]`, ensuring exact numeric/string sort parity and uniqueness. -#### A. Lock-then-Read 2PC Flow -Refactor the `TransactWriteItems` coordinator to acquire locks *before* reading data and evaluating condition expressions. +### 2. Transaction Rules & Isolation Guarantees + +#### A. Transaction Validation & Idempotency Rules +* **`ClientRequestToken` Idempotency:** `TransactWriteItems` enforces idempotency within a 10-minute sliding window. Requests with an active or recently committed token replay the committed result; conflicting requests with the same token but mismatched payload return `IdempotentParameterMismatchException`. +* **Duplicate Participant Rejection:** A single `TransactWriteItems` request cannot contain multiple operations on the same item. Any transaction with duplicate primary keys is rejected upfront with `ValidationException`. + +#### B. Lock-then-Read 2PC Flow +Refactor the `TransactWriteItems` coordinator to acquire locks *before* reading data and evaluating condition expressions: ```mermaid sequenceDiagram @@ -68,14 +82,19 @@ sequenceDiagram C->>B: Phase 3: Clean up (Write CLEANED to log, then drop txn row) ``` -#### B. Guarding Single-Row Writes +#### C. Read Isolation & Concurrency Guarantees +* **Read Committed (No Dirty Reads):** In Phase 3, the coordinator only writes intent lock markers to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 7** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. +* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically. Before reading data rows, it checks for active intent markers in column family `m`. If an active lock is present, it coordinates with `__extenddb_txn_log__` to observe the snapshot at the transaction commit boundary, preventing dirty or partial reads. +* **Cross-Row Visibility for Standard Reads:** During the 2PC apply window (Phase 7), standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. + +#### D. Guarding Single-Row Writes All single-row mutations (`PutItem`, `UpdateItem`, `DeleteItem`) must run via `CheckAndMutateRow` to prevent overwriting active 2PC locks: * **Predicate:** Matches if a cell exists in family `m` with qualifier `intent:*` and a timestamp $\ge$ `now - intent_timeout`. * **False Mutations (No Lock):** Execute the mutation. * **True Mutations (Locked):** None. Returns `TransactionConflict` (client retries). * **Deletes:** Use `DeleteFromFamily(d)` instead of `DeleteFromRow` to preserve the intent family `m`. -#### C. Recovery Sweeper +#### E. Recovery Sweeper A background worker periodically scans `__extenddb_txn_log__` for transactions older than `intent_timeout`: * **`PENDING` State:** Clear intents on participant rows and delete the coordinator row (rollback). * **`COMMITTED` State:** Re-apply mutations to participant rows, write stream records, clear intents, and delete the coordinator row (roll-forward). @@ -88,7 +107,7 @@ To ensure stream record atomicity: 3. **Phase 5 Commit:** Write the pre-generated stream records to the stream table alongside the data mutations. 4. **Recovery:** The recovery sweeper uses the payloads stored in the log to roll forward stream writes on crash. -### 4. Scalable TTL Indexing +### 4. Scalable TTL Indexing & Streams Integration Avoid full-table scans by introducing a sharded TTL index table. @@ -104,22 +123,24 @@ Avoid full-table scans by introducing a sharded TTL index table. * **Writes:** Insert an empty row in `__extenddb_ttl_index__` when writing an item with a TTL attribute. * **Updates/Deletes:** Delete the old index entry using the item's prior image. -#### C. Sweeper Flow +#### C. Sweeper Flow & Stream Emission 1. Perform parallel range scans across all 16 shards from `start_key = [S] [0]` to `end_key = [S] [current_time_epoch_s + 1]`. 2. For each expired entry, read the base row and verify its current TTL matches the index entry. 3. If valid, execute `delete_item` on the base table. -4. If invalid (stale index), delete the index entry. +4. **TTL Stream Records:** When DynamoDB Streams are enabled on the table, TTL deletions emit a `REMOVE` stream record containing `userIdentity.type = "Service"` and `userIdentity.principalId = "dynamodb.amazonaws.com"`, matching native DynamoDB behavior. +5. If invalid (stale index), delete the index entry. ### 5. GSI Projections & Consistency -#### A. Projection Validation +#### A. Projection Validation & ConsistentRead Rejection Enforce DynamoDB GSI projection behavior: * **Read Path:** Queries on GSIs with `KEYS_ONLY` or `INCLUDE` projections return only the projected attributes. * **Validation:** If the client requests `Select: ALL_ATTRIBUTES` (or requests non-projected attributes) on a non-`ALL` GSI, return `ValidationException`. Do not perform base table fetches. +* **ConsistentRead Rejection:** Queries on GSIs with `ConsistentRead = true` are rejected with `ValidationException` (matching DynamoDB API rules). * **Defaulting:** If `Select` is omitted in a GSI query, default to `Select::AllProjectedAttributes`. #### B. Background Reconciler -Implement a reconciler as an internal background worker spawned via `RuntimeHooks`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows. +Implement a reconciler as an internal background worker spawned via `RuntimeHooks`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows, preventing phantom records from returning during divergence windows. ### 6. GCP Credentials Configuration @@ -134,29 +155,23 @@ credentials_path = "/path/to/sa-key.json" # Optional pool_size = 20 ``` -* **Behavior:** If `credentials_path` is specified, the server programmatically sets the `GOOGLE_APPLICATION_CREDENTIALS` environment variable before client initialization. Configure `tonic` channels with `ClientTlsConfig` using native system roots. +* **Behavior:** If `credentials_path` is specified, the server programmatically acquires tokens from the service account key. Configure `tonic` channels with `ClientTlsConfig` using native system roots. -### 7. Implementation Sketch +### 7. Future Work & Non-Goals -* **`config.rs`**: Add `credentials_path` and `data_instance_id` to config. -* **`client.rs` & `admin.rs`**: Configure TLS and inject bearer tokens. -* **`item_ops.rs`**: Update mutations to use `CheckAndMutateRow` and target deletes to the `d` family. -* **`transact.rs`**: Refactor `TxnCoordinator` to Lock-then-Read and implement the recovery sweeper. -* **`engine.rs`**: Update `transact_write_items`, GSI retry tasks, and stream record writes. -* **`ttl_worker.rs`**: Implement sharded TTL sweeps. -* **`gsi_reconciler.rs`**: Implement background GSI reconciliation. +* **Backup / PITR / Export:** Point-in-Time Recovery (PITR) and automated backup snapshots are deferred to a follow-up RFC. Note that Cloud Bigtable's native backup retention windows and export capabilities will have different retention characteristics from DynamoDB's fixed 35-day PITR window. ## Testing Strategy 1. **Unit Tests (Emulator-based):** - * Verify type encoding/decoding and lexicographical sorting of numeric keys. - * Mock Bigtable client to verify 2PC coordinator state transitions. - * Assert `ValidationException` is returned for invalid GSI attribute requests. + * Verify exact decimal number key encoding/decoding and numerical sorting up to 38 significant digits. + * Mock Bigtable client to verify 2PC coordinator state transitions and idempotency token deduplication. + * Assert `ValidationException` is returned for invalid GSI attribute requests and `ConsistentRead = true` on GSIs. 2. **Failure Integration Tests (Real Bigtable & Emulator):** * Inject crashes during the 2PC flow and assert that the recovery sweeper rolls forward/back and preserves stream record writes. * Run concurrent mixed workloads to verify transactional serializability. * Verify GSI reconciler heals base-to-shadow mismatches. - * Verify TTL sweeper ignores updated items with old index entries. + * Verify TTL sweeper emits `REMOVE` stream records with the TTL principal and ignores updated items with old index entries. 3. **E2E & Chaos Tests:** * Run the Python integration suite (`devtools/run-tests --extenddb --pytest`) against production Bigtable. * Inject network partitions during `TransactWriteItems` to verify 2PC resilience. @@ -166,3 +181,4 @@ pool_size = 20 * **Unprotected Single-Row Writes:** Bypassing intent checks for single-row writes allows dirty writes, violating serializability. Rejected. * **Scan-Based TTL Sweeper:** Scanning the entire base table to evict items degrades performance at scale. Rejected. * **Cloud Spanner Backend:** Cloud Spanner supports multi-row transactions natively, eliminating the need for application-layer 2PC. This is a viable alternative to be explored as a separate backend connector. + From 12e2a4465c9a68f914e99c866690b050ea9a4c79 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Fri, 14 Aug 2026 14:30:33 +0000 Subject: [PATCH 03/11] docs(rfc): address maintainer feedback on phases, isolation, and reverse-sync spec --- docs/rfcs/0000-bigtable-backend.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index dc59fd6e3..2919d36be 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -27,22 +27,22 @@ This RFC provides the technical specification to resolve these challenges. #### A. Table Structure & Naming * **Catalog:** System metadata, accounts, and policies are stored in a single table named `__extenddb_catalog__`. -* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is a 32-character hex UUID). Data attributes are stored in column family `d`. -* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name). +* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is the first 16 hex characters of the table UUID, 17 characters total). Data attributes are stored in column family `d`. +* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name, 27 characters total). * **Transaction Intents:** Column family `m` in data tables stores lock/intent cells. * **TTL Markers:** Column family `t` (reserved). > [!NOTE] -> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (43 characters total) rather than reproducing the full index name. +> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (27 characters total) rather than reproducing the full index name. #### B. Exact Decimal & Order-Preserving Key Encoding Cloud Bigtable sorts row keys by raw byte lexicographical order. To maintain exact DynamoDB semantics: * **String & Binary Keys:** Encoded verbatim with null-byte / length-prefixed terminators to preserve lexicographical sort order. * **Number Keys:** DynamoDB supports numeric values with up to 38 significant digits and requires numerical sorting (e.g., `-10 < -2 < 0 < 1.5 < 2 < 100`). Numbers are stored as exact arbitrary-precision decimals (never floating point floats) using an order-preserving byte encoding: - * **Negative numbers:** Sign byte `0x00`, followed by bit-inverted exponent and complement mantissa bytes. + * **Negative numbers:** Sign byte `0x00`, followed by 1-byte bit-inverted biased exponent (`~exp_biased`), and 38-byte inverted mantissa digits (`9 - digit`) padded with `0x09`. * **Zero:** Exactly `[0x80]`. - * **Positive numbers:** Sign byte `0x81`, followed by big-endian exponent bytes and binary-coded decimal mantissa bytes. -* **GSI Index Row Keys:** Primary keys in GSI shadow tables are formatted as `[pk_val]\0[sk_val]\0[base_pk_val]\0[base_sk_val]`, ensuring exact numeric/string sort parity and uniqueness. + * **Positive numbers:** Sign byte `0xFF`, followed by 1-byte biased exponent (`exp_biased = sci_exp + 130`), and 38-byte normalized decimal digits padded with `0x00`. +* **GSI Index Row Keys:** Primary keys in GSI shadow tables are formatted as `[encoded_gsi_pk][encoded_gsi_sk]\xFE[encoded_base_pk][encoded_base_sk]`, reusing the exact order-preserving/length-prefixed encoding of the base table. The `0xFE` byte acts as a structural separator between the secondary and base key components, avoiding bare null-byte collisions and preserving uniqueness and sort parity. ### 2. Transaction Rules & Isolation Guarantees @@ -83,9 +83,10 @@ sequenceDiagram ``` #### C. Read Isolation & Concurrency Guarantees -* **Read Committed (No Dirty Reads):** In Phase 3, the coordinator only writes intent lock markers to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 7** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. -* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically. Before reading data rows, it checks for active intent markers in column family `m`. If an active lock is present, it coordinates with `__extenddb_txn_log__` to observe the snapshot at the transaction commit boundary, preventing dirty or partial reads. -* **Cross-Row Visibility for Standard Reads:** During the 2PC apply window (Phase 7), standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. +* **Read Committed (No Dirty Reads):** In Phase 1, the coordinator only writes intent lock markers to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 2** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. +* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically by reading all requested rows and checking for active intent markers in column family `m`. Because Bigtable lacks cross-row atomic snapshots, if *any* requested row has an active intent lock, the request immediately blocks and retries. By deferring the read until all participant locks are cleared (Phase 3), the read never observes partial transaction state, guaranteeing Serializable visibility. +* **Read-Your-Writes (Ack Point):** To guarantee that strongly-consistent `GetItem` or `Query` requests observe applied transaction data, the coordinator defers the HTTP 200 OK success acknowledgment (client ack) until *after* all Phase 2 mutations (data and streams) are definitively applied to column family `d`. +* **Cross-Row Visibility for Standard Reads:** During the 2PC apply window (Phase 2), standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. #### D. Guarding Single-Row Writes All single-row mutations (`PutItem`, `UpdateItem`, `DeleteItem`) must run via `CheckAndMutateRow` to prevent overwriting active 2PC locks: @@ -102,10 +103,9 @@ A background worker periodically scans `__extenddb_txn_log__` for transactions o ### 3. Stream Emissions in Transactions To ensure stream record atomicity: -1. **Phase 1 Resolution:** Fetch the full `TableDescription` (including `StreamSpecification` and `latest_stream_arn`) and pre-generate the `StreamRecord` payloads. -2. **Log Enrichment:** Store the pre-generated stream record payloads in the coordinator row of `__extenddb_txn_log__` in Phase 2. -3. **Phase 5 Commit:** Write the pre-generated stream records to the stream table alongside the data mutations. -4. **Recovery:** The recovery sweeper uses the payloads stored in the log to roll forward stream writes on crash. +1. **Phase 1 (Prepare):** Fetch the full `TableDescription` (including `StreamSpecification` and `latest_stream_arn`) and pre-generate the `StreamRecord` payloads. +2. **Phase 2 (Log Enrichment & Commit):** Store the pre-generated stream record payloads and participant mutation payloads in the coordinator row of `__extenddb_txn_log__` alongside `COMMITTED`, and apply stream records to `__extenddb_streams__` concurrently with data mutations. +3. **Recovery:** The recovery sweeper uses the payloads stored in the log to roll forward stream writes on crash. ### 4. Scalable TTL Indexing & Streams Integration @@ -140,7 +140,7 @@ Enforce DynamoDB GSI projection behavior: * **Defaulting:** If `Select` is omitted in a GSI query, default to `Select::AllProjectedAttributes`. #### B. Background Reconciler -Implement a reconciler as an internal background worker spawned via `RuntimeHooks`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows, preventing phantom records from returning during divergence windows. +Implement a reconciler as an internal background worker spawned via `ServerRuntimeHooks::spawn_workers`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows, preventing phantom records from returning during divergence windows. ### 6. GCP Credentials Configuration From fb18ce2e11dbe3c85c522b957f0c5114bdf1f771 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Thu, 20 Aug 2026 17:05:45 +0000 Subject: [PATCH 04/11] docs(rfc): update RFC with OCC versioning, fenced apply, GC rules, app_profile, and BackupEngine stubs --- docs/rfcs/0000-bigtable-backend.md | 115 +++++++++++++++++++---------- 1 file changed, 74 insertions(+), 41 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index 2919d36be..f0b62af73 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -7,17 +7,18 @@ ## Summary -This RFC defines the design and implementation of a production-grade Cloud Bigtable storage backend for ExtendDB. It addresses critical architectural requirements for this new backend: transaction isolation, stream emissions in transactions, Global Secondary Index (GSI) projections, GSI write consistency, Time-to-Live (TTL) eviction scalability, and secure Google Cloud Platform (GCP) connectivity. +This RFC defines the design and implementation of a production-grade Cloud Bigtable storage backend for ExtendDB. It addresses critical architectural requirements for this backend: transaction isolation, stream emissions in transactions, Global Secondary Index (GSI) projections, GSI write consistency, Time-to-Live (TTL) eviction scalability, Optimistic Concurrency Control (OCC) row versioning, fenced two-phase commit (2PC) apply, application profile single-cluster routing, and secure Google Cloud Platform (GCP) connectivity. ## Motivation A naive mapping of DynamoDB structures to Bigtable introduces several architectural challenges that must be addressed to ensure production-readiness: -1. **Transaction Isolation Leak:** Non-transactional (single-row) writes bypass 2-Phase Commit (2PC) locks (intents), enabling dirty writes and lost updates. -2. **2PC Race Condition (Read-then-Lock):** The 2PC coordinator reads row data before placing locks, exposing the system to Time-of-Check to Time-of-Use (TOCTOU) races. +1. **Transaction Isolation Leak & TOCTOU Races:** Non-transactional (single-row) conditional writes read an item and evaluate conditions without atomic concurrency control, leading to Time-of-Check to Time-of-Use (TOCTOU) races where concurrent writes can overwrite uncommitted state or bypass 2-Phase Commit (2PC) locks. +2. **2PC Race Condition (Read-then-Lock & Unfenced Apply):** Reading row data before placing locks exposes 2PC to TOCTOU races. Furthermore, applying 2PC Phase 2 mutations unconditionally without fencing against expired/aborted locks allows slow coordinators to overwrite newer state. 3. **Missing Transaction Streams:** Multi-row transactions (`TransactWriteItems`) do not emit DynamoDB Stream records. 4. **Inefficient TTL Eviction:** The TTL worker performs full-table scans to identify expired items, which degrades performance on large datasets. 5. **GSI Consistency Gap:** GSI shadow table write failures are logged without retry or repair, causing permanent base-to-shadow divergence. -6. **Auth Configuration Constraints:** Lack of support for explicit credentials file configuration. +6. **Multi-Cluster Replication & Conditional Mutations:** Cloud Bigtable rejects conditional mutations (`CheckAndMutateRow`) under multi-cluster routing with eventual consistency. +7. **Auth Configuration Constraints:** Lack of support for explicit credentials file configuration. This RFC provides the technical specification to resolve these challenges. @@ -27,22 +28,31 @@ This RFC provides the technical specification to resolve these challenges. #### A. Table Structure & Naming * **Catalog:** System metadata, accounts, and policies are stored in a single table named `__extenddb_catalog__`. -* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is the first 16 hex characters of the table UUID, 17 characters total). Data attributes are stored in column family `d`. -* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name, 27 characters total). -* **Transaction Intents:** Column family `m` in data tables stores lock/intent cells. +* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is a 32-character hex UUID). Data attributes are stored in column family `d`. +* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name). +* **Transaction Intents & OCC Versions:** Column family `m` in data tables stores lock/intent cells (`m:intent:`) and explicit OCC row versions (`m:v`). * **TTL Markers:** Column family `t` (reserved). > [!NOTE] -> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (27 characters total) rather than reproducing the full index name. +> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (43 characters total) rather than reproducing the full index name. #### B. Exact Decimal & Order-Preserving Key Encoding -Cloud Bigtable sorts row keys by raw byte lexicographical order. To maintain exact DynamoDB semantics: -* **String & Binary Keys:** Encoded verbatim with null-byte / length-prefixed terminators to preserve lexicographical sort order. -* **Number Keys:** DynamoDB supports numeric values with up to 38 significant digits and requires numerical sorting (e.g., `-10 < -2 < 0 < 1.5 < 2 < 100`). Numbers are stored as exact arbitrary-precision decimals (never floating point floats) using an order-preserving byte encoding: - * **Negative numbers:** Sign byte `0x00`, followed by 1-byte bit-inverted biased exponent (`~exp_biased`), and 38-byte inverted mantissa digits (`9 - digit`) padded with `0x09`. +Cloud Bigtable sorts row keys by raw byte lexicographical order. The maximum row key size supported by Cloud Bigtable is **4KB (4096 bytes)**, which is strictly enforced during key encoding (`row_key::encode_key`). + +Row keys are encoded using the following structured layout: +```text +Composite Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] [sk_tag:1] [sk_bytes] +PK-Only Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] +``` +Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, `0x4E` for `N`, `0x42` for `B`). + +* **Partition (HASH) Keys:** Partition keys use **length-prefixing** (`[pk_len:u32BE:4]`) preceding `[pk_bytes]`. Length prefixing is essential to delimit variable-length partition keys, prevent ambiguity/delimiter collision, and group all items sharing the same partition key contiguously within Bigtable's lexicographical keyspace. +* **Sort (RANGE) Keys:** Sort keys are stored as **raw order-preserving bytes without length prefixing**. Omitting the length prefix on sort keys is strictly mandatory: length-prefixing sort keys would sort primarily by byte-length rather than value, leading to severe sort inversion (for example, `"10"` of length 2 would sort before `"2"` of length 1, or shorter numbers would sort before longer numbers). +* **Number Encoding:** DynamoDB supports numeric values with up to 38 significant digits and requires exact numerical sorting (e.g., `-100 < -1.5 < -1 < 0 < 0.5 < 1 < 1.5 < 100`). Numbers are stored as exact arbitrary-precision decimals (never floating point floats) using an order-preserving byte encoding: + * **Negative numbers:** Sign byte `0x00`, followed by bit-inverted exponent and complement mantissa bytes. * **Zero:** Exactly `[0x80]`. - * **Positive numbers:** Sign byte `0xFF`, followed by 1-byte biased exponent (`exp_biased = sci_exp + 130`), and 38-byte normalized decimal digits padded with `0x00`. -* **GSI Index Row Keys:** Primary keys in GSI shadow tables are formatted as `[encoded_gsi_pk][encoded_gsi_sk]\xFE[encoded_base_pk][encoded_base_sk]`, reusing the exact order-preserving/length-prefixed encoding of the base table. The `0xFE` byte acts as a structural separator between the secondary and base key components, avoiding bare null-byte collisions and preserving uniqueness and sort parity. + * **Positive numbers:** Sign byte `0x81`, followed by big-endian exponent bytes and binary-coded decimal mantissa bytes. +* **GSI Index Row Keys:** Primary keys in GSI shadow tables follow the exact same encoding rules for the index partition and sort keys, formatted as `[gsi_pk_tag][gsi_pk_len][gsi_pk_bytes][gsi_sk_tag][gsi_sk_bytes][base_pk_tag][base_pk_len][base_pk_bytes][base_sk_tag][base_sk_bytes]`, ensuring full sort order preservation and primary key uniqueness. ### 2. Transaction Rules & Isolation Guarantees @@ -51,7 +61,7 @@ Cloud Bigtable sorts row keys by raw byte lexicographical order. To maintain exa * **Duplicate Participant Rejection:** A single `TransactWriteItems` request cannot contain multiple operations on the same item. Any transaction with duplicate primary keys is rejected upfront with `ValidationException`. #### B. Lock-then-Read 2PC Flow -Refactor the `TransactWriteItems` coordinator to acquire locks *before* reading data and evaluating condition expressions: +The `TransactWriteItems` coordinator acquires locks *before* reading data and evaluating condition expressions, and applies mutations via fenced CAS: ```mermaid sequenceDiagram @@ -68,37 +78,54 @@ sequenceDiagram Note over C: Return TransactionConflict end Note over C,B: Read & Verify - C->>B: Read participant rows (now locked by us) + C->>B: Read participant rows & capture row versions (m:v) Note over C: Evaluate Condition Expressions alt Any Condition Fails C->>B: Rollback (Clear intents, drop txn row) Note over C: Return TransactionCanceled end C->>B: Phase 2: Commit Transaction (Write COMMITTED to __extenddb_txn_log__) - Note over C,B: Apply Mutations + Note over C,B: Fenced Apply Mutations loop For each participant row - C->>B: Apply Data Mutations & Clear Intent (Atomic MutateRow) + C->>B: Fenced Apply (CheckAndMutateRow: if m:intent: present, write d, set m:v, delete m:intent) end C->>B: Phase 3: Clean up (Write CLEANED to log, then drop txn row) ``` #### C. Read Isolation & Concurrency Guarantees -* **Read Committed (No Dirty Reads):** In Phase 1, the coordinator only writes intent lock markers to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 2** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. -* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically by reading all requested rows and checking for active intent markers in column family `m`. Because Bigtable lacks cross-row atomic snapshots, if *any* requested row has an active intent lock, the request immediately blocks and retries. By deferring the read until all participant locks are cleared (Phase 3), the read never observes partial transaction state, guaranteeing Serializable visibility. -* **Read-Your-Writes (Ack Point):** To guarantee that strongly-consistent `GetItem` or `Query` requests observe applied transaction data, the coordinator defers the HTTP 200 OK success acknowledgment (client ack) until *after* all Phase 2 mutations (data and streams) are definitively applied to column family `d`. -* **Cross-Row Visibility for Standard Reads:** During the 2PC apply window (Phase 2), standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. - -#### D. Guarding Single-Row Writes -All single-row mutations (`PutItem`, `UpdateItem`, `DeleteItem`) must run via `CheckAndMutateRow` to prevent overwriting active 2PC locks: -* **Predicate:** Matches if a cell exists in family `m` with qualifier `intent:*` and a timestamp $\ge$ `now - intent_timeout`. -* **False Mutations (No Lock):** Execute the mutation. -* **True Mutations (Locked):** None. Returns `TransactionConflict` (client retries). -* **Deletes:** Use `DeleteFromFamily(d)` instead of `DeleteFromRow` to preserve the intent family `m`. - -#### E. Recovery Sweeper +* **Read Committed (No Dirty Reads):** In Phase 1 / Phase 2, the transaction coordinator only writes intent lock markers (`m:intent:`) to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 2 Apply** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. +* **Fenced Phase 2 Apply:** During Phase 2 Apply, participant mutations are applied via `CheckAndMutateRow` using a fencing predicate that asserts the coordinator's own intent marker `m:intent:` is still present on the participant row. The atomic mutation payload applies the data changes to family `d`, updates the row version `m:v`, and deletes `m:intent:` in a single atomic RPC. This guarantees that if an intent was timed out or aborted by the recovery sweeper, a slow/stalled coordinator cannot execute an unfenced write over newer state. +* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically. Before reading data rows, it checks for active intent markers in column family `m`. If an active lock is present, it coordinates with `__extenddb_txn_log__` to observe the snapshot at the transaction commit boundary, preventing dirty or partial reads. +* **Cross-Row Visibility for Standard Reads:** Standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables during the commit apply window. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. + +#### D. Optimistic Concurrency Control (OCC) Row Versioning for Single-Row Writes +All single-row writes (`PutItem`, `UpdateItem`, `DeleteItem`) maintain an explicit row version in column family `m` under qualifier `v` (`u64` monotonic counter or epoch timestamp) and execute via atomic `CheckAndMutateRow` to prevent TOCTOU race conditions and protect 2PC transactions: +* **Version Tracking (`m:v`):** Every row write writes data attributes into column family `d` and increments/sets the row version `m:v`. +* **Conditional Writes (`PutItem`, `UpdateItem`, `DeleteItem` with `ConditionExpression`):** + 1. **Read & Version Capture:** The engine reads the current row from Bigtable, extracting the existing item and capturing `read_version = m:v` (`Option`). + 2. **In-Memory Condition Evaluation:** `evaluate_condition` checks the condition expression against the read image. If false, `StorageError::ConditionFailed` is returned immediately. + 3. **Atomic OCC CAS Mutation:** The write is submitted via `CheckAndMutateRow`: + * **Existing Row (`read_version = Some(v)`):** Predicate filter uses a composite condition: `(no active intent in m) AND (m:v == v)`. Mutations (write `d`, set `m:v = v + 1`, or delete `d` and `m:v`) are placed in `true_mutations`. If the row was modified concurrently or locked, `predicate_matched == false`, and the engine returns `TransactionConflict`. + * **New Row Insert (`read_version = None`):** Predicate filter matches if `(active intent exists in m) OR (m:v exists) OR (family d exists)`. Mutations are placed in `false_mutations`. If the row already exists or is locked, `predicate_matched == true`, and the engine returns `TransactionConflict`. +* **Unconditional Writes:** + * **Predicate Filter:** Matches if an active 2PC intent exists in family `m` (`^intent:.*$` with timestamp $\ge$ `now - intent_timeout`). + * **Mutations:** In `false_mutations`, updates family `d` and sets `m:v = now_micros` (or incremented counter). +* **Deletes:** Use `DeleteFromFamily(d)` and `DeleteFromColumn(m:v)` instead of `DeleteFromRow` to preserve any concurrent 2PC intent markers in family `m`. + +#### E. Cloud Bigtable App Profile & Single-Cluster Routing Requirements +Cloud Bigtable requires single-cluster routing (or multi-cluster routing with single-row transactions enabled) to execute conditional mutations (`CheckAndMutateRow`). Multi-cluster instance routing configured with eventual consistency does not allow conditional mutations and rejects `CheckAndMutateRow` requests with `FailedPrecondition`. +* **Configuration (`app_profile_id`):** `BigtableStorageConfig` provides an optional `app_profile_id` field. When connecting to multi-cluster Bigtable instances, administrators must configure an application profile routed to a single cluster to ensure atomic OCC CAS mutations and 2PC intent locks operate correctly. + +#### F. Garbage Collection (GC) Rules +To prevent disk bloat and ensure fast lookups, tables provisioned by ExtendDB configure explicit Garbage Collection rules on all column families: +* **Data Column Family (`d`):** `MaxVersions(1)` retains only the latest cell version, compacting away historical cell values. +* **Metadata Column Family (`m`):** `MaxVersions(1)` retains only the latest row version `m:v` and intent markers. +* **System Tables:** Catalog table (`__extenddb_catalog__`), transaction log table (`__extenddb_txn_log__`), and TTL index table (`__extenddb_ttl_index__`) are all configured with `MaxVersions(1)`. + +#### G. Recovery Sweeper A background worker periodically scans `__extenddb_txn_log__` for transactions older than `intent_timeout`: * **`PENDING` State:** Clear intents on participant rows and delete the coordinator row (rollback). -* **`COMMITTED` State:** Re-apply mutations to participant rows, write stream records, clear intents, and delete the coordinator row (roll-forward). +* **`COMMITTED` State:** Re-apply mutations to participant rows via fenced `apply_fenced_mutation`, write stream records, clear intents, and delete the coordinator row (roll-forward). ### 3. Stream Emissions in Transactions @@ -118,6 +145,7 @@ Avoid full-table scans by introducing a sharded TTL index table. * `expiry_timestamp_be` (8 bytes): Big-Endian `u64` representing the TTL epoch second. * `encoded_base_row_key` (variable): Raw row key of the target item. * **Payload:** None (empty values). +* **GC Rule:** `MaxVersions(1)` on family `d`. #### B. Maintenance * **Writes:** Insert an empty row in `__extenddb_ttl_index__` when writing an item with a TTL attribute. @@ -142,34 +170,39 @@ Enforce DynamoDB GSI projection behavior: #### B. Background Reconciler Implement a reconciler as an internal background worker spawned via `ServerRuntimeHooks::spawn_workers`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows, preventing phantom records from returning during divergence windows. -### 6. GCP Credentials Configuration +### 6. GCP Credentials & Bigtable Configuration -Extend `BigtableStorageConfig` to support explicit service account files: +Extend `BigtableStorageConfig` to support explicit service account files and app profiles: ```toml [storage.bigtable] project_id = "my-project" instance_id = "my-instance" -data_instance_id = "my-data-instance" # Optional -credentials_path = "/path/to/sa-key.json" # Optional +data_instance_id = "my-data-instance" # Optional (separates catalog/data) +app_profile_id = "default" # Optional (requires single-cluster routing for CheckAndMutateRow) +credentials_path = "/path/to/sa-key.json" # Optional (service account JSON) pool_size = 20 ``` * **Behavior:** If `credentials_path` is specified, the server programmatically acquires tokens from the service account key. Configure `tonic` channels with `ClientTlsConfig` using native system roots. +* **App Profile:** If `app_profile_id` is specified, data client requests use the designated profile to ensure single-cluster routing for conditional mutations. ### 7. Future Work & Non-Goals -* **Backup / PITR / Export:** Point-in-Time Recovery (PITR) and automated backup snapshots are deferred to a follow-up RFC. Note that Cloud Bigtable's native backup retention windows and export capabilities will have different retention characteristics from DynamoDB's fixed 35-day PITR window. +* **Backup / PITR / Export (`BackupEngine`):** `BigtableEngine` implements the `extenddb_storage::BackupEngine` supertrait with explicit `StorageError::Internal("Operation not supported")` stubs. Point-in-Time Recovery (PITR), native Bigtable table backups, and Cloud Storage (GCS) exports require dedicated lifecycle orchestration and are deferred to a dedicated follow-up RFC. Note that Cloud Bigtable's native backup retention windows and export capabilities have distinct operational characteristics from DynamoDB's fixed 35-day PITR window. ## Testing Strategy 1. **Unit Tests (Emulator-based):** * Verify exact decimal number key encoding/decoding and numerical sorting up to 38 significant digits. - * Mock Bigtable client to verify 2PC coordinator state transitions and idempotency token deduplication. + * Verify row key 4KB size enforcement and partition length prefixing vs raw sort key ordering. + * Verify OCC row versioning (`m:v`) decoding and composite `CheckAndMutateRow` filter construction. + * Verify 2PC coordinator state transitions, fenced apply predicate, and idempotency token deduplication. * Assert `ValidationException` is returned for invalid GSI attribute requests and `ConsistentRead = true` on GSIs. + * Assert `BackupEngine` methods return `StorageError::Internal("Operation not supported")`. 2. **Failure Integration Tests (Real Bigtable & Emulator):** - * Inject crashes during the 2PC flow and assert that the recovery sweeper rolls forward/back and preserves stream record writes. - * Run concurrent mixed workloads to verify transactional serializability. + * Inject crashes during the 2PC flow and assert that the recovery sweeper rolls forward/back using fenced mutations and preserves stream record writes. + * Run concurrent mixed workloads to verify transactional serializability and OCC conflict detection on single-row writes. * Verify GSI reconciler heals base-to-shadow mismatches. * Verify TTL sweeper emits `REMOVE` stream records with the TTL principal and ignores updated items with old index entries. 3. **E2E & Chaos Tests:** @@ -180,5 +213,5 @@ pool_size = 20 * **Unprotected Single-Row Writes:** Bypassing intent checks for single-row writes allows dirty writes, violating serializability. Rejected. * **Scan-Based TTL Sweeper:** Scanning the entire base table to evict items degrades performance at scale. Rejected. +* **Length-Prefixed Sort Keys:** Length-prefixing sort keys in composite primary keys caused sort inversion where shorter string/numeric representations sorted before longer ones regardless of value. Rejected in favor of raw order-preserving sort key bytes. * **Cloud Spanner Backend:** Cloud Spanner supports multi-row transactions natively, eliminating the need for application-layer 2PC. This is a viable alternative to be explored as a separate backend connector. - From f58b70128420f863ef496bb4ab6edce048b2a3ee Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Mon, 24 Aug 2026 15:47:15 +0000 Subject: [PATCH 05/11] docs(rfc): address maintainer pass 3 review on GSI sort key escape encoding, TransactGetItems rule, and ack boundary --- docs/rfcs/0000-bigtable-backend.md | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index f0b62af73..d9af82fbe 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -52,7 +52,12 @@ Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, ` * **Negative numbers:** Sign byte `0x00`, followed by bit-inverted exponent and complement mantissa bytes. * **Zero:** Exactly `[0x80]`. * **Positive numbers:** Sign byte `0x81`, followed by big-endian exponent bytes and binary-coded decimal mantissa bytes. -* **GSI Index Row Keys:** Primary keys in GSI shadow tables follow the exact same encoding rules for the index partition and sort keys, formatted as `[gsi_pk_tag][gsi_pk_len][gsi_pk_bytes][gsi_sk_tag][gsi_sk_bytes][base_pk_tag][base_pk_len][base_pk_bytes][base_sk_tag][base_sk_bytes]`, ensuring full sort order preservation and primary key uniqueness. +* **GSI Index Row Keys:** Primary keys in GSI shadow tables follow the composite key format: + ```text + GSI Composite Key: [gsi_pk_tag:1] [gsi_pk_len:u32BE:4] [gsi_pk_bytes] [gsi_sk_tag:1] [gsi_sk_bytes_escaped] [0x00 0x00] [base_pk_tag:1] [base_pk_len:u32BE:4] [base_pk_bytes] [base_sk_tag:1] [base_sk_bytes] + ``` + * **Non-Terminal Sort Key Escape Encoding (`gsi_sk`):** The non-terminal `gsi_sk` segment is encoded using the FoundationDB tuple order-preserving escape encoding: each `0x00` byte within `gsi_sk_bytes` is escaped as `0x00 0xFF`, and the segment is terminated with delimiter `0x00 0x00`. Raw-to-end-of-key is only safe for the terminal segment; if `gsi_sk` were raw and unterminated, the subsequent byte (the `base_pk_tag`, e.g. `0x53`) would participate in lexicographical comparisons, causing sort inversion (for example, sort key `"A"` ordering after `"AB"` because `0x53 > 0x42`), breaking GSI query ordering, `begins_with`, and `between`. Escape-encoding and terminating with `0x00 0x00` completely prevents sort inversion and ensures unambiguous segment boundary decoding for reconciler parsing and primary key uniqueness. + * **Terminal Sort Key Raw Encoding (`base_sk`):** The terminal `base_sk` segment remains raw order-preserving bytes to the end of the row key. ### 2. Transaction Rules & Isolation Guarantees @@ -61,7 +66,7 @@ Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, ` * **Duplicate Participant Rejection:** A single `TransactWriteItems` request cannot contain multiple operations on the same item. Any transaction with duplicate primary keys is rejected upfront with `ValidationException`. #### B. Lock-then-Read 2PC Flow -The `TransactWriteItems` coordinator acquires locks *before* reading data and evaluating condition expressions, and applies mutations via fenced CAS: +The `TransactWriteItems` coordinator acquires locks *before* reading data and evaluating condition expressions, applies mutations via fenced CAS, and returns success to the client only after Phase 2 mutations are applied: ```mermaid sequenceDiagram @@ -89,13 +94,18 @@ sequenceDiagram loop For each participant row C->>B: Fenced Apply (CheckAndMutateRow: if m:intent: present, write d, set m:v, delete m:intent) end - C->>B: Phase 3: Clean up (Write CLEANED to log, then drop txn row) + Note over C: Return HTTP 200 OK (Success Ack Boundary) + C->>B: Phase 3: Clean up (Emit streams, write CLEANED to log, drop txn row) ``` #### C. Read Isolation & Concurrency Guarantees +* **Success Acknowledgment Boundary:** The HTTP 200 OK success acknowledgment is returned to the client **after** all Phase 2 fenced mutations are durably applied to column family `d` and GSI shadow tables. This guarantees monotonic Read-Your-Writes consistency: any subsequent strongly-consistent read (`GetItem` or `TransactGetItems`) issued by the client after receiving the 200 OK response is guaranteed to observe the updated state in column family `d`. * **Read Committed (No Dirty Reads):** In Phase 1 / Phase 2, the transaction coordinator only writes intent lock markers (`m:intent:`) to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 2 Apply** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. * **Fenced Phase 2 Apply:** During Phase 2 Apply, participant mutations are applied via `CheckAndMutateRow` using a fencing predicate that asserts the coordinator's own intent marker `m:intent:` is still present on the participant row. The atomic mutation payload applies the data changes to family `d`, updates the row version `m:v`, and deletes `m:intent:` in a single atomic RPC. This guarantees that if an intent was timed out or aborted by the recovery sweeper, a slow/stalled coordinator cannot execute an unfenced write over newer state. -* **Serializable `TransactGetItems`:** `TransactGetItems` observes the committed set atomically. Before reading data rows, it checks for active intent markers in column family `m`. If an active lock is present, it coordinates with `__extenddb_txn_log__` to observe the snapshot at the transaction commit boundary, preventing dirty or partial reads. +* **Serializable `TransactGetItems` (Read-Through-Log Snapshot Rule):** `TransactGetItems` observes the committed set atomically. Before serving data rows, it checks for active intent markers (`m:intent:`) in column family `m`: + * **Intent Present & Txn `COMMITTED`:** Serve the logged post-image from the coordinator row's mutation payloads in `__extenddb_txn_log__` (reflecting the durable commit even if Phase 2 apply has not yet executed on that participant row). + * **Intent Present & Txn `PENDING`:** Serve the current value from column family `d` (since Phase 2 apply cannot have started, `d` reflects the pre-transaction committed snapshot). + * **No Active Intent (or Txn `CLEANED`/`ABORTED`):** Serve the current value from column family `d` directly. * **Cross-Row Visibility for Standard Reads:** Standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables during the commit apply window. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. #### D. Optimistic Concurrency Control (OCC) Row Versioning for Single-Row Writes @@ -104,8 +114,8 @@ All single-row writes (`PutItem`, `UpdateItem`, `DeleteItem`) maintain an explic * **Conditional Writes (`PutItem`, `UpdateItem`, `DeleteItem` with `ConditionExpression`):** 1. **Read & Version Capture:** The engine reads the current row from Bigtable, extracting the existing item and capturing `read_version = m:v` (`Option`). 2. **In-Memory Condition Evaluation:** `evaluate_condition` checks the condition expression against the read image. If false, `StorageError::ConditionFailed` is returned immediately. - 3. **Atomic OCC CAS Mutation:** The write is submitted via `CheckAndMutateRow`: - * **Existing Row (`read_version = Some(v)`):** Predicate filter uses a composite condition: `(no active intent in m) AND (m:v == v)`. Mutations (write `d`, set `m:v = v + 1`, or delete `d` and `m:v`) are placed in `true_mutations`. If the row was modified concurrently or locked, `predicate_matched == false`, and the engine returns `TransactionConflict`. + 3. **Atomic OCC CAS Mutation (De Morgan Form):** Cloud Bigtable row filters do not have a native boolean `NOT` operator. Therefore, the OCC predicate cannot be expressed as `(no active intent) AND (m:v == v)` with `true_mutations`. Instead, OCC writes use the equivalent De Morgan conflict form: + * **Existing Row (`read_version = Some(v)`):** Predicate filter matches if `(active intent exists in m) OR (m:v != v)` using `RowFilter::Interleave` (combining active intent filter with a version mismatch condition filter), with write/delete mutations placed in `false_mutations`. If the row was modified concurrently, locked, or deleted, `predicate_matched == true`, mutations are not applied, and the engine returns `TransactionConflict`. If no conflict exists, `predicate_matched == false`, and Bigtable atomically applies `false_mutations`. * **New Row Insert (`read_version = None`):** Predicate filter matches if `(active intent exists in m) OR (m:v exists) OR (family d exists)`. Mutations are placed in `false_mutations`. If the row already exists or is locked, `predicate_matched == true`, and the engine returns `TransactionConflict`. * **Unconditional Writes:** * **Predicate Filter:** Matches if an active 2PC intent exists in family `m` (`^intent:.*$` with timestamp $\ge$ `now - intent_timeout`). From 0632fbddc8e18c6396b12f0a61ee048fcfa03c97 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Thu, 19 Nov 2026 01:58:30 +0000 Subject: [PATCH 06/11] docs(rfc): address pass 4 review on deterministic OCC timestamps, fenced streams, Unsupported stubs, and deliverables matrix --- docs/rfcs/0000-bigtable-backend.md | 362 ++++++++++++++++------------- 1 file changed, 202 insertions(+), 160 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index d9af82fbe..62743f97c 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -1,4 +1,4 @@ -# RFC-0003: Cloud Bigtable Storage Backend for ExtendDB +# RFC-0000: Cloud Bigtable Storage Backend for ExtendDB - Status: Draft - Author: @annguy3n @@ -7,221 +7,263 @@ ## Summary -This RFC defines the design and implementation of a production-grade Cloud Bigtable storage backend for ExtendDB. It addresses critical architectural requirements for this backend: transaction isolation, stream emissions in transactions, Global Secondary Index (GSI) projections, GSI write consistency, Time-to-Live (TTL) eviction scalability, Optimistic Concurrency Control (OCC) row versioning, fenced two-phase commit (2PC) apply, application profile single-cluster routing, and secure Google Cloud Platform (GCP) connectivity. +This RFC defines the design and implementation of a production-grade Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0`. It addresses transaction isolation and serializable read-through-log snapshots, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection, fenced two-phase commit (2PC) apply, unified write-ahead fenced DynamoDB Streams emission with full disable/re-enable shard lineage (`stream_lineage`), FoundationDB tuple escape-encoded Global Secondary Index (GSI) keys and projections, sharded Time-to-Live (TTL) indexing, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, IAM/metrics/rate-limit catalog conformance, gRPC transient-error classification, application-profile single-cluster routing, and Google Cloud Platform (GCP) authentication. ## Motivation -A naive mapping of DynamoDB structures to Bigtable introduces several architectural challenges that must be addressed to ensure production-readiness: -1. **Transaction Isolation Leak & TOCTOU Races:** Non-transactional (single-row) conditional writes read an item and evaluate conditions without atomic concurrency control, leading to Time-of-Check to Time-of-Use (TOCTOU) races where concurrent writes can overwrite uncommitted state or bypass 2-Phase Commit (2PC) locks. -2. **2PC Race Condition (Read-then-Lock & Unfenced Apply):** Reading row data before placing locks exposes 2PC to TOCTOU races. Furthermore, applying 2PC Phase 2 mutations unconditionally without fencing against expired/aborted locks allows slow coordinators to overwrite newer state. -3. **Missing Transaction Streams:** Multi-row transactions (`TransactWriteItems`) do not emit DynamoDB Stream records. -4. **Inefficient TTL Eviction:** The TTL worker performs full-table scans to identify expired items, which degrades performance on large datasets. -5. **GSI Consistency Gap:** GSI shadow table write failures are logged without retry or repair, causing permanent base-to-shadow divergence. -6. **Multi-Cluster Replication & Conditional Mutations:** Cloud Bigtable rejects conditional mutations (`CheckAndMutateRow`) under multi-cluster routing with eventual consistency. -7. **Auth Configuration Constraints:** Lack of support for explicit credentials file configuration. +Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-atomic data model introduces several distributed-systems challenges that a production backend must resolve: -This RFC provides the technical specification to resolve these challenges. +1. **Transaction Isolation & TOCTOU Races:** Naive read-modify-write conditional operations evaluate `ConditionExpression`s without atomic concurrency control, allowing concurrent writers to overwrite uncommitted state or bypass 2PC locks. +2. **Cell Timestamps vs. `MaxNumVersions(1)` Compaction:** Relying on server-assigned cell timestamps (`SetCell.timestamp_micros = -1`) allows tablet-server wall-clock differences or narrow concurrency windows to interleave cells from distinct writes across qualifiers (`d:*` vs. `m:v`), producing torn rows once `MaxNumVersions(1)` compaction runs. +3. **2PC Race Conditions (Read-then-Lock & Unfenced Apply):** Reading participant rows before placing intent locks exposes `TransactWriteItems` to TOCTOU races, while applying Phase 2 mutations unconditionally allows stalled coordinators whose intents were swept to overwrite newer committed data. +4. **Unfenced Stream Emission:** Emitting DynamoDB Stream records as an unfenced trailing write after mutating the base table loses stream records if the server crashes in the gap, violating [RFC-0003](0003-backend-acceptance-criteria.md) §3.2 and §5.1. +5. **Inefficient TTL Eviction:** Full-table scans to identify expired items degrade read throughput at scale and risk deleting items whose TTL attribute was concurrently extended. +6. **GSI Sort-Order & Consistency:** Non-terminal sort keys in composite GSI row keys suffer sort inversion unless escape-terminated, and shadow-table write failures require background reconciliation to heal base-to-shadow divergence. +7. **Multi-Cluster Routing & Auth Constraints:** Cloud Bigtable rejects `CheckAndMutateRow` under multi-cluster routing with eventual consistency unless routed via a single-cluster application profile, and enterprise deployments require explicit service-account credential configuration. ## Detailed Design ### 1. Table Mapping & Key Encoding #### A. Table Structure & Naming -* **Catalog:** System metadata, accounts, and policies are stored in a single table named `__extenddb_catalog__`. -* **Data Tables:** DynamoDB tables map to Bigtable tables named `t` (where `table_id_hex` is a 32-character hex UUID). Data attributes are stored in column family `d`. -* **GSIs:** Shadow tables are named `t_g` (where `idx_hash` is an 8-character hash of the index name). -* **Transaction Intents & OCC Versions:** Column family `m` in data tables stores lock/intent cells (`m:intent:`) and explicit OCC row versions (`m:v`). -* **TTL Markers:** Column family `t` (reserved). - -> [!NOTE] -> **Naming Constraints:** Table IDs in Cloud Bigtable are limited to 50 characters. To prevent overflow, GSIs are named `t_g` (43 characters total) rather than reproducing the full index name. +* **Catalog & Stream Ledger (`__extenddb_catalog__`):** Stores system settings (`setting:catalog_id`, `setting:encryption_key`, `setting:encryption_key_ring`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIA*` access keys and `ASIA*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:`), distributed worker leases (`lock:`), stream shard lineage rows (`stream_shard:`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). +* **Coordinator Transaction Log (`__extenddb_txn_log__`):** Stores coordinator state (`t:state`), start timestamp (`t:started_at`), participant list (`t:participants`), pre-computed mutations (`t:mutations`), and pre-generated stream records (`t:stream_records`) in column family `t`. +* **Sharded TTL Index (`__extenddb_ttl_index__`):** Stores expiration index entries across 16 hash shards in column family `d`. +* **Data Tables (`t`):** Each DynamoDB table maps to a dedicated Bigtable table named `t` followed by the first 16 lowercase hex characters of the table's unique `table_id` UUID (17 characters total). Deriving physical table names from `table_id` rather than `table_name` guarantees clean isolation across accounts and across `DeleteTable` + `CreateTable` name reuse ([RFC-0003](0003-backend-acceptance-criteria.md) §8.2). Data attributes live in column family `d` (one qualifier per top-level attribute); OCC row versions (`m:v`) and 2PC intent locks (`m:intent:`) live in column family `m`; column family `t` is reserved. +* **GSI Shadow Tables (`t_g`):** Each GSI maps to a shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit). #### B. Exact Decimal & Order-Preserving Key Encoding -Cloud Bigtable sorts row keys by raw byte lexicographical order. The maximum row key size supported by Cloud Bigtable is **4KB (4096 bytes)**, which is strictly enforced during key encoding (`row_key::encode_key`). +Cloud Bigtable sorts row keys by unsigned raw byte lexicographical order and enforces a **4 KiB (4096-byte)** row-key limit, validated upfront in `row_key::encode_key` and `gsi::shadow_row_key_for_item`. -Row keys are encoded using the following structured layout: +Base-table row keys follow: ```text Composite Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] [sk_tag:1] [sk_bytes] PK-Only Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] ``` Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, `0x4E` for `N`, `0x42` for `B`). -* **Partition (HASH) Keys:** Partition keys use **length-prefixing** (`[pk_len:u32BE:4]`) preceding `[pk_bytes]`. Length prefixing is essential to delimit variable-length partition keys, prevent ambiguity/delimiter collision, and group all items sharing the same partition key contiguously within Bigtable's lexicographical keyspace. -* **Sort (RANGE) Keys:** Sort keys are stored as **raw order-preserving bytes without length prefixing**. Omitting the length prefix on sort keys is strictly mandatory: length-prefixing sort keys would sort primarily by byte-length rather than value, leading to severe sort inversion (for example, `"10"` of length 2 would sort before `"2"` of length 1, or shorter numbers would sort before longer numbers). -* **Number Encoding:** DynamoDB supports numeric values with up to 38 significant digits and requires exact numerical sorting (e.g., `-100 < -1.5 < -1 < 0 < 0.5 < 1 < 1.5 < 100`). Numbers are stored as exact arbitrary-precision decimals (never floating point floats) using an order-preserving byte encoding: - * **Negative numbers:** Sign byte `0x00`, followed by bit-inverted exponent and complement mantissa bytes. - * **Zero:** Exactly `[0x80]`. - * **Positive numbers:** Sign byte `0x81`, followed by big-endian exponent bytes and binary-coded decimal mantissa bytes. -* **GSI Index Row Keys:** Primary keys in GSI shadow tables follow the composite key format: - ```text - GSI Composite Key: [gsi_pk_tag:1] [gsi_pk_len:u32BE:4] [gsi_pk_bytes] [gsi_sk_tag:1] [gsi_sk_bytes_escaped] [0x00 0x00] [base_pk_tag:1] [base_pk_len:u32BE:4] [base_pk_bytes] [base_sk_tag:1] [base_sk_bytes] - ``` - * **Non-Terminal Sort Key Escape Encoding (`gsi_sk`):** The non-terminal `gsi_sk` segment is encoded using the FoundationDB tuple order-preserving escape encoding: each `0x00` byte within `gsi_sk_bytes` is escaped as `0x00 0xFF`, and the segment is terminated with delimiter `0x00 0x00`. Raw-to-end-of-key is only safe for the terminal segment; if `gsi_sk` were raw and unterminated, the subsequent byte (the `base_pk_tag`, e.g. `0x53`) would participate in lexicographical comparisons, causing sort inversion (for example, sort key `"A"` ordering after `"AB"` because `0x53 > 0x42`), breaking GSI query ordering, `begins_with`, and `between`. Escape-encoding and terminating with `0x00 0x00` completely prevents sort inversion and ensures unambiguous segment boundary decoding for reconciler parsing and primary key uniqueness. - * **Terminal Sort Key Raw Encoding (`base_sk`):** The terminal `base_sk` segment remains raw order-preserving bytes to the end of the row key. - -### 2. Transaction Rules & Isolation Guarantees +* **Partition (`HASH`) Keys:** Length-prefixed (`[pk_len:u32BE:4]`) before `[pk_bytes]` so variable-length partition keys cannot collide across boundaries and all items sharing a partition key sort contiguously. Parallel scan segment assignment hashes the `[pk_tag:1][pk_len:4][pk_bytes]` prefix with CRC32 (`crc32(pk_prefix) % total_segments`), shared identically between `QueryScan::scan` and `DataEngine::scan_key_in_segment`. +* **Sort (`RANGE`) Keys:** Stored as raw order-preserving bytes **without** a length prefix on terminal segments so string and binary sort keys compare in unsigned byte-lexicographic order regardless of length. +* **Exact 38-Digit Decimal `N` Encoding (`encoding::number`):** DynamoDB numbers support up to 38 significant digits over scientific exponents `[-130, +125]`. Numbers are normalized (stripping leading/trailing zeros and collapsing `-0` / `0.0` to canonical zero) and encoded without floating-point conversion: + * **Negative (`value < 0`):** Sign byte `0x00`, inverted biased exponent `0xFF - (sci_exp + 130)`, and 38 digit bytes inverted as `9 - digit` (padded with `0x09` so shorter magnitudes compare greater / closer to zero). + * **Zero (`value == 0`):** Single byte `[0x80]`. + * **Positive (`value > 0`):** Sign byte `0xFF`, biased exponent `(sci_exp + 130) as u8`, and 38 digit bytes `0..=9` (padded with `0x00`). + * Inputs exceeding 38 significant digits or exponent bounds `[-130, 125]` are rejected at write/query time with `ValidationException`. +* **GSI Shadow Row Keys (`gsi::shadow_row_key_for_item`):** + ```text + GSI Composite Key: [gsi_pk_tag:1] [gsi_pk_len:u32BE:4] [gsi_pk_bytes] + [gsi_sk_tag:1] [escape_encoded(gsi_sk_bytes)] [0x00 0x00] + [base_pk_tag:1] [base_pk_len:u32BE:4] [base_pk_bytes] + [base_sk_tag:1] [base_sk_bytes] + ``` + * **Non-Terminal Sort Key Escape Encoding (`gsi_sk`):** Every `0x00` byte in `gsi_sk_bytes` is escaped as `0x00 0xFF` and terminated by `0x00 0x00` (FoundationDB tuple encoding). Without termination, the following `base_pk_tag` byte (e.g., `0x53`) would participate in sort-key comparison and invert ordering (e.g., `"A"` sorting after `"AB"` because `0x53 > 0x42`). + * **Terminal Sort Key (`base_sk`):** Remains raw order-preserving bytes to the end of the row key. + +### 2. Transaction Rules, Deterministic OCC Timestamps & Isolation Guarantees #### A. Transaction Validation & Idempotency Rules -* **`ClientRequestToken` Idempotency:** `TransactWriteItems` enforces idempotency within a 10-minute sliding window. Requests with an active or recently committed token replay the committed result; conflicting requests with the same token but mismatched payload return `IdempotentParameterMismatchException`. -* **Duplicate Participant Rejection:** A single `TransactWriteItems` request cannot contain multiple operations on the same item. Any transaction with duplicate primary keys is rejected upfront with `ValidationException`. +* **`ClientRequestToken` Idempotency:** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a 10-minute window and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`. Replays with matching operation fingerprints return `IdempotentReplay` (rolling forward first if the coordinator row is `COMMITTED`); mismatched payloads return `IdempotentMismatch`. +* **Duplicate Participant Rejection:** Any `TransactWriteItems` request targeting the same `(data_table, row_key)` more than once is rejected upfront with `ValidationException`. -#### B. Lock-then-Read 2PC Flow -The `TransactWriteItems` coordinator acquires locks *before* reading data and evaluating condition expressions, applies mutations via fenced CAS, and returns success to the client only after Phase 2 mutations are applied: +#### B. Lock-then-Read Coordinator 2PC Flow +`TransactWriteItems` acquires per-row intents *before* reading participant rows and evaluating condition expressions, commits atomically in `__extenddb_txn_log__`, applies mutations via fenced `CheckAndMutateRow`, and acknowledges HTTP 200 OK only after Phase 2 mutations and stream records are durable: ```mermaid sequenceDiagram participant C as Coordinator (ExtendDB) - participant B as Bigtable - - C->>B: Phase 1: Open Transaction (Write PENDING to __extenddb_txn_log__) - Note over C,B: Place Intents (Locks) - loop For each participant row - C->>B: Place Intent (CheckAndMutateRow: fail if other fresh intent exists) + participant L as __extenddb_txn_log__ + participant B as Bigtable Data / GSI / Catalog + + C->>L: Phase 1: Open Coordinator Row (t:state = PENDING) + loop Each participant row + C->>B: Place Intent (CheckAndMutateRow: fail if unexpired m:intent:* exists) end - alt Any Lock Fails - C->>B: Rollback (Clear placed intents, drop txn row) - Note over C: Return TransactionConflict + alt Intent Contention Exhausts Retries + C->>B: Clear placed intents & drop coordinator row + Note over C: Return TransactionCanceled (TransactionConflict) end - Note over C,B: Read & Verify - C->>B: Read participant rows & capture row versions (m:v) - Note over C: Evaluate Condition Expressions + C->>B: Read locked participant rows & capture OCC versions (m:v) + Note over C: Evaluate ConditionExpressions & compute next_occ_version alt Any Condition Fails - C->>B: Rollback (Clear intents, drop txn row) - Note over C: Return TransactionCanceled + C->>B: Clear intents & drop coordinator row + Note over C: Return TransactionCanceled (ConditionalCheckFailed) + end + C->>L: Phase 2 Commit: DeleteFromColumn(t:state, [0, commit_ts)) + SetCell(COMMITTED, mutations, stream_records) @ commit_ts > started_at + loop Each mutated participant + C->>B: Fenced Apply (if m:intent: && OCC state == expected: write d:* & m:v at occ_ts, retain intent) + C->>B: Update GSI shadow rows (at occ_ts) & TTL index end - C->>B: Phase 2: Commit Transaction (Write COMMITTED to __extenddb_txn_log__) - Note over C,B: Fenced Apply Mutations - loop For each participant row - C->>B: Fenced Apply (CheckAndMutateRow: if m:intent: present, write d, set m:v, delete m:intent) + C->>B: Write pre-generated stream records to __extenddb_catalog__ + loop Each locked participant + C->>B: Clear intent (DeleteFromColumn m:intent:) end - Note over C: Return HTTP 200 OK (Success Ack Boundary) - C->>B: Phase 3: Clean up (Emit streams, write CLEANED to log, drop txn row) + C->>L: Mark CLEANED (@ clean_ts > commit_ts) & delete coordinator row + Note over C: Return HTTP 200 OK (Read-Your-Writes Boundary) ``` -#### C. Read Isolation & Concurrency Guarantees -* **Success Acknowledgment Boundary:** The HTTP 200 OK success acknowledgment is returned to the client **after** all Phase 2 fenced mutations are durably applied to column family `d` and GSI shadow tables. This guarantees monotonic Read-Your-Writes consistency: any subsequent strongly-consistent read (`GetItem` or `TransactGetItems`) issued by the client after receiving the 200 OK response is guaranteed to observe the updated state in column family `d`. -* **Read Committed (No Dirty Reads):** In Phase 1 / Phase 2, the transaction coordinator only writes intent lock markers (`m:intent:`) to column family `m`. Actual data mutations in column family `d` are **only applied in Phase 2 Apply** after the coordinator's `COMMITTED` record is durable in `__extenddb_txn_log__`. Standard reads (`GetItem`, `Query`, `Scan`, `BatchGetItem`) read solely from column family `d` and therefore never observe uncommitted candidate writes that could roll back. -* **Fenced Phase 2 Apply:** During Phase 2 Apply, participant mutations are applied via `CheckAndMutateRow` using a fencing predicate that asserts the coordinator's own intent marker `m:intent:` is still present on the participant row. The atomic mutation payload applies the data changes to family `d`, updates the row version `m:v`, and deletes `m:intent:` in a single atomic RPC. This guarantees that if an intent was timed out or aborted by the recovery sweeper, a slow/stalled coordinator cannot execute an unfenced write over newer state. -* **Serializable `TransactGetItems` (Read-Through-Log Snapshot Rule):** `TransactGetItems` observes the committed set atomically. Before serving data rows, it checks for active intent markers (`m:intent:`) in column family `m`: - * **Intent Present & Txn `COMMITTED`:** Serve the logged post-image from the coordinator row's mutation payloads in `__extenddb_txn_log__` (reflecting the durable commit even if Phase 2 apply has not yet executed on that participant row). - * **Intent Present & Txn `PENDING`:** Serve the current value from column family `d` (since Phase 2 apply cannot have started, `d` reflects the pre-transaction committed snapshot). - * **No Active Intent (or Txn `CLEANED`/`ABORTED`):** Serve the current value from column family `d` directly. -* **Cross-Row Visibility for Standard Reads:** Standard `Query` or `Scan` operations may observe some participant rows updated before others across separate Bigtable tables during the commit apply window. This is fully compliant with DynamoDB's `Read Committed` isolation model, as every observed row reflects a durable, committed state. - -#### D. Optimistic Concurrency Control (OCC) Row Versioning for Single-Row Writes -All single-row writes (`PutItem`, `UpdateItem`, `DeleteItem`) maintain an explicit row version in column family `m` under qualifier `v` (`u64` monotonic counter or epoch timestamp) and execute via atomic `CheckAndMutateRow` to prevent TOCTOU race conditions and protect 2PC transactions: -* **Version Tracking (`m:v`):** Every row write writes data attributes into column family `d` and increments/sets the row version `m:v`. -* **Conditional Writes (`PutItem`, `UpdateItem`, `DeleteItem` with `ConditionExpression`):** - 1. **Read & Version Capture:** The engine reads the current row from Bigtable, extracting the existing item and capturing `read_version = m:v` (`Option`). - 2. **In-Memory Condition Evaluation:** `evaluate_condition` checks the condition expression against the read image. If false, `StorageError::ConditionFailed` is returned immediately. - 3. **Atomic OCC CAS Mutation (De Morgan Form):** Cloud Bigtable row filters do not have a native boolean `NOT` operator. Therefore, the OCC predicate cannot be expressed as `(no active intent) AND (m:v == v)` with `true_mutations`. Instead, OCC writes use the equivalent De Morgan conflict form: - * **Existing Row (`read_version = Some(v)`):** Predicate filter matches if `(active intent exists in m) OR (m:v != v)` using `RowFilter::Interleave` (combining active intent filter with a version mismatch condition filter), with write/delete mutations placed in `false_mutations`. If the row was modified concurrently, locked, or deleted, `predicate_matched == true`, mutations are not applied, and the engine returns `TransactionConflict`. If no conflict exists, `predicate_matched == false`, and Bigtable atomically applies `false_mutations`. - * **New Row Insert (`read_version = None`):** Predicate filter matches if `(active intent exists in m) OR (m:v exists) OR (family d exists)`. Mutations are placed in `false_mutations`. If the row already exists or is locked, `predicate_matched == true`, and the engine returns `TransactionConflict`. -* **Unconditional Writes:** - * **Predicate Filter:** Matches if an active 2PC intent exists in family `m` (`^intent:.*$` with timestamp $\ge$ `now - intent_timeout`). - * **Mutations:** In `false_mutations`, updates family `d` and sets `m:v = now_micros` (or incremented counter). -* **Deletes:** Use `DeleteFromFamily(d)` and `DeleteFromColumn(m:v)` instead of `DeleteFromRow` to preserve any concurrent 2PC intent markers in family `m`. +#### C. Read Isolation & `TransactGetItems` Read-Through-Log Rule +* **Read-Your-Writes Acknowledgment Boundary:** Success is returned only after Phase 2 mutations are applied to column family `d` and GSI shadow tables, guaranteeing `ConsistentRead = true` (`GetItem`, `Query`, `Scan`) and `TransactGetItems` immediately observe the committed state. +* **Read Committed (No Dirty Reads):** Uncommitted transactions write only `m:intent:` in family `m`. Standard reads filter strictly on family `d` (`Chain([FamilyNameRegexFilter("^d$"), CellsPerColumnLimitFilter(1)])`) and never observe uncommitted writes. +* **ABA-Safe Fenced Phase 2 Apply & Intent Retention:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard (`(Some(v), _) -> m:v == v`; `(None, false) -> neither m:v nor d:* exists`; `(None, true) -> d:* exists && m:v absent`). Checking `(expected_version, row_existed)` guarantees that even if an intent lease expires and a newer writer advances `m:v` to `v2`, neither a slow coordinator nor `sweeper::roll_forward` can overwrite `v2` on the base row or apply superseded GSI shadow mutations (which `roll_forward` gates on `applied || cur_ver == Some(new_version)`). Furthermore, `m:intent:` is retained across base-row apply, GSI shadow updates, TTL index updates, and stream ledger persistence, and cleared via `clear_intent` only after stream records land. +* **Serializable `TransactGetItems` (Read-Through-Log Snapshot Rule):** `TransactGetItems` reads family `d` alongside any unexpired `m:intent:` cell (`ItemOps::batch_get_with_intent_check`) and resolves active intents via `TxnCoordinator::get_state`: + * **Intent Present & Coordinator `COMMITTED`:** Serves the committed post-image (`Some(item)` for `Put`, `None` for `Delete`) directly from `t:mutations` in `__extenddb_txn_log__`, even if Phase 2 apply has not yet reached that participant row. + * **Intent Present & Coordinator `PENDING` / `ABORTED` / `CLEANED` (or No Active Intent):** Serves the current committed image from family `d`. + * **Lazy Compaction Filter & Rank-Ordered Coordinator Timestamps:** Because Cloud Bigtable enforces `MaxNumVersions(1)` asynchronously during compaction, `TxnCoordinator::get_state` and `sweeper::sweep_once` **must** read `__extenddb_txn_log__` with `Chain([FamilyNameRegexFilter("^t$"), CellsPerColumnLimitFilter(1)])`. Coordinator transitions allocate millisecond-aligned timestamps via `monotonic_timestamp_after_micros(exclusive_floor_micros)` (`PENDING` at `t0 >= now`, `ABORTED`/`COMMITTED` at `t1 > t0`, `CLEANED` at `t2 > t1`) preceded by bounded `DeleteFromColumn(t:state, [0, ts_micros))`. Anchoring to wall-clock time while enforcing `ts > floor` guarantees `COMMITTED` strictly dominates `PENDING` across multi-node NTP skew and ensures retried `ClientRequestToken`s (`SHA-256(account_id || ":" || token)`) after a Phase 1 abort (`DeleteFromRow`) always stamp cells above the prior delete marker. + +#### D. Deterministic OCC-Derived Cell Timestamps & Single-Row Concurrency Control +Using server-assigned cell timestamps (`timestamp_micros: -1`) is unsafe under `MaxNumVersions(1)`: if two writers pass filters within a narrow window, or tablet servers experience slight clock skew across tablet moves or recovery roll-forward, `MaxNumVersions(1)` compaction retains whichever cell had the higher wall-clock arrival timestamp per qualifier rather than the higher logical OCC version, risking torn rows (`d:*` from one write paired with `m:v` or attributes from another). + +To eliminate torn rows while satisfying Cloud Bigtable's **`TimestampGranularity::MILLIS`** rule (which rejects explicit `SetCell.timestamp_micros` values not divisible by `1_000` with `INVALID_ARGUMENT`), all row writes derive deterministic millisecond-aligned cell timestamps directly from the monotonic OCC version: + +* **Hybrid Monotonic OCC Version (`item_ops::next_occ_version`):** + * `now_ms = unix_timestamp_millis().max(1)` + * `next_occ_version(None) = now_ms` + * `next_occ_version(Some(prev)) = prev.max(now_ms) + 1` + * `version_to_timestamp_micros(v) = (v * 1_000) as i64` +* **Uniform Row-Wide Stamping:** Every `SetCell` in a write—every attribute cell in `d:*`, the `m:v` version cell (preceded by bounded `DeleteFromColumn(m:v, [0, occ_ts))`), and every projected cell in GSI shadow tables—is stamped with the exact same `version_to_timestamp_micros(next_version)`. Bounding `DeleteFromColumn` to `[0, occ_ts)` clears historical versions without creating an unbounded tombstone that could mask future writes, and a higher OCC version strictly dominates all cells of every prior write across all column families even across dozens of sequential writes within the same wall-clock millisecond. +* **Monotonic Tombstone Versioning on Delete:** Deleting an existing row (`expected_version = Some(v)`) issues `DeleteFromFamily("d")`, bounded `DeleteFromColumn("m", "v", [0, occ_ts))`, and `SetCell("m", "v", next_version)` at `version_to_timestamp_micros(next_version)`. Retaining the monotonic `m:v` marker across deletes prevents ABA version reuse and timestamp regression on rapid `Put -> Delete -> Put` cycles, while `Query`, `Scan`, and `BatchGetItem` filter on `FamilyNameRegexFilter("^d$")` so version-only tombstones never appear as items or consume `rows_limit`. +* **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** Because Bigtable row filters have no boolean `NOT` operator, `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`: + * **Versioned Existing Row (`read_version = Some(v)`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v != v)`. + * **Unversioned Pre-Existing Row (`read_version = None, row_existed = true`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v exists)`, allowing any legacy/unversioned row to transition onto monotonic `m:v` versioning on its first write while still rejecting concurrent writers that stamped `m:v` first. + * **New Row (`read_version = None, row_existed = false`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v exists) OR (d:* exists)`. + * **Conflict Classification & Contention Retry:** When `predicate_matched == true`, `ItemOps` checks `has_active_intent(row_key)`. If an unexpired 2PC intent holds the row, it immediately returns `StorageError::TransactionConflict` (`TransactionConflictException`, [RFC-0003](0003-backend-acceptance-criteria.md) §4.3). Otherwise, it returns `CasOutcome::OccMismatch` and `BigtableEngine` retries up to `MAX_OCC_ATTEMPTS` (16) with jittered exponential backoff—re-reading the row, re-evaluating `ConditionExpression` (so concurrent conditional losers deterministically receive `ConditionFailed` per §4.2), and re-applying `UpdateAction`s (so concurrent `UpdateItem` increments serialize cumulatively with zero lost updates per §4.4). #### E. Cloud Bigtable App Profile & Single-Cluster Routing Requirements -Cloud Bigtable requires single-cluster routing (or multi-cluster routing with single-row transactions enabled) to execute conditional mutations (`CheckAndMutateRow`). Multi-cluster instance routing configured with eventual consistency does not allow conditional mutations and rejects `CheckAndMutateRow` requests with `FailedPrecondition`. -* **Configuration (`app_profile_id`):** `BigtableStorageConfig` provides an optional `app_profile_id` field. When connecting to multi-cluster Bigtable instances, administrators must configure an application profile routed to a single cluster to ensure atomic OCC CAS mutations and 2PC intent locks operate correctly. +Cloud Bigtable requires single-cluster routing (or multi-cluster routing with single-row transactions enabled) to execute `CheckAndMutateRow`. Multi-cluster profiles with eventual consistency reject `CheckAndMutateRow` with `FailedPrecondition`. `BigtableStorageConfig` exposes `app_profile_id` and forwards it on every `ReadRows`, `MutateRow`, `MutateRows`, and `CheckAndMutateRow` RPC so multi-cluster deployments can bind ExtendDB to a single-cluster profile. -#### F. Garbage Collection (GC) Rules -To prevent disk bloat and ensure fast lookups, tables provisioned by ExtendDB configure explicit Garbage Collection rules on all column families: -* **Data Column Family (`d`):** `MaxVersions(1)` retains only the latest cell version, compacting away historical cell values. -* **Metadata Column Family (`m`):** `MaxVersions(1)` retains only the latest row version `m:v` and intent markers. -* **System Tables:** Catalog table (`__extenddb_catalog__`), transaction log table (`__extenddb_txn_log__`), and TTL index table (`__extenddb_ttl_index__`) are all configured with `MaxVersions(1)`. +#### F. Garbage Collection (GC) Rules & Recovery Sweeper +* **Column Family GC:** `d` and `m` on data/GSI tables, `c` on `__extenddb_catalog__`, `t` on `__extenddb_txn_log__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. +* **2PC Recovery Sweeper (`sweeper.rs`):** Spawned via `BigtableRuntimeHooks::spawn_workers` under a distributed catalog lease (`lock:sweeper`) with graceful `CancellationToken` shutdown. Transactions in `__extenddb_txn_log__` older than `intent_timeout_secs` are rolled back if `PENDING`/`ABORTED` (clearing intents and deleting the coordinator row) or rolled forward idempotently if `COMMITTED` (re-running fenced base mutations, GSI shadow writes, and idempotent stream record writes before marking `CLEANED` and dropping the coordinator row). -#### G. Recovery Sweeper -A background worker periodically scans `__extenddb_txn_log__` for transactions older than `intent_timeout`: -* **`PENDING` State:** Clear intents on participant rows and delete the coordinator row (rollback). -* **`COMMITTED` State:** Re-apply mutations to participant rows via fenced `apply_fenced_mutation`, write stream records, clear intents, and delete the coordinator row (roll-forward). +### 3. Unified Fenced DynamoDB Streams Architecture & Stream Lineage -### 3. Stream Emissions in Transactions +#### A. Write-Ahead Fenced Stream Emission & Labelled Shard Lineage (`stream_lineage`) +To satisfy [RFC-0003](0003-backend-acceptance-criteria.md) §3.2 and §5.1 ("a crash between a committed data write and its stream record insert must not be possible"), stream emission is **never** performed as an unfenced trailing write. Whenever a caller supplies `stream: Some(&StreamCapture)` on a table whose `StreamSpecification.stream_enabled` is active (`active_stream_target_for_capture`), single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through `BigtableEngine::execute_fenced_single_item_write`, sharing the exact same `__extenddb_txn_log__` commit fence as `TransactWriteItems` (while `DataEngine` writes with `stream: None`—such as `ImportTable` bulk imports—preserve the upstream stream-suppression contract without emitting stream events): -To ensure stream record atomicity: -1. **Phase 1 (Prepare):** Fetch the full `TableDescription` (including `StreamSpecification` and `latest_stream_arn`) and pre-generate the `StreamRecord` payloads. -2. **Phase 2 (Log Enrichment & Commit):** Store the pre-generated stream record payloads and participant mutation payloads in the coordinator row of `__extenddb_txn_log__` alongside `COMMITTED`, and apply stream records to `__extenddb_streams__` concurrently with data mutations. -3. **Recovery:** The recovery sweeper uses the payloads stored in the log to roll forward stream writes on crash. +1. **Labelled 4-Shard Stream Lineage (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and provisions `SHARDS_PER_STREAM` (`4`) open `ShardMeta` rows (`00..03`) in `__extenddb_catalog__` at `stream_shard:`, where `shard_id = shardId-{table_id}-{label_millis:013}{view_digit:1}{index:02}` (61 characters, within the 65-character AWS SDK `ShardId` limit). Writes and `StreamEngine::assign_shard` route partition keys deterministically across open shards via `crc32fast::hash(pk_text.as_bytes()) % open.len()`, preserving strict per-item causal ordering while matching `SqliteEngine`'s shard fan-out. Disabling a stream stamps `ending_sequence_number` on all open shards while retaining `LatestStreamArn`, `LatestStreamLabel`, and closed shard/record history so disabled streams remain describable, listed by `ListStreams`, and readable under their original ARN while rejecting cross-stream `(newer_arn, older_shard_id)` pairings (`SHARD_DOES_NOT_EXIST` / `STREAM_DOES_NOT_EXIST`). +2. **Lock & Read:** Open a coordinator row (`PENDING`) in `__extenddb_txn_log__`, place `m:intent:` on the target row (retrying transient single-row intent contention), read the locked pre-image and `m:v`, and evaluate `ConditionExpression` (plus `removes_only` no-op detection on missing items for `UpdateItem`). On failure or no-op, clear the intent and drop the coordinator row without writing data or stream records. +3. **Sequence Allocation & Record Construction (`streams.rs`):** Allocate a fixed-width **26-digit decimal sequence number** (`{epoch_ms:013}{counter:09}{node_suffix:04}`, `StreamEngine::sequence_number_width() == 26`) that is strictly monotonic, lexicographically ordered, and parseable as `u128` for `AT_SEQUENCE_NUMBER` shard-iterator arithmetic in `extenddb-engine`. Build the `StreamRecord` (`INSERT`, `MODIFY`, or `REMOVE`) honoring `StreamCapture` (`view_type`, `region`, and optional TTL `user_identity`), suppressing no-op `MODIFY` events when `old_image == new_image`. +4. **Atomic Commit Point:** Write `COMMITTED` to `__extenddb_txn_log__` together with `t:mutations` and `t:stream_records` (carrying `(stream_arn, shard_id, record)`) *before* mutating column family `d`. +5. **Fenced Apply & Idempotent Ledger Write:** Apply the fenced `CheckAndMutateRow` mutation to the base table, update GSI shadow tables and TTL index entries, and persist each stream record to `__extenddb_catalog__` at deterministic row key `stream_record::`. Mark `CLEANED` and drop the coordinator row only after `streams::write_record` succeeds. +6. **Crash Recovery Idempotency:** If ExtendDB crashes after `COMMITTED` (before base-row apply or before `streams::write_record`), `TransactGetItems` immediately serves the committed post-image via the read-through-log rule, and `sweeper::sweep_once` rolls forward both the fenced data write and `streams::write_record`. Because the stream ledger row key is deterministic on `(shard_id, sequence_number)`, re-running `roll_forward` overwrites the identical JSON payload with zero duplicate stream records. -### 4. Scalable TTL Indexing & Streams Integration +#### B. Why the `__extenddb_catalog__` Table Ledger Beats Cloud Bigtable Native Change Streams +Cloud Bigtable offers a native Change Streams CDC feature (`ReadChangeStream`), which we evaluated and deliberately rejected in favor of the coordinator-fenced `__extenddb_catalog__` stream ledger for five architectural reasons: -Avoid full-table scans by introducing a sharded TTL index table. +1. **Transactional Commit Gating:** Bigtable Change Streams emit low-level per-row storage mutations immediately upon `MutateRow` / `CheckAndMutateRow` without awareness of `__extenddb_txn_log__`. Intent placements (`m:intent:`), rolled-back intents, or multi-table 2PC writes in progress would require a complex stateful stream-join consumer to buffer and filter against coordinator state. +2. **Item-Level `StreamViewType` Fidelity:** DynamoDB Streams require complete item-level `OldImage` and `NewImage` projections (`KEYS_ONLY`, `NEW_IMAGE`, `OLD_IMAGE`, `NEW_AND_OLD_IMAGES`) and exact `INSERT` vs. `MODIFY` vs. `REMOVE` classification. Bigtable Change Streams emit cell-level deltas (`SetCell`, `DeleteFromColumn`, `DeleteFromFamily`) and do not materialize prior full-row item images on partial updates or deletes. +3. **Shard Stability & `u128` Sequence-Number Contract:** Bigtable Change Streams dynamically split and merge tablet partitions and address positions via opaque `ChangeStreamContinuationToken`s, which cannot satisfy DynamoDB's stable shard topology, `u128`-parseable decimal `SequenceNumber` ordering (`AT_SEQUENCE_NUMBER` / `AFTER_SEQUENCE_NUMBER`), or 15-minute `ShardIterator` semantics. +4. **TTL Service `UserIdentity` Attribution:** DynamoDB requires TTL deletions to carry `userIdentity = { type: "Service", principalId: "dynamodb.amazonaws.com" }`. Native storage-level CDC carries no application caller or TTL service identity metadata. +5. **Hermetic Emulator & Zero-Admin Portability:** The official `cbtemulator` does not implement `ReadChangeStream`, whereas the `__extenddb_catalog__` ledger runs identically in hermetic CI (`cbtemulator`) and production GCP without requiring separate change-stream retention DDL on every user table. -#### A. TTL Index Table Schema -* **Table Name:** `__extenddb_ttl_index__` -* **Row Key format (Binary):** `[shard_id:1] [expiry_timestamp_be:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` - * `shard_id` (1 byte): `hash(base_row_key) % 16` (prevents write hotspotting). - * `expiry_timestamp_be` (8 bytes): Big-Endian `u64` representing the TTL epoch second. - * `encoded_base_row_key` (variable): Raw row key of the target item. -* **Payload:** None (empty values). -* **GC Rule:** `MaxVersions(1)` on family `d`. +### 4. Scalable TTL Indexing & Fenced Expiration -#### B. Maintenance -* **Writes:** Insert an empty row in `__extenddb_ttl_index__` when writing an item with a TTL attribute. -* **Updates/Deletes:** Delete the old index entry using the item's prior image. +#### A. Sharded TTL Index Schema (`__extenddb_ttl_index__`) +* **Row Key Binary Layout:** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` + * `shard_id = fnv1a(base_row_key) % 16` distributes writes and sweeps evenly across 16 prefixes instead of creating a monotonic timestamp hotspot. + * `expiry_epoch_secs_be` orders entries chronologically within each shard so each sweep reads only `[shard_id || 0, shard_id || (now + 1))`. +* **Write Maintenance:** `PutItem`, `UpdateItem`, `DeleteItem`, and `TransactWriteItems` parse TTL attributes via `parse_ttl_epoch_secs` (supporting integer, fractional, and scientific `AttributeValue::N` strings via `bigdecimal` while treating `<= 0` as non-expiring per DynamoDB semantics), removing stale TTL index keys when a prior item's TTL attribute changes or is deleted and inserting a new TTL index row when the post-image carries a positive numeric TTL epoch. -#### C. Sweeper Flow & Stream Emission -1. Perform parallel range scans across all 16 shards from `start_key = [S] [0]` to `end_key = [S] [current_time_epoch_s + 1]`. -2. For each expired entry, read the base row and verify its current TTL matches the index entry. -3. If valid, execute `delete_item` on the base table. -4. **TTL Stream Records:** When DynamoDB Streams are enabled on the table, TTL deletions emit a `REMOVE` stream record containing `userIdentity.type = "Service"` and `userIdentity.principalId = "dynamodb.amazonaws.com"`, matching native DynamoDB behavior. -5. If invalid (stale index), delete the index entry. +#### B. Live Verification, Metrics & Fenced TTL Stream Emission (`ttl_worker.rs`) +1. Under the distributed `lock:ttl_worker` catalog lease, scan `[shard || 0, shard || (now + 1))` across all 16 shards. +2. Confirm the table still exists and has `TimeToLiveStatus::Enabled`. If the table was dropped or TTL was disabled, delete the stale index row without touching base data. +3. Read the live base item (`DataEngine::get_item`) and verify its current TTL attribute (`parse_ttl_epoch_secs`) still equals the index row's `expiry` (`> 0` and `<= now`). If the item was already deleted or updated to a later or non-positive expiration timestamp, delete **only** the stale TTL index entry. +4. Issue `DataEngine::delete_item` with a `#ttl = :ttl_exp` `ConditionExpression` guard (preventing a race if a client extends TTL between step 3 and step 4) and, when streams are enabled on the table, a `StreamCapture` carrying `UserIdentity { principal_id: "dynamodb.amazonaws.com", identity_type: "Service" }`, recording `TimeToLiveDeletedItemCount` and `TtlStalenessSeconds` in `MetricsCollector`. Because stream-enabled `delete_item` executes through `execute_fenced_single_item_write`, the base-row deletion and TTL `REMOVE` stream record are atomically fenced in `__extenddb_txn_log__`. -### 5. GSI Projections & Consistency +### 5. Query, Scan & GSI Consistency -#### A. Projection Validation & ConsistentRead Rejection -Enforce DynamoDB GSI projection behavior: -* **Read Path:** Queries on GSIs with `KEYS_ONLY` or `INCLUDE` projections return only the projected attributes. -* **Validation:** If the client requests `Select: ALL_ATTRIBUTES` (or requests non-projected attributes) on a non-`ALL` GSI, return `ValidationException`. Do not perform base table fetches. -* **ConsistentRead Rejection:** Queries on GSIs with `ConsistentRead = true` are rejected with `ValidationException` (matching DynamoDB API rules). -* **Defaulting:** If `Select` is omitted in a GSI query, default to `Select::AllProjectedAttributes`. +* **Query Direction & `cbtemulator` Compatibility (`query_scan.rs`):** Forward and reverse `Query` calls (`ScanIndexForward`) construct tight byte-range bounds over `[pk_prefix, pk_upper]` (merging `ExclusiveStartKey` into the active sort-key range bound so `BETWEEN` and `begins_with` never lose their upper/lower bounds across pages, [RFC-0003](0003-backend-acceptance-criteria.md) §2.6, and short-circuiting inverted/empty bounds such as `BETWEEN :hi AND :lo` where `:hi > :lo` before issuing an RPC). Production Cloud Bigtable executes descending queries server-side via `ReadRowsRequest { reversed: true }`; when running against `cbtemulator` (which returns `UNIMPLEMENTED` or `FAILED_PRECONDITION` for `reversed: true`), `QueryScan::query` automatically falls back to a bounded partition scan plus in-memory reversal with identical `LastEvaluatedKey` semantics. +* **Exact `LastEvaluatedKey` & Parallel Scan Completeness:** Both `Query` and `Scan` fetch `limit + 1` storage rows so `LastEvaluatedKey` is emitted if and only if unread items remain in the range ([RFC-0003](0003-backend-acceptance-criteria.md) §7.2). Parallel scans (`total_segments > 1`) page through storage in chunks until `limit + 1` in-segment items (`crc32(pk_prefix) % total_segments == segment`) are collected or the table exhausts, avoiding premature segment termination under key skew (§7.3). +* **GSI Projections, Key Validation & TOCTOU-Safe Background Reconciler (`gsi.rs`, `gsi_worker.rs`):** `PutItem`, `UpdateItem`, and `TransactWriteItems` validate GSI/LSI key scalar types and non-emptiness upfront (`validate_index_keys`, `validate_index_key_literal_operands`, `validate_index_key_types_after_update`) and validate `UpdateAction` operands prior to `removes_only` missing-item short-circuits (`#478`). Shadow writes synchronously project `ALL`, `KEYS_ONLY`, or `INCLUDE` attributes at the base write's deterministic OCC timestamp. `gsi_worker::run` periodically scans shadow-to-base and base-to-shadow (using pre-encoded composite shadow keys via `ItemOps::batch_get_by_raw_keys`) under `lock:gsi_reconciler`; whenever divergence is detected, it atomically re-reads `(fresh_base_row, fresh_ver)` via `ItemOps::get_with_version` and stamps repaired GSI shadow cells at `version_to_timestamp_micros(fresh_ver)` so concurrent base updates are never masked by wall-clock timestamps. -#### B. Background Reconciler -Implement a reconciler as an internal background worker spawned via `ServerRuntimeHooks::spawn_workers`. The worker scans GSIs, compares them with the base tables, and repairs missing, orphaned, or mismatched shadow rows, preventing phantom records from returning during divergence windows. - -### 6. GCP Credentials & Bigtable Configuration - -Extend `BigtableStorageConfig` to support explicit service account files and app profiles: +### 6. GCP Connectivity, Secret Key Ring, Catalog Stores & Error Classification ```toml [storage.bigtable] -project_id = "my-project" -instance_id = "my-instance" -data_instance_id = "my-data-instance" # Optional (separates catalog/data) -app_profile_id = "default" # Optional (requires single-cluster routing for CheckAndMutateRow) -credentials_path = "/path/to/sa-key.json" # Optional (service account JSON) +project_id = "my-gcp-project" +instance_id = "my-bt-instance" +data_instance_id = "my-bt-data-instance" # Optional: separate catalog and data instances +app_profile_id = "single-cluster-profile" # Recommended: single-cluster routing for CheckAndMutateRow +credentials_path = "/etc/extenddb/sa.json" # Optional: explicit GCP service-account JSON key +# emulator_host = "127.0.0.1:8086" # Optional: local cbtemulator endpoint pool_size = 20 +catalog_pool_size = 8 +sweeper_cadence_secs = 30 +intent_timeout_secs = 60 +ttl_scan_cadence_secs = 60 +gsi_reconcile_cadence_secs = 300 ``` -* **Behavior:** If `credentials_path` is specified, the server programmatically acquires tokens from the service account key. Configure `tonic` channels with `ClientTlsConfig` using native system roots. -* **App Profile:** If `app_profile_id` is specified, data client requests use the designated profile to ensure single-cluster routing for conditional mutations. - -### 7. Future Work & Non-Goals - -* **Backup / PITR / Export (`BackupEngine`):** `BigtableEngine` implements the `extenddb_storage::BackupEngine` supertrait with explicit `StorageError::Internal("Operation not supported")` stubs. Point-in-Time Recovery (PITR), native Bigtable table backups, and Cloud Storage (GCS) exports require dedicated lifecycle orchestration and are deferred to a dedicated follow-up RFC. Note that Cloud Bigtable's native backup retention windows and export capabilities have distinct operational characteristics from DynamoDB's fixed 35-day PITR window. +* **Safe Client Construction & Split-Instance Isolation (`data/client.rs`):** `BigtableClient::connect` builds emulator connections via `BigTableConnection::new_with_emulator` and explicit service-account connections via `gcp_auth::CustomServiceAccount::from_file` + `BigTableConnection::new_with_token_provider` without any `unsafe` process-environment mutation (`std::env::set_var`) or `Box::leak` allocations. When `data_instance_id` differs from `instance_id`, catalog tables, distributed worker leases (`lock:*`), and stream ledger records stay strictly on `instance_id` (`catalog_client` sized by `catalog_pool_size`) while user data tables, GSI shadow tables, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` live strictly on `data_instance_id` (`data_client` sized by `pool_size`). +* **Thin-Binary Compile-Time Registration (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` so standard `cargo build` / `cargo check` invocations work unchanged, while exposing a mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`) that installs `extenddb_storage_bigtable::backend()` via `extenddb_storage::set_backend` with zero edits to `crates/core`, `crates/engine`, `crates/auth`, or `crates/server`. +* **At-Rest Secret Encryption & KEK/DEK Key Ring (`extenddb_storage::secret_keys`):** `m0001_baseline` seeds a unique `setting:catalog_id` UUID, and `BigtableCatalogStore` / `BigtableCredentialStore` encrypt and decrypt `AKIA*` access-key secrets and `ASIA*` STS session secrets via `SecretKeys` (`SecretRow::access_key` and `SecretRow::session` AAD binding `(table, access_key_id, account_id, principal, session_name, expires_at)`). `SettingsStore::replace_setting` uses single-row `CheckAndMutateRow` compare-and-swap (`Catalog::compare_and_swap_raw` / `put_if_absent`), and `ManagementStore` implements cursor-paged `read_secret_page`, `write_secrets`, `delete_secrets`, and `delete_setting` to support `extenddb encryption-key switch`, `rotate`, `rewrap`, and `reset`. +* **IAM Leftover Hygiene, Operational Metrics & Login Rate Limiting (`catalog_store.rs`):** Deleting or creating a user, group, role, or account atomically purges associated policies, permission boundaries, tags, memberships, access keys, and `failed_login:/` rate-limit entries (`iam_leftovers_conformance`). `MetricsStore` accumulates minute-bucketed metrics keyed by `metric::` via CAS retry and supports retention pruning (`metrics_conformance`). +* **Frozen Baseline & Additive Migration Ledger (`m0001_baseline.rs`, `migrations.rs`):** `m0001_baseline.rs` (`#[rustfmt::skip]`) provisions `__extenddb_catalog__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` plus `setting:catalog_id`; `MigrationId`s `2..=12` record cleanly as schema-less no-ops in `migration_ledger:catalog:` under `lock:catalog_migrations`. +* **gRPC Transient Error Classification (`data/client.rs`):** Data-plane and catalog errors are classified via `map_bigtable_err`, `map_catalog_err`, and `classify_grpc_status`: + * `Unavailable`, `DeadlineExceeded`, `Aborted`, `ResourceExhausted`, RPC timeouts, and transient I/O errors map to `StorageError::Transient` (surfaced by the server as retryable HTTP 503 `ServiceUnavailable` rather than opaque HTTP 500s). + * Transport connection failures map to `StorageError::Connection`. + * `InvalidArgument` and `OutOfRange` map to `StorageError::Validation` (HTTP 400). + * `Unimplemented` maps to `StorageError::Unsupported` (HTTP 400). + +### 7. Backup, Snapshot, Restore & Point-in-Time Recovery + +* **Explicit `StorageError::Unsupported` Refusal (`backup_stubs.rs`):** Cloud Bigtable does not provide cross-table point-in-time snapshot reads on the data plane, and GCP-native Cloud Bigtable Backups operate asynchronously through the GCP Admin API rather than ExtendDB's logical/store-backed backup format. `BigtableEngine` implements `SnapshotEngine`, `LegacyBackupReader`, `BackupCatalog`, and `RestoreEngine` by returning `StorageError::Unsupported` on all user-facing backup, snapshot, and restore operations (`CreateBackup`, `DescribeBackup`, `ListBackups`, `DeleteBackup`, `RestoreTableFromBackup`), which `extenddb-engine` maps cleanly to `ValidationException` (HTTP 400) rather than `InternalServerError` (HTTP 500). Passive background `BackupReconciler` queries (`check_maintenance_claim`, `list_dead_restore_jobs`, `abandoned_creating_backups`, `list_backup_rows`) return empty `Ok` results so `extenddb serve` runs cleanly without log noise. +* **Point-in-Time Recovery (`#335`):** `DescribeContinuousBackups`, `UpdateContinuousBackups`, and `RestoreTableToPointInTime` are owned directly by `extenddb-engine`, consulting `BigtableEngine::describe_table` solely for table existence. + +### 8. Deliverables & Trait Conformance Matrix + +Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-acceptance-criteria.md), `crates/storage-bigtable` implements the full ExtendDB `v1.0.0` backend surface as follows: + +| Trait / Subsystem | Classification | Status | Implementation Module | Notes | +|---|---|---|---|---| +| `TableEngine` | Mandatory (Data/Control) | Implemented | `src/engine.rs` | `CreateTable`, `DeleteTable`, `DescribeTable`, `ListTables`, `UpdateTable` (with 4-shard `stream_lineage` transitions), `table_key_info`, `index_info`, `index_info_by_table_id` | +| `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with deterministic `occ_version * 1000` timestamps, `GetItem`, `Query`, `Scan`, `scan_key_in_segment`, ABA-fenced 2PC `TransactWriteItems`, read-through-log `TransactGetItems` | +| `VectorSearchEngine` | Optional (`as_vector_search`) | Opted out (`None`) | `src/engine.rs` | Engine rejects vector index DDL and `SearchVectors` upfront | +| `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | Resource tagging (`TagResource`/`UntagResource`/`ListTagsOfResource`) + 16-shard `__extenddb_ttl_index__` with `parse_ttl_epoch_secs` | +| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item, TTL, and 2PC streams; 4-shard CRC32 partition-key routing + `stream_lineage` disable/re-enable history; 26-digit `u128` decimal sequence numbers | +| `WorkerStore` | Optional (Lifecycle) | Implemented | `src/engine.rs` | Inline `ACTIVE` table creation (`process_control_plane_transitions` no-op) | +| `SnapshotEngine`, `BackupCatalog`, `LegacyBackupReader`, `RestoreEngine` | Optional (Backup/Restore) | Explicit Refusal | `src/backup_stubs.rs` | User operations return `StorageError::Unsupported` (`ValidationException` HTTP 400); passive reconciler probes return empty `Ok` | +| `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM users/groups/roles/policies/boundaries/tags, STS sessions, password-hash persistence, `SecretKeys` KEK/DEK paging & rotation | +| `AuthorizationStore` | Mandatory (Authz) | Implemented | `src/catalog_store.rs` | User/group/role policies, permission boundaries, resource/principal tags, RFC 3339 `created_at` | +| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, table/index diagnostics | +| `CredentialStore` | Mandatory (`SigV4` Auth) | Implemented | `src/catalog_store.rs` | `AKIA*` + `ASIA*` `SecretKeys` decryption with `SecretRow` AAD, `ExpiredTokenException`, and inactive-key S-5 propagation | +| `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | Idempotent catalog/key/account/admin bootstrap (`catalog_key_present`, `data_connection_present`) and `destroy` cleanup | +| `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | Exhaustive `MigrationId` 1..=12 coverage, frozen `m0001_baseline.rs` checksum, `lock:catalog_migrations` lease | +| `OperationsEngine` | Mandatory (CLI) | Implemented | `src/operations.rs` | Connection URL parsing, identifier validation, sensitive-key redaction | +| `ServerRuntimeHooks` | Mandatory (Workers) | Implemented | `src/runtime_hooks.rs` | Spawns 6 lease-guarded workers (`ttl_worker` with metrics, 2PC `sweeper`, `gsi_reconciler`, 24h `stream_record_cleanup`, 10m `idempotency_token_cleanup`, 5m `table_size_refresh`) with `CancellationToken` shutdown | ## Testing Strategy -1. **Unit Tests (Emulator-based):** - * Verify exact decimal number key encoding/decoding and numerical sorting up to 38 significant digits. - * Verify row key 4KB size enforcement and partition length prefixing vs raw sort key ordering. - * Verify OCC row versioning (`m:v`) decoding and composite `CheckAndMutateRow` filter construction. - * Verify 2PC coordinator state transitions, fenced apply predicate, and idempotency token deduplication. - * Assert `ValidationException` is returned for invalid GSI attribute requests and `ConsistentRead = true` on GSIs. - * Assert `BackupEngine` methods return `StorageError::Internal("Operation not supported")`. -2. **Failure Integration Tests (Real Bigtable & Emulator):** - * Inject crashes during the 2PC flow and assert that the recovery sweeper rolls forward/back using fenced mutations and preserves stream record writes. - * Run concurrent mixed workloads to verify transactional serializability and OCC conflict detection on single-row writes. - * Verify GSI reconciler heals base-to-shadow mismatches. - * Verify TTL sweeper emits `REMOVE` stream records with the TTL principal and ignores updated items with old index entries. -3. **E2E & Chaos Tests:** - * Run the Python integration suite (`devtools/run-tests --extenddb --pytest`) against production Bigtable. - * Inject network partitions during `TransactWriteItems` to verify 2PC resilience. +1. **Pure Unit Tests (`cargo test -p extenddb-storage-bigtable --lib`):** + * Exact 38-digit decimal `N` encoding/decoding, zero normalization, and full-spectrum lexicographic order (`number.rs`). + * Row-key 4 KiB limit enforcement, partition length prefixing, raw terminal sort-key ordering, and FDB escape-encoded GSI sort-key roundtrips (`row_key.rs`, `gsi.rs`, `ttl_key.rs`). + * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`), `parse_ttl_epoch_secs` decimal/zero/negative parsing, 3-case De Morgan `select_occ_predicate` and ABA-safe `build_fenced_apply_predicate` `RowFilter` construction (`item_ops.rs`, `transact.rs`), RE2 metacharacter escaping and `monotonic_timestamp_after_micros` (`client.rs`), URL-encoded query parameter / TOML / `string_coerce` env-var config roundtripping (`config.rs`, `bootstrapper.rs`), 26-digit `u128` stream sequence numbers and TTL `UserIdentity` propagation (`streams.rs`), gRPC transient error mapping (`client.rs`), `check_released` migration checksum invariants (`migrations.rs`), and `StorageError::Unsupported` backup/snapshot/restore stubs (`backup_stubs.rs`). +2. **Live Bigtable Emulator Integration & Conformance Suite (`tests/emulator_integration.rs` against `cbtemulator`):** + * Catalog bootstrap, `BigtableCatalogMigrations` baseline run, table DDL lifecycle, and split catalog-vs-data instance (`data_instance_id != instance_id`) isolation across `BigtableBootstrapper` and background workers (`sweeper`, `ttl_worker`, `gsi_worker`). + * Guarded single-row CRUD, `ConditionExpression` evaluation, arithmetic `UpdateItem`, `removes_only` missing-item no-ops, and `#478` invalid-operand rejection on missing items. + * Deterministic OCC cell timestamps (`m:v * 1000` shared across all cells), post-`DeleteItem` `m:v` tombstone retention and rapid re-insert monotonicity, concurrent 10-way `UpdateItem` counter increments (zero lost updates), and 8-way conditional `PutItem` races (1 winner, 7 `ConditionFailed`). + * Multi-table 2PC `TransactWriteItems`, atomic condition-failure rollback, reused `ClientRequestToken` tombstone safety after Phase 1 abort, post-lease-expiry ABA fencing across base and GSI shadow rows, idempotency replay/mismatch, and concurrent `TransactGetItems` read-through-log verification (`COMMITTED` vs. `PENDING`). + * Fenced single-item stream emission (`INSERT`/`MODIFY`/`REMOVE`) across `SHARDS_PER_STREAM` (`4`) CRC32-routed shards, `ImportTable` `stream: None` bulk-import suppression, post-`COMMITTED` crash recovery and pre-`COMMITTED` crash rollback via `sweeper::sweep_with_cutoff_override` without duplicates or phantom records, and full stream disable/re-enable lineage (`stream_lineage`) + cross-stream shard isolation. + * Exact decimal range queries, inverted `BETWEEN` range guards, reverse `Query` (`ScanIndexForward = false`) pagination, GSI escape-encoded `begins_with` queries, upfront secondary-index key validation, TOCTOU-safe GSI reconciler OCC-timestamp repair, runtime GC helpers (`cleanup_expired_idempotency_tokens`, `cleanup_expired_stream_records`), and TTL sweeper fractional/scientific/zero/negative re-verification + `MetricsCollector` recording + fenced `dynamodb.amazonaws.com` `REMOVE` stream emission. + * Upstream shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, `key_conformance::run` (`switch`/`rotate`/`rewrap`/`reset`), and `BigtableCredentialStore` `AKIA*` + `ASIA*` (`ExpiredTokenException`) verification. +3. **End-to-End Conformance (`devtools/run-tests`):** + * Wire-level Rust and pytest conformance suites against an `extenddb` binary built with `--no-default-features --features bigtable`. ## Alternatives Considered -* **Unprotected Single-Row Writes:** Bypassing intent checks for single-row writes allows dirty writes, violating serializability. Rejected. -* **Scan-Based TTL Sweeper:** Scanning the entire base table to evict items degrades performance at scale. Rejected. -* **Length-Prefixed Sort Keys:** Length-prefixing sort keys in composite primary keys caused sort inversion where shorter string/numeric representations sorted before longer ones regardless of value. Rejected in favor of raw order-preserving sort key bytes. -* **Cloud Spanner Backend:** Cloud Spanner supports multi-row transactions natively, eliminating the need for application-layer 2PC. This is a viable alternative to be explored as a separate backend connector. +* **Server-Assigned Cell Timestamps (`timestamp_micros: -1`):** Simpler to construct, but risks torn rows under `MaxNumVersions(1)` when two writers or recovery sweeps touch the same row in a narrow window or under clock skew. Rejected in favor of deterministic OCC-derived millisecond-aligned timestamps (`occ_version * 1_000`). +* **Unfenced Trailing Stream Writes on Single-Item Operations:** Lower write amplification (1 RPC instead of coordinator log + fenced apply), but loses stream records if the process crashes after the base-row mutation lands. Rejected because [RFC-0003](0003-backend-acceptance-criteria.md) §5.1 requires strict atomicity between data visibility and stream record durability. +* **Cloud Bigtable Native Change Streams (`ReadChangeStream`):** Rejected for the five reasons detailed in §3.B (lack of 2PC coordinator commit gating, missing pre-image `StreamViewType` reconstruction, dynamic tablet-split continuations incompatible with DynamoDB `ShardIterator` / `u128` `SequenceNumber`s, missing TTL `Service` `UserIdentity`, and lack of `cbtemulator` support). +* **Unprotected Single-Row Writes / Full-Table Scan TTL / Length-Prefixed Sort Keys:** Rejected due to dirty-write isolation violations, $O(N)$ scan cost at scale, and lexicographic sort inversion respectively. +* **Cloud Spanner Backend:** Provides native multi-row serializable transactions without application-layer 2PC, and remains a viable separate backend candidate for relational/Spanner-invested GCP environments. + +--- + +## License + +Copyright 2026 ExtendDB contributors. Licensed under the Apache License, Version 2.0. +See [LICENSE](../../LICENSE) for the full text. + +This software is provided "as is" without warranty of any kind. ExtendDB is not +affiliated with, endorsed by, or sponsored by Amazon Web Services. "DynamoDB" is +a trademark of Amazon.com, Inc. From defe9b70690f40e2bc6f829315d58c4726dafe1b Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Fri, 20 Nov 2026 15:25:18 +0000 Subject: [PATCH 07/11] docs(rfc): sync RFC with 2PC, stream, GSI, TTL, and LSI changes --- docs/rfcs/0000-bigtable-backend.md | 148 ++++++++++++++++------------- 1 file changed, 80 insertions(+), 68 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index 62743f97c..74a964ce7 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -7,7 +7,7 @@ ## Summary -This RFC defines the design and implementation of a production-grade Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0`. It addresses transaction isolation and serializable read-through-log snapshots, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection, fenced two-phase commit (2PC) apply, unified write-ahead fenced DynamoDB Streams emission with full disable/re-enable shard lineage (`stream_lineage`), FoundationDB tuple escape-encoded Global Secondary Index (GSI) keys and projections, sharded Time-to-Live (TTL) indexing, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, IAM/metrics/rate-limit catalog conformance, gRPC transient-error classification, application-profile single-cluster routing, and Google Cloud Platform (GCP) authentication. +This RFC defines the design and implementation of a production-grade Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0`. It addresses transaction isolation and serializable read-through-log snapshots, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection and Cloud Bigtable's millisecond granularity, incarnation-fenced two-phase commit (2PC) apply, unified write-ahead fenced DynamoDB Streams emission with contiguous per-shard sequence slots and disable/re-enable shard lineage (`stream_lineage`), FoundationDB tuple escape-encoded Global Secondary Index (GSI) keys and version-guarded shadow projections, sharded Time-to-Live (TTL) indexing, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, CAS-guarded IAM/metrics/DDL catalog conformance, gRPC transient-error classification, application-profile single-cluster routing, and Google Cloud Platform (GCP) authentication. ## Motivation @@ -15,10 +15,10 @@ Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-at 1. **Transaction Isolation & TOCTOU Races:** Naive read-modify-write conditional operations evaluate `ConditionExpression`s without atomic concurrency control, allowing concurrent writers to overwrite uncommitted state or bypass 2PC locks. 2. **Cell Timestamps vs. `MaxNumVersions(1)` Compaction:** Relying on server-assigned cell timestamps (`SetCell.timestamp_micros = -1`) allows tablet-server wall-clock differences or narrow concurrency windows to interleave cells from distinct writes across qualifiers (`d:*` vs. `m:v`), producing torn rows once `MaxNumVersions(1)` compaction runs. -3. **2PC Race Conditions (Read-then-Lock & Unfenced Apply):** Reading participant rows before placing intent locks exposes `TransactWriteItems` to TOCTOU races, while applying Phase 2 mutations unconditionally allows stalled coordinators whose intents were swept to overwrite newer committed data. -4. **Unfenced Stream Emission:** Emitting DynamoDB Stream records as an unfenced trailing write after mutating the base table loses stream records if the server crashes in the gap, violating [RFC-0003](0003-backend-acceptance-criteria.md) §3.2 and §5.1. -5. **Inefficient TTL Eviction:** Full-table scans to identify expired items degrade read throughput at scale and risk deleting items whose TTL attribute was concurrently extended. -6. **GSI Sort-Order & Consistency:** Non-terminal sort keys in composite GSI row keys suffer sort inversion unless escape-terminated, and shadow-table write failures require background reconciliation to heal base-to-shadow divergence. +3. **2PC Race Conditions (Read-then-Lock, Unfenced Commit/Abort & Unfenced Apply):** Reading participant rows before placing intent locks exposes `TransactWriteItems` to TOCTOU races; unconditional coordinator `COMMITTED` writes or unfenced sweeper rollbacks allow partial 2PC commits; and applying Phase 2 mutations unconditionally allows stalled coordinators whose intents were swept to overwrite newer committed data. +4. **Unfenced Stream Emission & Out-of-Order Shard Visibility:** Emitting DynamoDB Stream records as an unfenced trailing write loses stream records if the server crashes in the gap ([RFC-0003](0003-backend-acceptance-criteria.md) §3.2, §5.1), while pre-allocating global sequence numbers in Phase 1 allows a later sequence number (`seq_2 > seq_1`) to persist before `seq_1` on the same shard and cause `AFTER_SEQUENCE_NUMBER` consumers to permanently skip `seq_1` (§5.2). +5. **Inefficient & ABA-Prone TTL Eviction:** Full-table scans degrade read throughput at scale, while unlocked trailing TTL index maintenance or unbounded index row deletes suffer `1000 -> 2000 -> 1000` ABA races and risk wiping concurrent same-second TTL inserts. +6. **GSI Sort-Order, Online Lifecycle & Shadow Consistency:** Non-terminal sort keys in composite GSI row keys suffer sort inversion unless escape-terminated, online `UpdateTable` GSI builds must backfill existing rows before serving queries, and delayed writers or reconcilers (`v1 < v2`) must never clobber newer `v2` shadow state via unbounded `DeleteFromFamily` or `DeleteFromRow`. 7. **Multi-Cluster Routing & Auth Constraints:** Cloud Bigtable rejects `CheckAndMutateRow` under multi-cluster routing with eventual consistency unless routed via a single-cluster application profile, and enterprise deployments require explicit service-account credential configuration. ## Detailed Design @@ -26,11 +26,11 @@ Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-at ### 1. Table Mapping & Key Encoding #### A. Table Structure & Naming -* **Catalog & Stream Ledger (`__extenddb_catalog__`):** Stores system settings (`setting:catalog_id`, `setting:encryption_key`, `setting:encryption_key_ring`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIA*` access keys and `ASIA*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:`), distributed worker leases (`lock:`), stream shard lineage rows (`stream_shard:`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). -* **Coordinator Transaction Log (`__extenddb_txn_log__`):** Stores coordinator state (`t:state`), start timestamp (`t:started_at`), participant list (`t:participants`), pre-computed mutations (`t:mutations`), and pre-generated stream records (`t:stream_records`) in column family `t`. -* **Sharded TTL Index (`__extenddb_ttl_index__`):** Stores expiration index entries across 16 hash shards in column family `d`. +* **Catalog & Stream Ledger (`__extenddb_catalog__`):** Stores system settings (`setting:catalog_id`, `setting:encryption_key`, `setting:encryption_key_ring`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIA*` access keys and `ASIA*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:`), distributed worker leases (`lock:`), stream shard lineage/cursor rows (`stream_shard:` carrying `next_seq_num` and `last_sequence_number`), per-event stream deduplication markers (`stream_dedup::`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). +* **Coordinator Transaction Log (`__extenddb_txn_log__`):** Stores coordinator state (`t:state`), incarnation start timestamp (`t:started_at`), canonical sorted participant list (`t:participants`), pre-computed mutations (`t:mutations`), pre-generated stream records (`t:stream_records`), logged TTL index transitions (`t:ttl_mutations`), and `ClientRequestToken` metadata (`t:token_meta`) in column family `t`. +* **Sharded TTL Index (`__extenddb_ttl_index__`):** Stores OCC-timestamped, millisecond-aligned expiration index entries across 16 hash shards in column family `d`. * **Data Tables (`t`):** Each DynamoDB table maps to a dedicated Bigtable table named `t` followed by the first 16 lowercase hex characters of the table's unique `table_id` UUID (17 characters total). Deriving physical table names from `table_id` rather than `table_name` guarantees clean isolation across accounts and across `DeleteTable` + `CreateTable` name reuse ([RFC-0003](0003-backend-acceptance-criteria.md) §8.2). Data attributes live in column family `d` (one qualifier per top-level attribute); OCC row versions (`m:v`) and 2PC intent locks (`m:intent:`) live in column family `m`; column family `t` is reserved. -* **GSI Shadow Tables (`t_g`):** Each GSI maps to a shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit). +* **GSI Shadow Tables (`t_g`):** Each GSI maps to a shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit), storing projected item attributes in column family `d` and base-row OCC version guards (`m:v`) in column family `m`. #### B. Exact Decimal & Order-Preserving Key Encoding Cloud Bigtable sorts row keys by unsigned raw byte lexicographical order and enforces a **4 KiB (4096-byte)** row-key limit, validated upfront in `row_key::encode_key` and `gsi::shadow_row_key_for_item`. @@ -62,11 +62,15 @@ Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, ` ### 2. Transaction Rules, Deterministic OCC Timestamps & Isolation Guarantees #### A. Transaction Validation & Idempotency Rules -* **`ClientRequestToken` Idempotency:** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a 10-minute window and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`. Replays with matching operation fingerprints return `IdempotentReplay` (rolling forward first if the coordinator row is `COMMITTED`); mismatched payloads return `IdempotentMismatch`. -* **Duplicate Participant Rejection:** Any `TransactWriteItems` request targeting the same `(data_table, row_key)` more than once is rejected upfront with `ValidationException`. +* **`ClientRequestToken` Idempotency (`RFC-0003` §3.3):** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a strict **10-minute (`600s`) `applied_at` window** (`check_idempotency_record` evicts expired entries via `Catalog::mutate_json_cas`) and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`: + * `TxnCoordinator::open_with_token` atomically persists `TxnTokenMeta` (`account_id`, `token`, `fingerprint`) in `t:token_meta` alongside `t:state = PENDING` and `t:started_at`, returning `(created, started_at_micros)`. + * When `created == true`, the caller immediately re-verifies `idem::` (rolling back and dropping its nascent `PENDING` incarnation if a prior winner persisted `idem:` and dropped `txn:` between pre-check and `open_with_token`). + * When `created == false`, the caller never strips intents belonging to an active concurrent owner; instead, the follower loop validates `t:token_meta.fingerprint` across `PENDING`, `COMMITTED`, and `CLEANED` states (returning `IdempotentMismatch` immediately on payload mismatch without poisoning `idem:`, and cooperatively rolling forward `COMMITTED` transactions before returning `IdempotentReplay`). + * Both inline Phase 2 (`roll_forward`) and `sweeper::sweep_with_cutoff_override` (on both `COMMITTED` and `CLEANED` coordinator rows) persist `idem::` via `persist_idempotency_if_unexpired` **before** marking `CLEANED` and calling `drop_matching_start`, while Phase 1 `ConditionFailed` rollbacks drop `txn:` without writing `idem:` so retries with the same token can execute cleanly. +* **Duplicate Participant Rejection & Canonical Lock Ordering (`RFC-0003` §3.4):** Any `TransactWriteItems` request targeting the same `(data_table, row_key)` more than once is rejected upfront with `ValidationException`. Participant locks are acquired in canonical `(data_table, row_key)` lexicographical order (`ParticipantRow: Ord`) to prevent `[k1, k2]` vs. `[k2, k1]` deadlocks while preserving caller-order indices on `StorageError::TransactionCanceled(reasons)` (never leaking `StorageError::TransactionConflict` from 2PC, and honoring per-item `ReturnValuesOnConditionCheckFailure::None` vs. `AllOld`). #### B. Lock-then-Read Coordinator 2PC Flow -`TransactWriteItems` acquires per-row intents *before* reading participant rows and evaluating condition expressions, commits atomically in `__extenddb_txn_log__`, applies mutations via fenced `CheckAndMutateRow`, and acknowledges HTTP 200 OK only after Phase 2 mutations and stream records are durable: +`TransactWriteItems` acquires per-row intents in sorted order *before* reading participant rows and evaluating condition expressions, transitions `(t:state == PENDING && t:started_at == started_at_micros) -> COMMITTED` via incarnation-fenced CAS `CheckAndMutateRow` in `__extenddb_txn_log__`, applies mutations idempotently via `roll_forward`, and acknowledges HTTP 200 OK only after Phase 2 mutations, GSI shadows, TTL transitions, stream records, and `idem:` entries are durable: ```mermaid sequenceDiagram @@ -74,78 +78,82 @@ sequenceDiagram participant L as __extenddb_txn_log__ participant B as Bigtable Data / GSI / Catalog - C->>L: Phase 1: Open Coordinator Row (t:state = PENDING) - loop Each participant row - C->>B: Place Intent (CheckAndMutateRow: fail if unexpired m:intent:* exists) + C->>L: Phase 1: open_with_token (CheckAndMutateRow: t:state = PENDING, t:started_at, t:token_meta) + loop Each participant row in sorted (data_table, row_key) order + C->>B: place_intent_once (CheckAndMutateRow: fail if any m:intent:* exists; cooperatively resolve stale/COMMITTED) end alt Intent Contention Exhausts Retries - C->>B: Clear placed intents & drop coordinator row + C->>L: try_abort_pending (CAS PENDING + started_at -> ABORTED) + C->>B: Clear placed intents & drop_matching_start Note over C: Return TransactionCanceled (TransactionConflict) end C->>B: Read locked participant rows & capture OCC versions (m:v) Note over C: Evaluate ConditionExpressions & compute next_occ_version alt Any Condition Fails - C->>B: Clear intents & drop coordinator row - Note over C: Return TransactionCanceled (ConditionalCheckFailed) + C->>L: try_abort_pending (CAS PENDING + started_at -> ABORTED) + C->>B: Clear intents & drop_matching_start + Note over C: Return TransactionCanceled (ConditionalCheckFailed honoring ReturnValuesOnCCF) end - C->>L: Phase 2 Commit: DeleteFromColumn(t:state, [0, commit_ts)) + SetCell(COMMITTED, mutations, stream_records) @ commit_ts > started_at - loop Each mutated participant - C->>B: Fenced Apply (if m:intent: && OCC state == expected: write d:* & m:v at occ_ts, retain intent) - C->>B: Update GSI shadow rows (at occ_ts) & TTL index + C->>L: Phase 2 Commit: try_commit_full (CAS PENDING + started_at -> COMMITTED, mutations, stream_records, ttl_mutations) + loop Each mutated participant (roll_forward) + C->>B: apply_fenced_mutation (if m:intent: && OCC state == expected: write d:* & m:v at occ_ts, retain intent) + C->>B: Version-guarded GSI shadow updates (put/delete_shadow_versioned) & OCC-bounded TTL index updates end - C->>B: Write pre-generated stream records to __extenddb_catalog__ + C->>B: Append contiguous per-shard stream slot (write_record_ordered + stream_dedup) + C->>B: Persist idem:: (if t:token_meta present) loop Each locked participant C->>B: Clear intent (DeleteFromColumn m:intent:) end - C->>L: Mark CLEANED (@ clean_ts > commit_ts) & delete coordinator row + C->>L: Mark CLEANED (@ clean_ts > commit_ts) & drop_matching_start Note over C: Return HTTP 200 OK (Read-Your-Writes Boundary) ``` -#### C. Read Isolation & `TransactGetItems` Read-Through-Log Rule +#### C. Read Isolation, Incarnation-Fenced CAS Commit/Abort & `TransactGetItems` Double-Read Snapshot * **Read-Your-Writes Acknowledgment Boundary:** Success is returned only after Phase 2 mutations are applied to column family `d` and GSI shadow tables, guaranteeing `ConsistentRead = true` (`GetItem`, `Query`, `Scan`) and `TransactGetItems` immediately observe the committed state. * **Read Committed (No Dirty Reads):** Uncommitted transactions write only `m:intent:` in family `m`. Standard reads filter strictly on family `d` (`Chain([FamilyNameRegexFilter("^d$"), CellsPerColumnLimitFilter(1)])`) and never observe uncommitted writes. -* **ABA-Safe Fenced Phase 2 Apply & Intent Retention:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard (`(Some(v), _) -> m:v == v`; `(None, false) -> neither m:v nor d:* exists`; `(None, true) -> d:* exists && m:v absent`). Checking `(expected_version, row_existed)` guarantees that even if an intent lease expires and a newer writer advances `m:v` to `v2`, neither a slow coordinator nor `sweeper::roll_forward` can overwrite `v2` on the base row or apply superseded GSI shadow mutations (which `roll_forward` gates on `applied || cur_ver == Some(new_version)`). Furthermore, `m:intent:` is retained across base-row apply, GSI shadow updates, TTL index updates, and stream ledger persistence, and cleared via `clear_intent` only after stream records land. -* **Serializable `TransactGetItems` (Read-Through-Log Snapshot Rule):** `TransactGetItems` reads family `d` alongside any unexpired `m:intent:` cell (`ItemOps::batch_get_with_intent_check`) and resolves active intents via `TxnCoordinator::get_state`: - * **Intent Present & Coordinator `COMMITTED`:** Serves the committed post-image (`Some(item)` for `Put`, `None` for `Delete`) directly from `t:mutations` in `__extenddb_txn_log__`, even if Phase 2 apply has not yet reached that participant row. - * **Intent Present & Coordinator `PENDING` / `ABORTED` / `CLEANED` (or No Active Intent):** Serves the current committed image from family `d`. - * **Lazy Compaction Filter & Rank-Ordered Coordinator Timestamps:** Because Cloud Bigtable enforces `MaxNumVersions(1)` asynchronously during compaction, `TxnCoordinator::get_state` and `sweeper::sweep_once` **must** read `__extenddb_txn_log__` with `Chain([FamilyNameRegexFilter("^t$"), CellsPerColumnLimitFilter(1)])`. Coordinator transitions allocate millisecond-aligned timestamps via `monotonic_timestamp_after_micros(exclusive_floor_micros)` (`PENDING` at `t0 >= now`, `ABORTED`/`COMMITTED` at `t1 > t0`, `CLEANED` at `t2 > t1`) preceded by bounded `DeleteFromColumn(t:state, [0, ts_micros))`. Anchoring to wall-clock time while enforcing `ts > floor` guarantees `COMMITTED` strictly dominates `PENDING` across multi-node NTP skew and ensures retried `ClientRequestToken`s (`SHA-256(account_id || ":" || token)`) after a Phase 1 abort (`DeleteFromRow`) always stamp cells above the prior delete marker. +* **Incarnation-Fenced Mutual Exclusion Between `try_commit_full` and `try_abort_pending` (`RFC-0003` §3.1):** Both `TxnCoordinator::try_commit_full` (`PENDING -> COMMITTED`) and `TxnCoordinator::try_abort_pending` (`PENDING -> ABORTED`) execute `CheckAndMutateRow` predicated on `build_pending_incarnation_predicate(started_at_micros)` (applying `CellsPerColumnLimitFilter(1)` **before** `ValueRegexFilter` on `t:state == "PENDING"` and `t:started_at == started_at_micros`), and `sweeper` / inline cooperative recovery always CAS-transitions `PENDING -> ABORTED` **before** clearing any participant intent (if CAS fails because the coordinator concurrently reached `COMMITTED`, recovery immediately invokes `roll_forward`). Row drops use `drop_matching_start(txn_id, started_at_micros)` and stale intent cleanup uses timestamp-bounded `clear_intent_up_to` so a stale cleaner can never delete a newer reused token incarnation. +* **Zero Wall-Clock Intent Bypass & Cooperative Resolution (`RFC-0003` §3.1, §3.5, §4.2):** `build_active_intent_filter` and `build_intent_presence_filter` carry **no** wall-clock `TimestampRangeFilter`, because an intent older than `intent_timeout_secs` may belong to a `COMMITTED` coordinator awaiting roll-forward. Whenever a writer or worker encounters an intent on a row, `resolve_blocking_intents` / `read_row_resolving_committed_intents` inspects `__extenddb_txn_log__`: `COMMITTED` transactions are rolled forward immediately, timed-out `PENDING` transactions are CAS-aborted and cleaned up, and `ABORTED`/`CLEANED`/dropped intents are cleared safely. +* **ABA-Safe Fenced Phase 2 Apply & Side-Effect Gating:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard (`(Some(v), _) -> m:v == v`; `(None, false) -> neither m:v nor d:* exists`; `(None, true) -> d:* exists && m:v absent`). Unified `roll_forward` tracks `materialized_participants` (`applied || (cur_ver == Some(new_version) && payload_matches)`), gating GSI shadow writes, `TxnTtlMutation` maintenance, **and** `TxnStreamRecord` emission so superseded coordinators emit zero phantom side effects. +* **Serializable `TransactGetItems` via Optimistic Double-Read Snapshot Validation (`RFC-0003` §3.5, §9.1, §9.2):** `TransactGetItems` validates keys upfront via `validate_key_only` (returning `TransactionCanceled` with `ValidationError` reasons on malformed keys), deduplicates physical row keys while preserving positional output mapping, and executes a non-mutating double-read loop: + * **Pass 1:** Batch-reads `RowSnapshot` (`d:*`, `m:v`, and all `(m:intent:, ts_micros)` regardless of age) across all unique keys and queries `TxnCoordinator::get_state` for every referenced `txn_id`. + * **Pass 2 Validation:** Re-reads `RowSnapshot`s across all unique keys and re-queries referenced coordinator states, accepting the snapshot if and only if `(m:v, intents, d:*)` and coordinator `(state, started_at)` match identically across Pass 1 and Pass 2—proving a single linearization point across concurrent `PENDING -> COMMITTED`, `COMMITTED -> CLEANED -> drop`, and OCC updates. + * **Monotonic Coordinator `SetCell` Transitions:** State transitions (`PENDING` at `t0`, `ABORTED`/`COMMITTED` at `t1 > t0`, `CLEANED` at `t2 > t1`) write monotonic `SetCell(t:state)` values without `DeleteFromColumn(t:state, ...)`, and `get_state` treats any row lacking `t:state` as `Ok(None)`, eliminating transient `StorageError::Internal` HTTP 500s on `cbtemulator`. #### D. Deterministic OCC-Derived Cell Timestamps & Single-Row Concurrency Control Using server-assigned cell timestamps (`timestamp_micros: -1`) is unsafe under `MaxNumVersions(1)`: if two writers pass filters within a narrow window, or tablet servers experience slight clock skew across tablet moves or recovery roll-forward, `MaxNumVersions(1)` compaction retains whichever cell had the higher wall-clock arrival timestamp per qualifier rather than the higher logical OCC version, risking torn rows (`d:*` from one write paired with `m:v` or attributes from another). -To eliminate torn rows while satisfying Cloud Bigtable's **`TimestampGranularity::MILLIS`** rule (which rejects explicit `SetCell.timestamp_micros` values not divisible by `1_000` with `INVALID_ARGUMENT`), all row writes derive deterministic millisecond-aligned cell timestamps directly from the monotonic OCC version: +To eliminate torn rows while satisfying Cloud Bigtable's **`TimestampGranularity::MILLIS`** rule (which rejects explicit `SetCell.timestamp_micros` and `TimestampRange` bounds not divisible by `1_000` with `INVALID_ARGUMENT`), all row writes and range filters derive deterministic millisecond-aligned timestamps directly from the monotonic OCC version: -* **Hybrid Monotonic OCC Version (`item_ops::next_occ_version`):** +* **Hybrid Monotonic OCC Version (`item_ops::next_occ_version` & `next_millis_exclusive`):** * `now_ms = unix_timestamp_millis().max(1)` * `next_occ_version(None) = now_ms` * `next_occ_version(Some(prev)) = prev.max(now_ms) + 1` * `version_to_timestamp_micros(v) = (v * 1_000) as i64` -* **Uniform Row-Wide Stamping:** Every `SetCell` in a write—every attribute cell in `d:*`, the `m:v` version cell (preceded by bounded `DeleteFromColumn(m:v, [0, occ_ts))`), and every projected cell in GSI shadow tables—is stamped with the exact same `version_to_timestamp_micros(next_version)`. Bounding `DeleteFromColumn` to `[0, occ_ts)` clears historical versions without creating an unbounded tombstone that could mask future writes, and a higher OCC version strictly dominates all cells of every prior write across all column families even across dozens of sequential writes within the same wall-clock millisecond. -* **Monotonic Tombstone Versioning on Delete:** Deleting an existing row (`expected_version = Some(v)`) issues `DeleteFromFamily("d")`, bounded `DeleteFromColumn("m", "v", [0, occ_ts))`, and `SetCell("m", "v", next_version)` at `version_to_timestamp_micros(next_version)`. Retaining the monotonic `m:v` marker across deletes prevents ABA version reuse and timestamp regression on rapid `Put -> Delete -> Put` cycles, while `Query`, `Scan`, and `BatchGetItem` filter on `FamilyNameRegexFilter("^d$")` so version-only tombstones never appear as items or consume `rows_limit`. + * `next_millis_exclusive(ts_micros) = ((ts_micros / 1_000) + 1) * 1_000` +* **Uniform Row-Wide & Version-Guarded GSI Shadow Stamping:** Every `SetCell` in a write—every attribute cell in `d:*`, the `m:v` version cell (followed by bounded `DeleteFromColumn(m:v, [0, occ_ts))`), and every projected cell + `m:v` guard in GSI shadow tables—is stamped with `version_to_timestamp_micros(next_version)`. GSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, and `ItemOps::delete_shadow_orphan_if_unchanged`) never issue unbounded `DeleteFromFamily("d")` or `DeleteFromRow`: instead, they inspect `(existing_quals, max_d_ts, cur_ver)` and execute `CheckAndMutateRow` predicated on exact `m:v == cur_ver` (or missing `m:v`), placing `SetCell` before bounded per-qualifier `DeleteFromColumn` (`[0, occ_ts)` / `[0, next_millis_exclusive(occ_ts))`) and rejecting (`Ok(false)`) any delayed writer or reconciler (`new_version < cur_ver`) so stale mutations never overwrite or delete newer `v2` shadow state. +* **Monotonic Tombstone Versioning on Delete:** Deleting an existing base or GSI shadow row advances `SetCell("m", "v", next_version)` at `version_to_timestamp_micros(next_version)` (with bounded `DeleteFromColumn("m", "v", [0, occ_ts))`). Retaining the monotonic `m:v` marker across deletes prevents ABA version reuse and timestamp regression on rapid `Put -> Delete -> Put` cycles, while `Query`, `Scan`, and `BatchGetItem` filter on `FamilyNameRegexFilter("^d$")` so version-only tombstones never appear as items or consume `rows_limit`. * **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** Because Bigtable row filters have no boolean `NOT` operator, `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`: - * **Versioned Existing Row (`read_version = Some(v)`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v != v)`. - * **Unversioned Pre-Existing Row (`read_version = None, row_existed = true`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v exists)`, allowing any legacy/unversioned row to transition onto monotonic `m:v` versioning on its first write while still rejecting concurrent writers that stamped `m:v` first. - * **New Row (`read_version = None, row_existed = false`):** Predicate matches if `(unexpired m:intent:* exists) OR (m:v exists) OR (d:* exists)`. - * **Conflict Classification & Contention Retry:** When `predicate_matched == true`, `ItemOps` checks `has_active_intent(row_key)`. If an unexpired 2PC intent holds the row, it immediately returns `StorageError::TransactionConflict` (`TransactionConflictException`, [RFC-0003](0003-backend-acceptance-criteria.md) §4.3). Otherwise, it returns `CasOutcome::OccMismatch` and `BigtableEngine` retries up to `MAX_OCC_ATTEMPTS` (16) with jittered exponential backoff—re-reading the row, re-evaluating `ConditionExpression` (so concurrent conditional losers deterministically receive `ConditionFailed` per §4.2), and re-applying `UpdateAction`s (so concurrent `UpdateItem` increments serialize cumulatively with zero lost updates per §4.4). + * **Versioned Existing Row (`read_version = Some(v)`):** Predicate matches if `(any m:intent:* exists) OR (m:v != v)`. + * **Unversioned Pre-Existing Row (`read_version = None, row_existed = true`):** Predicate matches if `(any m:intent:* exists) OR (m:v exists) OR (d:* missing)`. + * **New Row (`read_version = None, row_existed = false`):** Predicate matches if `(any m:intent:* exists) OR (m:v exists) OR (d:* exists)`. + * **Conflict Classification & Contention Retry:** When `predicate_matched == true`, `BigtableEngine` classifies `CasOutcome::IntentPresent` vs. `CasOutcome::OccMismatch`, cooperatively resolves `COMMITTED` or expired `PENDING` intents via `resolve_blocking_intents` (waiting/retrying across transient `sgl-*` single-item fenced writes), returns `StorageError::TransactionConflict` if a live multi-item 2PC `txn-*` holds the row ([RFC-0003](0003-backend-acceptance-criteria.md) §4.3), or retries OCC mismatches with jittered backoff. #### E. Cloud Bigtable App Profile & Single-Cluster Routing Requirements Cloud Bigtable requires single-cluster routing (or multi-cluster routing with single-row transactions enabled) to execute `CheckAndMutateRow`. Multi-cluster profiles with eventual consistency reject `CheckAndMutateRow` with `FailedPrecondition`. `BigtableStorageConfig` exposes `app_profile_id` and forwards it on every `ReadRows`, `MutateRow`, `MutateRows`, and `CheckAndMutateRow` RPC so multi-cluster deployments can bind ExtendDB to a single-cluster profile. #### F. Garbage Collection (GC) Rules & Recovery Sweeper -* **Column Family GC:** `d` and `m` on data/GSI tables, `c` on `__extenddb_catalog__`, `t` on `__extenddb_txn_log__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. -* **2PC Recovery Sweeper (`sweeper.rs`):** Spawned via `BigtableRuntimeHooks::spawn_workers` under a distributed catalog lease (`lock:sweeper`) with graceful `CancellationToken` shutdown. Transactions in `__extenddb_txn_log__` older than `intent_timeout_secs` are rolled back if `PENDING`/`ABORTED` (clearing intents and deleting the coordinator row) or rolled forward idempotently if `COMMITTED` (re-running fenced base mutations, GSI shadow writes, and idempotent stream record writes before marking `CLEANED` and dropping the coordinator row). +* **Column Family GC:** `d` and `m` on data/GSI tables, `c` on `__extenddb_catalog__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. +* **2PC Recovery Sweeper (`sweeper.rs`):** Spawned via `BigtableRuntimeHooks::spawn_workers` under a distributed catalog lease (`lock:sweeper`) with graceful `CancellationToken` shutdown. Timed-out `PENDING` coordinators are first CAS-transitioned to `ABORTED` (`try_abort_pending`) before clearing intents and calling `drop_matching_start` (rolling forward if concurrently `COMMITTED`); `COMMITTED` coordinators are rolled forward idempotently (`roll_forward` applying base rows, versioned GSI shadows, `t:ttl_mutations`, contiguous deduplicated stream records, and `idem::` before marking `CLEANED` and dropping); and stranded `CLEANED` rows persist `idem:` if `t:token_meta` is present before dropping. ### 3. Unified Fenced DynamoDB Streams Architecture & Stream Lineage #### A. Write-Ahead Fenced Stream Emission & Labelled Shard Lineage (`stream_lineage`) To satisfy [RFC-0003](0003-backend-acceptance-criteria.md) §3.2 and §5.1 ("a crash between a committed data write and its stream record insert must not be possible"), stream emission is **never** performed as an unfenced trailing write. Whenever a caller supplies `stream: Some(&StreamCapture)` on a table whose `StreamSpecification.stream_enabled` is active (`active_stream_target_for_capture`), single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through `BigtableEngine::execute_fenced_single_item_write`, sharing the exact same `__extenddb_txn_log__` commit fence as `TransactWriteItems` (while `DataEngine` writes with `stream: None`—such as `ImportTable` bulk imports—preserve the upstream stream-suppression contract without emitting stream events): -1. **Labelled 4-Shard Stream Lineage (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and provisions `SHARDS_PER_STREAM` (`4`) open `ShardMeta` rows (`00..03`) in `__extenddb_catalog__` at `stream_shard:`, where `shard_id = shardId-{table_id}-{label_millis:013}{view_digit:1}{index:02}` (61 characters, within the 65-character AWS SDK `ShardId` limit). Writes and `StreamEngine::assign_shard` route partition keys deterministically across open shards via `crc32fast::hash(pk_text.as_bytes()) % open.len()`, preserving strict per-item causal ordering while matching `SqliteEngine`'s shard fan-out. Disabling a stream stamps `ending_sequence_number` on all open shards while retaining `LatestStreamArn`, `LatestStreamLabel`, and closed shard/record history so disabled streams remain describable, listed by `ListStreams`, and readable under their original ARN while rejecting cross-stream `(newer_arn, older_shard_id)` pairings (`SHARD_DOES_NOT_EXIST` / `STREAM_DOES_NOT_EXIST`). -2. **Lock & Read:** Open a coordinator row (`PENDING`) in `__extenddb_txn_log__`, place `m:intent:` on the target row (retrying transient single-row intent contention), read the locked pre-image and `m:v`, and evaluate `ConditionExpression` (plus `removes_only` no-op detection on missing items for `UpdateItem`). On failure or no-op, clear the intent and drop the coordinator row without writing data or stream records. -3. **Sequence Allocation & Record Construction (`streams.rs`):** Allocate a fixed-width **26-digit decimal sequence number** (`{epoch_ms:013}{counter:09}{node_suffix:04}`, `StreamEngine::sequence_number_width() == 26`) that is strictly monotonic, lexicographically ordered, and parseable as `u128` for `AT_SEQUENCE_NUMBER` shard-iterator arithmetic in `extenddb-engine`. Build the `StreamRecord` (`INSERT`, `MODIFY`, or `REMOVE`) honoring `StreamCapture` (`view_type`, `region`, and optional TTL `user_identity`), suppressing no-op `MODIFY` events when `old_image == new_image`. -4. **Atomic Commit Point:** Write `COMMITTED` to `__extenddb_txn_log__` together with `t:mutations` and `t:stream_records` (carrying `(stream_arn, shard_id, record)`) *before* mutating column family `d`. -5. **Fenced Apply & Idempotent Ledger Write:** Apply the fenced `CheckAndMutateRow` mutation to the base table, update GSI shadow tables and TTL index entries, and persist each stream record to `__extenddb_catalog__` at deterministic row key `stream_record::`. Mark `CLEANED` and drop the coordinator row only after `streams::write_record` succeeds. -6. **Crash Recovery Idempotency:** If ExtendDB crashes after `COMMITTED` (before base-row apply or before `streams::write_record`), `TransactGetItems` immediately serves the committed post-image via the read-through-log rule, and `sweeper::sweep_once` rolls forward both the fenced data write and `streams::write_record`. Because the stream ledger row key is deterministic on `(shard_id, sequence_number)`, re-running `roll_forward` overwrites the identical JSON payload with zero duplicate stream records. +1. **Labelled 4-Shard Stream Lineage (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and provisions `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) in `__extenddb_catalog__` at `stream_shard:`, where `shard_id = shardId-{table_id}-{label_millis:013}{view_digit:1}{index:02}` (61 characters, within the 65-character AWS SDK `ShardId` limit). `UpdateTable` commits `table_meta` via `Catalog::mutate_json_cas` **before** closing disabled shards (`close_shards_by_id` via CAS) or provisioning newly enabled shards (`put_shard_if_absent` followed by `stream_lineage::enable_still_current` re-verification so concurrent disable calls immediately close superseded shards). Writes and `StreamEngine::assign_shard` route partition keys deterministically across the 4 shards via `crc32fast::hash(pk_text.as_bytes()) % SHARDS_PER_STREAM`. +2. **Contention-Resilient Single-Item Serialization (`sgl-` Prefix):** Single-item fenced writes serialize same-process contention per `(data_table, row_key)` via an async mutex (`acquire_single_write_lock`) and tag their coordinator IDs with `sgl-` (`TxnCoordinator::new_single_txn_id`) so cross-process single-item contenders wait and retry cooperatively rather than aborting unconditional `PutItem`/`UpdateItem` calls with spurious `TransactionConflictException`. +3. **Wait-Free Contiguous Per-Shard Sequence Slot Append (`streams.rs`, `RFC-0003` §5.2):** Phase 1 constructs each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER` (`"00000000000000000000000000"`), its associated `ParticipantRow`, and `:` `dedup_key`. During Phase 2 (`streams::write_record_ordered`), under an in-process per-shard mutex (`shard_local_mutex`), the writer reads `ShardMeta.next_seq_num` (`>= 1`) **first**, checks `stream_dedup::` **second**, formats `slot_seq = slot_sequence_number(shard_id, slot)` (`{label_ms:013}{slot:011}{shard_idx:02}`), atomically claims `stream_record::` via `Catalog::put_if_absent` (on slot collision, persisting the slot winner's `stream_dedup` marker **before** advancing `ShardMeta.next_seq_num`), persists its own `stream_dedup` markers, and monotonically advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS (`advance_shard_cursor_at_least`, plus `ensure_shard_past_record` before 24h retention pruning). Because slots `1, 2, 3, ...` are filled strictly in publication order without gaps or duplicates, `get_stream_records` (`after_sequence`) never skips a delayed writer on the same shard. +4. **Atomic Commit Point & Phantom-Free Crash Recovery (`RFC-0003` §5.1, §5.4):** `try_commit_full` writes `COMMITTED` to `__extenddb_txn_log__` together with `t:mutations`, `t:stream_records`, and `t:ttl_mutations` *before* mutating column family `d`. During `roll_forward`, stream records are emitted **only** for `materialized_participants` whose base-row mutation actually materialized, and `stream_dedup` guarantees exact-once emission across arbitrary crash/recovery replays. #### B. Why the `__extenddb_catalog__` Table Ledger Beats Cloud Bigtable Native Change Streams Cloud Bigtable offers a native Change Streams CDC feature (`ReadChangeStream`), which we evaluated and deliberately rejected in favor of the coordinator-fenced `__extenddb_catalog__` stream ledger for five architectural reasons: @@ -162,19 +170,22 @@ Cloud Bigtable offers a native Change Streams CDC feature (`ReadChangeStream`), * **Row Key Binary Layout:** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` * `shard_id = fnv1a(base_row_key) % 16` distributes writes and sweeps evenly across 16 prefixes instead of creating a monotonic timestamp hotspot. * `expiry_epoch_secs_be` orders entries chronologically within each shard so each sweep reads only `[shard_id || 0, shard_id || (now + 1))`. -* **Write Maintenance:** `PutItem`, `UpdateItem`, `DeleteItem`, and `TransactWriteItems` parse TTL attributes via `parse_ttl_epoch_secs` (supporting integer, fractional, and scientific `AttributeValue::N` strings via `bigdecimal` while treating `<= 0` as non-expiring per DynamoDB semantics), removing stale TTL index keys when a prior item's TTL attribute changes or is deleted and inserting a new TTL index row when the post-image carries a positive numeric TTL epoch. +* **OCC-Ordered Write & Recovery Maintenance (`apply_ttl_mutation_versioned`):** `PutItem`, `UpdateItem`, `DeleteItem`, `TransactWriteItems`, and `roll_forward` (via `t:ttl_mutations`) parse TTL attributes via `parse_ttl_epoch_secs` (supporting integer, fractional, and scientific `AttributeValue::N` strings via `bigdecimal` while treating `<= 0` as non-expiring per DynamoDB semantics). Whenever `old_expiry != new_expiry`, old TTL index cells are cleared via bounded `DeleteFromColumn("d", b"", [0, occ_ts))`; whenever `new_expiry` is positive, `insert_ttl_index_entry_at` stamps `SetCell("d", b"", occ_ts)` first followed by bounded `DeleteFromColumn("d", b"", [0, occ_ts))` at `version_to_timestamp_micros(new_version)` (even when `old_expiry == new_expiry`, e.g., `"1000" -> "1000.5"`), making out-of-order `1000 -> 2000 -> 1000` ABA updates commute deterministically with millisecond-aligned timestamps. #### B. Live Verification, Metrics & Fenced TTL Stream Emission (`ttl_worker.rs`) -1. Under the distributed `lock:ttl_worker` catalog lease, scan `[shard || 0, shard || (now + 1))` across all 16 shards. -2. Confirm the table still exists and has `TimeToLiveStatus::Enabled`. If the table was dropped or TTL was disabled, delete the stale index row without touching base data. -3. Read the live base item (`DataEngine::get_item`) and verify its current TTL attribute (`parse_ttl_epoch_secs`) still equals the index row's `expiry` (`> 0` and `<= now`). If the item was already deleted or updated to a later or non-positive expiration timestamp, delete **only** the stale TTL index entry. -4. Issue `DataEngine::delete_item` with a `#ttl = :ttl_exp` `ConditionExpression` guard (preventing a race if a client extends TTL between step 3 and step 4) and, when streams are enabled on the table, a `StreamCapture` carrying `UserIdentity { principal_id: "dynamodb.amazonaws.com", identity_type: "Service" }`, recording `TimeToLiveDeletedItemCount` and `TtlStalenessSeconds` in `MetricsCollector`. Because stream-enabled `delete_item` executes through `execute_fenced_single_item_write`, the base-row deletion and TTL `REMOVE` stream record are atomically fenced in `__extenddb_txn_log__`. +1. Under the distributed `lock:ttl_worker` catalog lease, scan `[shard || 0, shard || (now + 1))` across all 16 shards, capturing each scanned index cell's `idx_ts_micros`. +2. Confirm the table still exists and has `TimeToLiveStatus::Enabled`. If the table was dropped or TTL was disabled, retire the stale index cell via bounded `DeleteFromColumn("d", b"", [0, next_millis_exclusive(idx_ts_micros)))` without touching base data. +3. Read the live base item + OCC version (`get_item_with_version`, cooperatively resolving any `COMMITTED` intent) and inspect its current TTL attribute (`parse_ttl_epoch_secs`): + * If the item was already deleted or updated to a non-positive value, retire only the scanned index cell up to `next_millis_exclusive(bound_ts)` so concurrent same-second TTL inserts at higher OCC timestamps are never wiped. + * If `live_secs > now` (extended into the future), re-assert `(live_secs, live_ver)` via `ensure_ttl_index_entry` before retiring the stale expired entry. + * Whenever `0 < live_secs <= now` (even if `live_secs != scanned_expiry` due to ABA index skew), proceed to eviction. +4. Issue `DataEngine::delete_item` with `#ttl = :live_exp_str` `ConditionExpression` and, when streams are enabled on the table, a `StreamCapture` carrying `UserIdentity { principal_id: "dynamodb.amazonaws.com", identity_type: "Service" }`, recording `TimeToLiveDeletedItemCount` and `TtlStalenessSeconds` in `MetricsCollector`, then retire the scanned TTL index cell via bounded `DeleteFromColumn("d", b"", [0, next_millis_exclusive(bound_ts)))`. -### 5. Query, Scan & GSI Consistency +### 5. Query, Scan, LSI Ordering & Online GSI Lifecycle * **Query Direction & `cbtemulator` Compatibility (`query_scan.rs`):** Forward and reverse `Query` calls (`ScanIndexForward`) construct tight byte-range bounds over `[pk_prefix, pk_upper]` (merging `ExclusiveStartKey` into the active sort-key range bound so `BETWEEN` and `begins_with` never lose their upper/lower bounds across pages, [RFC-0003](0003-backend-acceptance-criteria.md) §2.6, and short-circuiting inverted/empty bounds such as `BETWEEN :hi AND :lo` where `:hi > :lo` before issuing an RPC). Production Cloud Bigtable executes descending queries server-side via `ReadRowsRequest { reversed: true }`; when running against `cbtemulator` (which returns `UNIMPLEMENTED` or `FAILED_PRECONDITION` for `reversed: true`), `QueryScan::query` automatically falls back to a bounded partition scan plus in-memory reversal with identical `LastEvaluatedKey` semantics. -* **Exact `LastEvaluatedKey` & Parallel Scan Completeness:** Both `Query` and `Scan` fetch `limit + 1` storage rows so `LastEvaluatedKey` is emitted if and only if unread items remain in the range ([RFC-0003](0003-backend-acceptance-criteria.md) §7.2). Parallel scans (`total_segments > 1`) page through storage in chunks until `limit + 1` in-segment items (`crc32(pk_prefix) % total_segments == segment`) are collected or the table exhausts, avoiding premature segment termination under key skew (§7.3). -* **GSI Projections, Key Validation & TOCTOU-Safe Background Reconciler (`gsi.rs`, `gsi_worker.rs`):** `PutItem`, `UpdateItem`, and `TransactWriteItems` validate GSI/LSI key scalar types and non-emptiness upfront (`validate_index_keys`, `validate_index_key_literal_operands`, `validate_index_key_types_after_update`) and validate `UpdateAction` operands prior to `removes_only` missing-item short-circuits (`#478`). Shadow writes synchronously project `ALL`, `KEYS_ONLY`, or `INCLUDE` attributes at the base write's deterministic OCC timestamp. `gsi_worker::run` periodically scans shadow-to-base and base-to-shadow (using pre-encoded composite shadow keys via `ItemOps::batch_get_by_raw_keys`) under `lock:gsi_reconciler`; whenever divergence is detected, it atomically re-reads `(fresh_base_row, fresh_ver)` via `ItemOps::get_with_version` and stamps repaired GSI shadow cells at `version_to_timestamp_micros(fresh_ver)` so concurrent base updates are never masked by wall-clock timestamps. +* **Exact `LastEvaluatedKey`, LSI `Scan` & Parallel Scan Completeness:** Base and GSI `Query`/`Scan` always resolve `base_key_schema` from catalog `TableDescription` (even when `extenddb-engine` rewrites `TableKeyInfo.key_schema` to the target index schema) and fetch `limit + 1` storage rows so `LastEvaluatedKey` is emitted if and only if unread items remain ([RFC-0003](0003-backend-acceptance-criteria.md) §7.2). `QueryScan::scan_lsi` streams base rows partition-by-partition, filters sparse items lacking `lsi_sk_name` **before** applying `limit`, sorts each partition by `(enc_lsi_sk, enc_base_sk)`, and emits/resumes `LastEvaluatedKey` tuples carrying `(pk, base_sk, lsi_sk)` (§7.1, §7.4). Parallel scans (`total_segments > 1`) page through storage in chunks until `limit + 1` in-segment items (`crc32(pk_prefix) % total_segments == segment`) are collected or the table exhausts (§7.3). +* **Online `UpdateTable` GSI Lifecycle, Version-Guarded Shadows & Background Reconciler (`engine.rs`, `gsi.rs`, `gsi_worker.rs`):** `UpdateTable` executes via `Catalog::mutate_json_cas` (`CatalogJsonAction`) on `table_meta` (matching `update_ttl`, `tag_resource`, `untag_resource`, IAM/policy/secret mutations, and `MetricsStore::insert_metrics`), supporting `GlobalSecondaryIndexUpdates` (`Create` with `CREATING -> backfill -> ACTIVE` transition under `BuildingGsiGuard` and `IndexNotFound` read refusal on `index_info`/`query`/`scan` while `index_status != "ACTIVE"`, `Update` of `WarmThroughput`, and `Delete` with shadow table teardown and orphaned `AttributeDefinitions` pruning), `TableClass`, `WarmThroughput`, and `NoOpUpdate` checks. Both live writes and `gsi_worker` repairs mutate GSI shadow rows exclusively through version-guarded `put_shadow_versioned` / `delete_shadow_versioned` / `delete_shadow_orphan_if_unchanged` (rolling forward committed transactions for the table prior to backfill/reconciliation), and `gsi_worker` promotes interrupted `CREATING` GSIs to `ACTIVE` via CAS only after reconciliation succeeds cleanly. ### 6. GCP Connectivity, Secret Key Ring, Catalog Stores & Error Classification @@ -196,8 +207,8 @@ gsi_reconcile_cadence_secs = 300 * **Safe Client Construction & Split-Instance Isolation (`data/client.rs`):** `BigtableClient::connect` builds emulator connections via `BigTableConnection::new_with_emulator` and explicit service-account connections via `gcp_auth::CustomServiceAccount::from_file` + `BigTableConnection::new_with_token_provider` without any `unsafe` process-environment mutation (`std::env::set_var`) or `Box::leak` allocations. When `data_instance_id` differs from `instance_id`, catalog tables, distributed worker leases (`lock:*`), and stream ledger records stay strictly on `instance_id` (`catalog_client` sized by `catalog_pool_size`) while user data tables, GSI shadow tables, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` live strictly on `data_instance_id` (`data_client` sized by `pool_size`). * **Thin-Binary Compile-Time Registration (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` so standard `cargo build` / `cargo check` invocations work unchanged, while exposing a mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`) that installs `extenddb_storage_bigtable::backend()` via `extenddb_storage::set_backend` with zero edits to `crates/core`, `crates/engine`, `crates/auth`, or `crates/server`. -* **At-Rest Secret Encryption & KEK/DEK Key Ring (`extenddb_storage::secret_keys`):** `m0001_baseline` seeds a unique `setting:catalog_id` UUID, and `BigtableCatalogStore` / `BigtableCredentialStore` encrypt and decrypt `AKIA*` access-key secrets and `ASIA*` STS session secrets via `SecretKeys` (`SecretRow::access_key` and `SecretRow::session` AAD binding `(table, access_key_id, account_id, principal, session_name, expires_at)`). `SettingsStore::replace_setting` uses single-row `CheckAndMutateRow` compare-and-swap (`Catalog::compare_and_swap_raw` / `put_if_absent`), and `ManagementStore` implements cursor-paged `read_secret_page`, `write_secrets`, `delete_secrets`, and `delete_setting` to support `extenddb encryption-key switch`, `rotate`, `rewrap`, and `reset`. -* **IAM Leftover Hygiene, Operational Metrics & Login Rate Limiting (`catalog_store.rs`):** Deleting or creating a user, group, role, or account atomically purges associated policies, permission boundaries, tags, memberships, access keys, and `failed_login:/` rate-limit entries (`iam_leftovers_conformance`). `MetricsStore` accumulates minute-bucketed metrics keyed by `metric::` via CAS retry and supports retention pruning (`metrics_conformance`). +* **At-Rest Secret Encryption & KEK/DEK Key Ring (`extenddb_storage::secret_keys`):** `m0001_baseline` seeds a unique `setting:catalog_id` UUID, and `BigtableCatalogStore` / `BigtableCredentialStore` encrypt and decrypt `AKIA*` access-key secrets and `ASIA*` STS session secrets via `SecretKeys` (`SecretRow::access_key` and `SecretRow::session` AAD binding `(table, access_key_id, account_id, principal, session_name, expires_at)`). `SettingsStore::replace_setting` uses single-row `CheckAndMutateRow` compare-and-swap (`Catalog::mutate_json_cas` / `put_if_absent`), and `ManagementStore` implements cursor-paged `read_secret_page`, CAS `write_secrets`, `delete_secrets`, and `delete_setting` to support `extenddb encryption-key switch`, `rotate`, `rewrap`, and `reset`. +* **IAM Leftover Hygiene, Operational Metrics & Login Rate Limiting (`catalog_store.rs`):** Deleting or creating a user, group, role, or account atomically purges associated policies, permission boundaries, tags, memberships, access keys, and `failed_login:/` rate-limit entries (`iam_leftovers_conformance`). `MetricsStore::insert_metrics` accumulates minute-bucketed metrics keyed by `metric::` via `Catalog::mutate_json_cas` and supports retention pruning (`metrics_conformance`). * **Frozen Baseline & Additive Migration Ledger (`m0001_baseline.rs`, `migrations.rs`):** `m0001_baseline.rs` (`#[rustfmt::skip]`) provisions `__extenddb_catalog__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` plus `setting:catalog_id`; `MigrationId`s `2..=12` record cleanly as schema-less no-ops in `migration_ledger:catalog:` under `lock:catalog_migrations`. * **gRPC Transient Error Classification (`data/client.rs`):** Data-plane and catalog errors are classified via `map_bigtable_err`, `map_catalog_err`, and `classify_grpc_status`: * `Unavailable`, `DeadlineExceeded`, `Aborted`, `ResourceExhausted`, RPC timeouts, and transient I/O errors map to `StorageError::Transient` (surfaced by the server as retryable HTTP 503 `ServiceUnavailable` rather than opaque HTTP 500s). @@ -216,16 +227,16 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept | Trait / Subsystem | Classification | Status | Implementation Module | Notes | |---|---|---|---|---| -| `TableEngine` | Mandatory (Data/Control) | Implemented | `src/engine.rs` | `CreateTable`, `DeleteTable`, `DescribeTable`, `ListTables`, `UpdateTable` (with 4-shard `stream_lineage` transitions), `table_key_info`, `index_info`, `index_info_by_table_id` | -| `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with deterministic `occ_version * 1000` timestamps, `GetItem`, `Query`, `Scan`, `scan_key_in_segment`, ABA-fenced 2PC `TransactWriteItems`, read-through-log `TransactGetItems` | +| `TableEngine` | Mandatory (Data/Control) | Implemented | `src/engine.rs` | CAS `CreateTable`/`UpdateTable` (online GSI `Create`/`Update`/`Delete` + backfill, `TableClass`, `WarmThroughput`, post-CAS `stream_lineage` transitions), `DeleteTable`, `DescribeTable`, `ListTables`, `table_key_info`, `index_info` | +| `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with cooperative intent resolution & versioned GSI shadows, `GetItem`, `Query`, `Scan` (including sparse sorted `scan_lsi`), `scan_key_in_segment`, incarnation-fenced CAS 2PC `TransactWriteItems`, double-read snapshot `TransactGetItems` | | `VectorSearchEngine` | Optional (`as_vector_search`) | Opted out (`None`) | `src/engine.rs` | Engine rejects vector index DDL and `SearchVectors` upfront | -| `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | Resource tagging (`TagResource`/`UntagResource`/`ListTagsOfResource`) + 16-shard `__extenddb_ttl_index__` with `parse_ttl_epoch_secs` | -| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item, TTL, and 2PC streams; 4-shard CRC32 partition-key routing + `stream_lineage` disable/re-enable history; 26-digit `u128` decimal sequence numbers | +| `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | CAS resource tagging (`TagResource`/`UntagResource`/`ListTagsOfResource`) + 16-shard `__extenddb_ttl_index__` with `parse_ttl_epoch_secs` & millisecond-aligned bounds | +| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item (`sgl-*`), TTL, and 2PC streams; 4-shard CRC32 partition-key routing + contiguous `put_if_absent` sequence slots (`write_record_ordered`) + `stream_dedup` + `stream_lineage` disable/re-enable history | | `WorkerStore` | Optional (Lifecycle) | Implemented | `src/engine.rs` | Inline `ACTIVE` table creation (`process_control_plane_transitions` no-op) | | `SnapshotEngine`, `BackupCatalog`, `LegacyBackupReader`, `RestoreEngine` | Optional (Backup/Restore) | Explicit Refusal | `src/backup_stubs.rs` | User operations return `StorageError::Unsupported` (`ValidationException` HTTP 400); passive reconciler probes return empty `Ok` | -| `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM users/groups/roles/policies/boundaries/tags, STS sessions, password-hash persistence, `SecretKeys` KEK/DEK paging & rotation | +| `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM users/groups/roles/policies/boundaries/tags, STS sessions, CAS password-hash persistence, `SecretKeys` KEK/DEK paging & rotation | | `AuthorizationStore` | Mandatory (Authz) | Implemented | `src/catalog_store.rs` | User/group/role policies, permission boundaries, resource/principal tags, RFC 3339 `created_at` | -| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, table/index diagnostics | +| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, CAS SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, table/index diagnostics | | `CredentialStore` | Mandatory (`SigV4` Auth) | Implemented | `src/catalog_store.rs` | `AKIA*` + `ASIA*` `SecretKeys` decryption with `SecretRow` AAD, `ExpiredTokenException`, and inactive-key S-5 propagation | | `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | Idempotent catalog/key/account/admin bootstrap (`catalog_key_present`, `data_connection_present`) and `destroy` cleanup | | `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | Exhaustive `MigrationId` 1..=12 coverage, frozen `m0001_baseline.rs` checksum, `lock:catalog_migrations` lease | @@ -236,18 +247,19 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept 1. **Pure Unit Tests (`cargo test -p extenddb-storage-bigtable --lib`):** * Exact 38-digit decimal `N` encoding/decoding, zero normalization, and full-spectrum lexicographic order (`number.rs`). - * Row-key 4 KiB limit enforcement, partition length prefixing, raw terminal sort-key ordering, and FDB escape-encoded GSI sort-key roundtrips (`row_key.rs`, `gsi.rs`, `ttl_key.rs`). - * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`), `parse_ttl_epoch_secs` decimal/zero/negative parsing, 3-case De Morgan `select_occ_predicate` and ABA-safe `build_fenced_apply_predicate` `RowFilter` construction (`item_ops.rs`, `transact.rs`), RE2 metacharacter escaping and `monotonic_timestamp_after_micros` (`client.rs`), URL-encoded query parameter / TOML / `string_coerce` env-var config roundtripping (`config.rs`, `bootstrapper.rs`), 26-digit `u128` stream sequence numbers and TTL `UserIdentity` propagation (`streams.rs`), gRPC transient error mapping (`client.rs`), `check_released` migration checksum invariants (`migrations.rs`), and `StorageError::Unsupported` backup/snapshot/restore stubs (`backup_stubs.rs`). + * Row-key 4 KiB limit enforcement, partition length prefixing, raw terminal sort-key ordering, FDB escape-encoded GSI sort-key roundtrips, and LSI `LastEvaluatedKey` / `ExclusiveStartKey` validation (`row_key.rs`, `gsi.rs`, `ttl_key.rs`, `query_scan.rs`). + * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`, `next_millis_exclusive`), `parse_ttl_epoch_secs` decimal/zero/negative parsing, wall-clock-free intent filters, 3-case De Morgan `select_occ_predicate`, and incarnation-fenced `build_pending_incarnation_predicate` / ABA-safe `build_fenced_apply_predicate` `RowFilter` construction (`item_ops.rs`, `transact.rs`), RE2 metacharacter escaping and `monotonic_timestamp_after_micros` (`client.rs`), URL-encoded query parameter / TOML / `string_coerce` env-var config roundtripping (`config.rs`, `bootstrapper.rs`), 26-digit `u128` stream sequence numbers (`slot_sequence_number`) and TTL `UserIdentity` propagation (`streams.rs`), gRPC transient error mapping (`client.rs`), `check_released` migration checksum invariants (`migrations.rs`), and `StorageError::Unsupported` backup/snapshot/restore stubs (`backup_stubs.rs`). 2. **Live Bigtable Emulator Integration & Conformance Suite (`tests/emulator_integration.rs` against `cbtemulator`):** * Catalog bootstrap, `BigtableCatalogMigrations` baseline run, table DDL lifecycle, and split catalog-vs-data instance (`data_instance_id != instance_id`) isolation across `BigtableBootstrapper` and background workers (`sweeper`, `ttl_worker`, `gsi_worker`). * Guarded single-row CRUD, `ConditionExpression` evaluation, arithmetic `UpdateItem`, `removes_only` missing-item no-ops, and `#478` invalid-operand rejection on missing items. * Deterministic OCC cell timestamps (`m:v * 1000` shared across all cells), post-`DeleteItem` `m:v` tombstone retention and rapid re-insert monotonicity, concurrent 10-way `UpdateItem` counter increments (zero lost updates), and 8-way conditional `PutItem` races (1 winner, 7 `ConditionFailed`). - * Multi-table 2PC `TransactWriteItems`, atomic condition-failure rollback, reused `ClientRequestToken` tombstone safety after Phase 1 abort, post-lease-expiry ABA fencing across base and GSI shadow rows, idempotency replay/mismatch, and concurrent `TransactGetItems` read-through-log verification (`COMMITTED` vs. `PENDING`). - * Fenced single-item stream emission (`INSERT`/`MODIFY`/`REMOVE`) across `SHARDS_PER_STREAM` (`4`) CRC32-routed shards, `ImportTable` `stream: None` bulk-import suppression, post-`COMMITTED` crash recovery and pre-`COMMITTED` crash rollback via `sweeper::sweep_with_cutoff_override` without duplicates or phantom records, and full stream disable/re-enable lineage (`stream_lineage`) + cross-stream shard isolation. - * Exact decimal range queries, inverted `BETWEEN` range guards, reverse `Query` (`ScanIndexForward = false`) pagination, GSI escape-encoded `begins_with` queries, upfront secondary-index key validation, TOCTOU-safe GSI reconciler OCC-timestamp repair, runtime GC helpers (`cleanup_expired_idempotency_tokens`, `cleanup_expired_stream_records`), and TTL sweeper fractional/scientific/zero/negative re-verification + `MetricsCollector` recording + fenced `dynamodb.amazonaws.com` `REMOVE` stream emission. + * Multi-table 2PC `TransactWriteItems`, incarnation-fenced `try_commit_full` vs. `sweeper` race (`AllOrNothing2PCAtomicity`), post-`COMMITTED` expired intent protection (`BUG-03`), canonical sorted `[k1, k2]` vs. `[k2, k1]` locking, `ReturnValuesOnConditionCheckFailure::None` vs. `AllOld` fidelity, 4-vector `ClientRequestToken` idempotency (`IdempotencyAtMostOnce`), and concurrent `TransactGetItems` linearizable snapshot verification (`NoTornTransactGetSnapshot`). + * Fenced single-item stream emission (`INSERT`/`MODIFY`/`REMOVE`) across `SHARDS_PER_STREAM` (`4`) CRC32-routed shards, out-of-order Phase 2 contiguous slot ordering (`NoSkippedStreamSequenceOnShard`), 12-way concurrent identical-`event_id` deduplication (`write_record_ordered`), superseded `roll_forward` phantom suppression (`NoPhantomStreamRecord`), 36-way single-item stream contention with live tailing consumer, `ImportTable` `stream: None` bulk-import suppression, and full stream disable/re-enable lineage (`stream_lineage`). + * Exact decimal range queries, inverted `BETWEEN` range guards, reverse `Query` (`ScanIndexForward = false`) pagination, sparse sorted LSI `Scan` (`scan_lsi`) with deleted-`ExclusiveStartKey` resumption, online `UpdateTable` GSI `Create`/`Update`/`Delete` + `CREATING` read refusal + version-guarded GSI shadow mutations (`QuiescentGsiShadowConsistency`), `roll_forward` TTL indexing + `1000 -> future -> 1000 -> 1000.5` ABA / millisecond-aligned TTL bounds (`QuiescentTtlIndexCompleteness`), runtime GC helpers (`cleanup_expired_idempotency_tokens`, `cleanup_expired_stream_records`), and concurrent CAS `MetricsStore::insert_metrics` / `tag_resource`. * Upstream shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, `key_conformance::run` (`switch`/`rotate`/`rewrap`/`reset`), and `BigtableCredentialStore` `AKIA*` + `ASIA*` (`ExpiredTokenException`) verification. -3. **End-to-End Conformance (`devtools/run-tests`):** +3. **End-to-End Conformance (`devtools/run-tests`) & TLA+ Formal Verification (`tlc2.TLC`):** * Wire-level Rust and pytest conformance suites against an `extenddb` binary built with `--no-default-features --features bigtable`. + * Exhaustive breadth-first `tlc2.TLC` model checking across 2PC CAS commit/rollback atomicity (`AllOrNothing2PCAtomicity`), double-read `TransactGetItems` linearizability (`NoTornTransactGetSnapshot`), post-commit lease expiry protection (`NoActiveIntentBypassAfterCommit`), multi-RPC per-shard stream sequence visibility & deduplication (`NoSkippedStreamSequenceOnShard`), superseded roll-forward stream gating (`NoPhantomStreamRecord`), TTL index completeness (`QuiescentTtlIndexCompleteness`), 4-vector `ClientRequestToken` idempotency (`IdempotencyAtMostOnce`), and versioned GSI shadow consistency (`QuiescentGsiShadowConsistency`). ## Alternatives Considered From 07300361dc6d0c2fe4bf5f29877278ab89f54672 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Fri, 20 Nov 2026 15:25:19 +0000 Subject: [PATCH 08/11] docs(rfc): address maintainer review on Experimental tier, live trait parity, and backend protocols - State backend tier as Experimental and remove unshipped verification claims and dev_mode references. - Align Bootstrapper, CatalogMigrations (MigrationId::Baseline catalog + data_instance_id split, renewed lock:catalog_migrations), and ServerRuntimeHooks (ServingRegistrar, ServingRegistration, startup status & single-cluster GetAppProfile check, 5 leased workers) with live crate symbols. - Document multi-attribute digest-bounded GSI/LSI shadow keys, durable post-* shadow/TTL recovery, pre-CAS stream_lineage shard creation, leased online GSI visibility fence, TTL ENABLING backfill, live-scan ExportTableToPointInTime, and zero ItemCount/TableSizeBytes. --- docs/rfcs/0000-bigtable-backend.md | 265 ++++++++++++++--------------- 1 file changed, 124 insertions(+), 141 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index 74a964ce7..b0d0a4013 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -7,76 +7,78 @@ ## Summary -This RFC defines the design and implementation of a production-grade Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0`. It addresses transaction isolation and serializable read-through-log snapshots, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection and Cloud Bigtable's millisecond granularity, incarnation-fenced two-phase commit (2PC) apply, unified write-ahead fenced DynamoDB Streams emission with contiguous per-shard sequence slots and disable/re-enable shard lineage (`stream_lineage`), FoundationDB tuple escape-encoded Global Secondary Index (GSI) keys and version-guarded shadow projections, sharded Time-to-Live (TTL) indexing, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, CAS-guarded IAM/metrics/DDL catalog conformance, gRPC transient-error classification, application-profile single-cluster routing, and Google Cloud Platform (GCP) authentication. +This RFC defines the design and implementation of an **Experimental** Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0` (evaluation tier per `README.md`, not for production use). It addresses single-row concurrency control and cooperative read-through / optimistic double-read snapshot validation for `GetItem` and `TransactGetItems`, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection and Cloud Bigtable's millisecond granularity, incarnation-fenced two-phase commit (2PC) apply and deleted-table recovery, write-ahead fenced DynamoDB Streams emission with pre-created shard metadata (`stream_lineage`) and contiguous per-shard sequence slots, SHA-256 partition-digest and FoundationDB tuple escape-encoded Global Secondary Index (GSI) and Local Secondary Index (LSI) shadow tables bounded within Bigtable's 4 KiB row-key limit, sharded Time-to-Live (TTL) indexing with `ENABLING` base-table backfill and version-only tombstone reclamation, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, `ADR-0023` renewed migration leases and `ServingRegistrar` fencing, `ADR-0029` catalog + data-instance baseline migrations, gRPC HTTP/2 pool resilience and internal-fault error classification, startup single-cluster transactional app-profile verification, and Google Cloud Platform (GCP) authentication. ## Motivation -Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-atomic data model introduces several distributed-systems challenges that a production backend must resolve: +Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-atomic data model introduces several distributed-systems challenges that the backend must resolve: -1. **Transaction Isolation & TOCTOU Races:** Naive read-modify-write conditional operations evaluate `ConditionExpression`s without atomic concurrency control, allowing concurrent writers to overwrite uncommitted state or bypass 2PC locks. +1. **Transaction Isolation & TOCTOU Races:** Naive read-modify-write conditional operations evaluate `ConditionExpression`s without atomic concurrency control, allowing concurrent writers to overwrite uncommitted state, bypass 2PC locks, or expose stale values when a committed 2PC write has not yet applied to column family `d`. 2. **Cell Timestamps vs. `MaxNumVersions(1)` Compaction:** Relying on server-assigned cell timestamps (`SetCell.timestamp_micros = -1`) allows tablet-server wall-clock differences or narrow concurrency windows to interleave cells from distinct writes across qualifiers (`d:*` vs. `m:v`), producing torn rows once `MaxNumVersions(1)` compaction runs. 3. **2PC Race Conditions (Read-then-Lock, Unfenced Commit/Abort & Unfenced Apply):** Reading participant rows before placing intent locks exposes `TransactWriteItems` to TOCTOU races; unconditional coordinator `COMMITTED` writes or unfenced sweeper rollbacks allow partial 2PC commits; and applying Phase 2 mutations unconditionally allows stalled coordinators whose intents were swept to overwrite newer committed data. -4. **Unfenced Stream Emission & Out-of-Order Shard Visibility:** Emitting DynamoDB Stream records as an unfenced trailing write loses stream records if the server crashes in the gap ([RFC-0003](0003-backend-acceptance-criteria.md) §3.2, §5.1), while pre-allocating global sequence numbers in Phase 1 allows a later sequence number (`seq_2 > seq_1`) to persist before `seq_1` on the same shard and cause `AFTER_SEQUENCE_NUMBER` consumers to permanently skip `seq_1` (§5.2). -5. **Inefficient & ABA-Prone TTL Eviction:** Full-table scans degrade read throughput at scale, while unlocked trailing TTL index maintenance or unbounded index row deletes suffer `1000 -> 2000 -> 1000` ABA races and risk wiping concurrent same-second TTL inserts. -6. **GSI Sort-Order, Online Lifecycle & Shadow Consistency:** Non-terminal sort keys in composite GSI row keys suffer sort inversion unless escape-terminated, online `UpdateTable` GSI builds must backfill existing rows before serving queries, and delayed writers or reconcilers (`v1 < v2`) must never clobber newer `v2` shadow state via unbounded `DeleteFromFamily` or `DeleteFromRow`. -7. **Multi-Cluster Routing & Auth Constraints:** Cloud Bigtable rejects `CheckAndMutateRow` under multi-cluster routing with eventual consistency unless routed via a single-cluster application profile, and enterprise deployments require explicit service-account credential configuration. +4. **Unfenced Stream Emission, Missing-Shard Races & Closed-Shard Leaks:** Emitting DynamoDB Stream records as an unfenced trailing write loses stream records if the server crashes in the gap ([RFC-0003](0003-backend-acceptance-criteria.md) §3.2, §5.1). Publishing `table_meta` before creating `ShardMeta` rows or falling back to wall-clock sequence numbers causes readers using `AFTER_SEQUENCE_NUMBER` to permanently skip later slot records (§5.2), and disabling a stream without draining committed writes or rejecting post-close appends leaks records past `EndingSequenceNumber`. +5. **TTL Pre-Enable Gaps, Disabled-State Retention & Tombstone Accumulation:** Full-table scans degrade read throughput at scale, enabling TTL on a populated table misses pre-existing expired items unless a backfill scan runs before reporting `ENABLED`, deleting due index entries while TTL is `DISABLED` or `ENABLING` loses expirations across toggles, and retaining `m:v` tombstones forever leaks row metadata unless reclaimed safely after a grace window. +6. **Secondary-Index Key Bounds, Online GSI Visibility & Post-Commit Side Effects:** Multi-attribute GSIs (`1..=4` `HASH`, `0..=4` `RANGE`) and LSIs can exceed Bigtable's 4,096-byte row-key limit if raw 2,048-byte partition keys are concatenated directly; non-terminal sort keys suffer sort inversion unless escape-terminated; online `UpdateTable` GSI builds can miss concurrent writes on sibling nodes unless metadata cache TTLs, slow-write self-repair, and pre-backfill visibility fences cooperate under a per-index lease; and post-commit shadow/TTL write failures must be retried and logged for `sweeper` replay without returning misleading HTTP 503 errors after the base row has committed. +7. **Single-Cluster Transactional App Profiles & Auth Constraints:** Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on single-cluster routing app profiles with `allow_transactional_writes = true` (multi-cluster routing rejects `CheckAndMutateRow` with `FailedPrecondition`), requiring startup app-profile verification and explicit service-account or ADC authentication. ## Detailed Design ### 1. Table Mapping & Key Encoding #### A. Table Structure & Naming -* **Catalog & Stream Ledger (`__extenddb_catalog__`):** Stores system settings (`setting:catalog_id`, `setting:encryption_key`, `setting:encryption_key_ring`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIA*` access keys and `ASIA*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:`), distributed worker leases (`lock:`), stream shard lineage/cursor rows (`stream_shard:` carrying `next_seq_num` and `last_sequence_number`), per-event stream deduplication markers (`stream_dedup::`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). -* **Coordinator Transaction Log (`__extenddb_txn_log__`):** Stores coordinator state (`t:state`), incarnation start timestamp (`t:started_at`), canonical sorted participant list (`t:participants`), pre-computed mutations (`t:mutations`), pre-generated stream records (`t:stream_records`), logged TTL index transitions (`t:ttl_mutations`), and `ClientRequestToken` metadata (`t:token_meta`) in column family `t`. -* **Sharded TTL Index (`__extenddb_ttl_index__`):** Stores OCC-timestamped, millisecond-aligned expiration index entries across 16 hash shards in column family `d`. +* **Catalog & Stream Ledger (`__extenddb_catalog__` on `instance_id`):** Stores system settings (`setting:catalog_id`, `setting:catalog_version`, `setting:catalog_encryption_key`, `setting:encryption_key_ring`, `setting:default_account_id`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:` + `version:catalog`), renewed migration & worker leases (`lock:`), live server registrations (`server_registration:`), stream shard lineage/cursor rows (`stream_shard:` carrying `next_seq_num` and `last_sequence_number`), per-event stream deduplication markers (`stream_dedup::`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). +* **Data Migration Ledger (`__extenddb_data_ledger__` on `effective_data_instance_id`):** Stores the `StoreKind::Data` baseline ledger rows (`migration_ledger:data:0001`) in column family `c` (qualifier `j`) so separate `data_instance_id` deployments track data-store initialization independently of `__extenddb_catalog__`. +* **Coordinator Transaction & Side-Effect Log (`__extenddb_txn_log__` on `effective_data_instance_id`):** Stores coordinator state (`t:state`), incarnation start timestamp (`t:started_at`), canonical sorted participant list (`t:participants`), pre-computed mutations (`t:mutations`), pre-generated stream records (`t:stream_records`), logged TTL index transitions (`t:ttl_mutations`), and `ClientRequestToken` metadata (`t:token_meta`) in column family `t`—covering 2PC transactions (`txn-*`), stream-fenced single-item writes (`sgl-*`), and post-commit side-effect recovery records (`post-*`). +* **Sharded TTL Index & Tombstone GC Queue (`__extenddb_ttl_index__` on `effective_data_instance_id`):** Stores OCC-timestamped, millisecond-aligned expiration index entries across 16 hash shards (`0x00..=0x0F`) and disjoint `b"tomb:"` (`0x74`) version-only tombstone reclamation entries in column family `d`. * **Data Tables (`t`):** Each DynamoDB table maps to a dedicated Bigtable table named `t` followed by the first 16 lowercase hex characters of the table's unique `table_id` UUID (17 characters total). Deriving physical table names from `table_id` rather than `table_name` guarantees clean isolation across accounts and across `DeleteTable` + `CreateTable` name reuse ([RFC-0003](0003-backend-acceptance-criteria.md) §8.2). Data attributes live in column family `d` (one qualifier per top-level attribute); OCC row versions (`m:v`) and 2PC intent locks (`m:intent:`) live in column family `m`; column family `t` is reserved. -* **GSI Shadow Tables (`t_g`):** Each GSI maps to a shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit), storing projected item attributes in column family `d` and base-row OCC version guards (`m:v`) in column family `m`. +* **GSI & LSI Shadow Tables (`t_g` and `t_l`):** Each GSI (`_g`) and each LSI (`_l`) maps to an ordered shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit), storing projected item attributes (plus full HASH key attributes for defense-in-depth collision filtering) in column family `d` and base-row OCC version guards (`m:v`) in column family `m`. Storing LSIs in dedicated ordered shadow tables avoids loading entire partitions into memory on `Query`/`Scan` while preserving synchronous `ConsistentRead = true` maintenance on the write path. -#### B. Exact Decimal & Order-Preserving Key Encoding -Cloud Bigtable sorts row keys by unsigned raw byte lexicographical order and enforces a **4 KiB (4096-byte)** row-key limit, validated upfront in `row_key::encode_key` and `gsi::shadow_row_key_for_item`. +#### B. Exact Decimal, Digest-Bounded & Order-Preserving Key Encoding +Cloud Bigtable sorts row keys by unsigned raw byte lexicographical order and enforces a **4 KiB (4,096-byte)** row-key limit, validated upfront in `row_key::encode_key` and `gsi::shadow_row_key_for_item` **before** any base-table `put_cas` or 2PC commit executes. Base-table row keys follow: ```text Composite Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] [sk_tag:1] [sk_bytes] PK-Only Key: [pk_tag:1] [pk_len:u32BE:4] [pk_bytes] ``` -Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, `0x4E` for `N`, `0x42` for `B`). +Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, `0x4E` for `N`, `0x42` for `B`). Because DynamoDB limits HASH keys to 2,048 bytes and RANGE keys to 1,024 bytes, a base-table row key is at most `1 + 4 + 2048 + 1 + 1024 = 3,078 <= 4,096` bytes. * **Partition (`HASH`) Keys:** Length-prefixed (`[pk_len:u32BE:4]`) before `[pk_bytes]` so variable-length partition keys cannot collide across boundaries and all items sharing a partition key sort contiguously. Parallel scan segment assignment hashes the `[pk_tag:1][pk_len:4][pk_bytes]` prefix with CRC32 (`crc32(pk_prefix) % total_segments`), shared identically between `QueryScan::scan` and `DataEngine::scan_key_in_segment`. -* **Sort (`RANGE`) Keys:** Stored as raw order-preserving bytes **without** a length prefix on terminal segments so string and binary sort keys compare in unsigned byte-lexicographic order regardless of length. +* **Sort (`RANGE`) Keys:** Stored as raw order-preserving bytes **without** a length prefix on terminal segments so string and binary sort keys compare in unsigned byte-lexicographic order regardless of length. Base-table `Query` range bounds (`build_base_range_for_query`) use exact closed/open sort-key bounds for `=`, `<`, `<=`, `>`, `>=`, and `BETWEEN`, reserving the `0xFF` prefix trailer strictly for `begins_with` and whole-partition scans. * **Exact 38-Digit Decimal `N` Encoding (`encoding::number`):** DynamoDB numbers support up to 38 significant digits over scientific exponents `[-130, +125]`. Numbers are normalized (stripping leading/trailing zeros and collapsing `-0` / `0.0` to canonical zero) and encoded without floating-point conversion: * **Negative (`value < 0`):** Sign byte `0x00`, inverted biased exponent `0xFF - (sci_exp + 130)`, and 38 digit bytes inverted as `9 - digit` (padded with `0x09` so shorter magnitudes compare greater / closer to zero). * **Zero (`value == 0`):** Single byte `[0x80]`. * **Positive (`value > 0`):** Sign byte `0xFF`, biased exponent `(sci_exp + 130) as u8`, and 38 digit bytes `0..=9` (padded with `0x00`). * Inputs exceeding 38 significant digits or exponent bounds `[-130, 125]` are rejected at write/query time with `ValidationException`. -* **GSI Shadow Row Keys (`gsi::shadow_row_key_for_item`):** +* **Digest-Bounded GSI & LSI Shadow Row Keys (`gsi::shadow_row_key_for_item`):** + Raw concatenation of a 2,048-byte index HASH key, a 1,024-byte index RANGE key, a 2,048-byte base HASH key, and a 1,024-byte base RANGE key would reach 6,158 bytes and exceed Bigtable's 4,096-byte row-key limit. Because HASH keys are queried strictly by equality (never by byte-order range) and full HASH attributes are stored in column family `d` cells, the index partition envelope (`1..=4` `HASH` keys) uses a fixed 32-byte SHA-256 digest and the base partition-key tie-breaker combines a 64-byte order-preserving escaped prefix with a 32-byte SHA-256 digest: ```text - GSI Composite Key: [gsi_pk_tag:1] [gsi_pk_len:u32BE:4] [gsi_pk_bytes] - [gsi_sk_tag:1] [escape_encoded(gsi_sk_bytes)] [0x00 0x00] - [base_pk_tag:1] [base_pk_len:u32BE:4] [base_pk_bytes] - [base_sk_tag:1] [base_sk_bytes] + Index PK Digest Prefix: [0x44 ('D'):1] [32u32BE:4] [SHA-256(index_pk_envelope):32] (37 bytes) + Index Sort Segments: ([idx_sk_tag_j:1] [escape_encoded(idx_sk_bytes_j)] [0x00 0x00]){0..4} + Base Key Tie-Breaker: [base_pk_tag:1] [escape_encoded(base_pk_bytes[..min(64)])] [0x00, 0x00|0x01] [SHA-256(base_pk):32] ([base_sk_tag:1] [base_sk_bytes])? ``` - * **Non-Terminal Sort Key Escape Encoding (`gsi_sk`):** Every `0x00` byte in `gsi_sk_bytes` is escaped as `0x00 0xFF` and terminated by `0x00 0x00` (FoundationDB tuple encoding). Without termination, the following `base_pk_tag` byte (e.g., `0x53`) would participate in sort-key comparison and invert ordering (e.g., `"A"` sorting after `"AB"` because `0x53 > 0x42`). - * **Terminal Sort Key (`base_sk`):** Remains raw order-preserving bytes to the end of the row key. + * **Bounded Size & Order-Preserving Tie-Breaking:** Every single-`RANGE` GSI and LSI shadow key is at most `37 + (1 + 2048 + 2) + (1 + 128 + 2 + 32) + (1 + 1024) = 3,276 <= 4,096` bytes—even with 2,048-byte partition keys and 1,024-byte all-`0x00` sort keys—while items sharing identical `(gsi_pk, gsi_sk)` with `<= 64`-byte base partition keys sort in exact DynamoDB lexicographical base-PK order. Multi-`RANGE` GSIs (`2..=4` `RANGE` keys) additionally validate the assembled shadow key against `row_key::MAX_ROW_KEY_SIZE` (`4,096`) in `prepare_shadow_plan` **before** mutating the base table. + * **Multi-Attribute Partition Envelope (`1..=4` `HASH` Keys) & Exact Equality Filtering:** The hashed `index_pk_envelope` frames single-`HASH` (`[tag:1][len:4][bytes]`) and multi-`HASH` (`[0x4D][inner_len:4]([tag_i:1][len_i:4][bytes_i]){2..4}`) keys unambiguously, and `QueryScan::query` (guided by an explicit `is_index: bool` flag from `BigtableEngine` so a GSI sharing the base table's key schema still uses shadow-key bounds) verifies the decoded HASH attributes in column family `d` before counting toward `limit`. Items missing any index `HASH` or `RANGE` key attribute are omitted from the shadow table (sparse-index semantics). + * **Non-Terminal Sort Key Escape Encoding (`0..=4` `RANGE` Keys):** Every `0x00` byte in each `idx_sk_bytes_j` is escaped as `0x00 0xFF` and terminated by `0x00 0x00` (FoundationDB tuple encoding), preserving DynamoDB's lexicographic order across all `RANGE` attributes and base-key tie-breakers without sort-key boundary inversion. ### 2. Transaction Rules, Deterministic OCC Timestamps & Isolation Guarantees #### A. Transaction Validation & Idempotency Rules -* **`ClientRequestToken` Idempotency (`RFC-0003` §3.3):** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a strict **10-minute (`600s`) `applied_at` window** (`check_idempotency_record` evicts expired entries via `Catalog::mutate_json_cas`) and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`: +* **`ClientRequestToken` Idempotency (`RFC-0003` §3.3):** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a strict **10-minute (`600 s`) `applied_at` window** (`check_idempotency_record` evicts expired entries via `Catalog::mutate_json_cas`) and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`: * `TxnCoordinator::open_with_token` atomically persists `TxnTokenMeta` (`account_id`, `token`, `fingerprint`) in `t:token_meta` alongside `t:state = PENDING` and `t:started_at`, returning `(created, started_at_micros)`. * When `created == true`, the caller immediately re-verifies `idem::` (rolling back and dropping its nascent `PENDING` incarnation if a prior winner persisted `idem:` and dropped `txn:` between pre-check and `open_with_token`). * When `created == false`, the caller never strips intents belonging to an active concurrent owner; instead, the follower loop validates `t:token_meta.fingerprint` across `PENDING`, `COMMITTED`, and `CLEANED` states (returning `IdempotentMismatch` immediately on payload mismatch without poisoning `idem:`, and cooperatively rolling forward `COMMITTED` transactions before returning `IdempotentReplay`). - * Both inline Phase 2 (`roll_forward`) and `sweeper::sweep_with_cutoff_override` (on both `COMMITTED` and `CLEANED` coordinator rows) persist `idem::` via `persist_idempotency_if_unexpired` **before** marking `CLEANED` and calling `drop_matching_start`, while Phase 1 `ConditionFailed` rollbacks drop `txn:` without writing `idem:` so retries with the same token can execute cleanly. -* **Duplicate Participant Rejection & Canonical Lock Ordering (`RFC-0003` §3.4):** Any `TransactWriteItems` request targeting the same `(data_table, row_key)` more than once is rejected upfront with `ValidationException`. Participant locks are acquired in canonical `(data_table, row_key)` lexicographical order (`ParticipantRow: Ord`) to prevent `[k1, k2]` vs. `[k2, k1]` deadlocks while preserving caller-order indices on `StorageError::TransactionCanceled(reasons)` (never leaking `StorageError::TransactionConflict` from 2PC, and honoring per-item `ReturnValuesOnConditionCheckFailure::None` vs. `AllOld`). + * Both inline Phase 2 (`roll_forward`) and `sweeper::sweep_once` (on both `COMMITTED` and `CLEANED` coordinator rows) persist `idem::` via `persist_idempotency_if_unexpired` **before** marking `CLEANED` and calling `drop_matching_start`, while Phase 1 `ConditionFailed` rollbacks drop `txn:` without writing `idem:` so retries with the same token can execute cleanly. +* **Key-Fault Precedence, Item-Size Enforcement, Duplicate Participant Rejection & Canonical Lock Ordering (`RFC-0003` §3.4):** `extenddb-engine` (`crates/engine/src/transact_write_items.rs`) rejects any `TransactWriteItems` request targeting the same item more than once before reaching storage. Inside `BigtableEngine::transact_write_items`, the backend runs up-front primary-key, secondary-index key, and shadow-key size checks (`transact_op_key_checks`, `prepare_shadow_plan`) across all members before locking or opening a coordinator row, and evaluates conditions, update expressions, `max_item_size_bytes` (`validate_transact_update_item_size`, alongside the 31-region statement-size `validate_update_item_size` on standalone `UpdateItem`), and post-update secondary-index key constraints across all locked items before resolving cross-member key-fault precedence via `CancellationReason::resolve_key_faults`. Participant locks are acquired in canonical `(data_table, row_key)` lexicographical order (`ParticipantRow: Ord`) to prevent `[k1, k2]` vs. `[k2, k1]` deadlocks while preserving caller-order indices on `StorageError::TransactionCanceled(reasons)` via `CancellationReason::transaction_conflict()` (honoring per-item `ReturnValuesOnConditionCheckFailure::None` vs. `AllOld`). #### B. Lock-then-Read Coordinator 2PC Flow -`TransactWriteItems` acquires per-row intents in sorted order *before* reading participant rows and evaluating condition expressions, transitions `(t:state == PENDING && t:started_at == started_at_micros) -> COMMITTED` via incarnation-fenced CAS `CheckAndMutateRow` in `__extenddb_txn_log__`, applies mutations idempotently via `roll_forward`, and acknowledges HTTP 200 OK only after Phase 2 mutations, GSI shadows, TTL transitions, stream records, and `idem:` entries are durable: +`TransactWriteItems` acquires per-row intents in sorted order *before* reading participant rows and evaluating condition expressions, transitions `(t:state == PENDING && t:started_at == started_at_micros) -> COMMITTED` via incarnation-fenced CAS `CheckAndMutateRow` in `__extenddb_txn_log__`, applies mutations idempotently via `roll_forward`, and logs (without surfacing HTTP 503 to the client) any post-commit transient error so `sweeper` finishes cleanup without triggering duplicate SDK retries: ```mermaid sequenceDiagram participant C as Coordinator (ExtendDB) participant L as __extenddb_txn_log__ - participant B as Bigtable Data / GSI / Catalog + participant B as Bigtable Data / Index / Catalog C->>L: Phase 1: open_with_token (CheckAndMutateRow: t:state = PENDING, t:started_at, t:token_meta) loop Each participant row in sorted (data_table, row_key) order @@ -85,19 +87,19 @@ sequenceDiagram alt Intent Contention Exhausts Retries C->>L: try_abort_pending (CAS PENDING + started_at -> ABORTED) C->>B: Clear placed intents & drop_matching_start - Note over C: Return TransactionCanceled (TransactionConflict) + Note over C: Return TransactionCanceled (CancellationReason::transaction_conflict) end C->>B: Read locked participant rows & capture OCC versions (m:v) - Note over C: Evaluate ConditionExpressions & compute next_occ_version - alt Any Condition Fails + Note over C: Evaluate ConditionExpressions, UpdateExpressions, max_item_size_bytes & shadow keys + alt Any Member Fails C->>L: try_abort_pending (CAS PENDING + started_at -> ABORTED) C->>B: Clear intents & drop_matching_start - Note over C: Return TransactionCanceled (ConditionalCheckFailed honoring ReturnValuesOnCCF) + Note over C: Resolve cross-member precedence (CancellationReason::resolve_key_faults) end C->>L: Phase 2 Commit: try_commit_full (CAS PENDING + started_at -> COMMITTED, mutations, stream_records, ttl_mutations) - loop Each mutated participant (roll_forward) + loop Each mutated participant (roll_forward; TableNotFound treated as done) C->>B: apply_fenced_mutation (if m:intent: && OCC state == expected: write d:* & m:v at occ_ts, retain intent) - C->>B: Version-guarded GSI shadow updates (put/delete_shadow_versioned) & OCC-bounded TTL index updates + C->>B: Version-guarded GSI & LSI shadow updates + OCC-bounded TTL index & tomb: GC updates end C->>B: Append contiguous per-shard stream slot (write_record_ordered + stream_dedup) C->>B: Persist idem:: (if t:token_meta present) @@ -105,24 +107,18 @@ sequenceDiagram C->>B: Clear intent (DeleteFromColumn m:intent:) end C->>L: Mark CLEANED (@ clean_ts > commit_ts) & drop_matching_start - Note over C: Return HTTP 200 OK (Read-Your-Writes Boundary) + Note over C: Return HTTP 200 OK ``` -#### C. Read Isolation, Incarnation-Fenced CAS Commit/Abort & `TransactGetItems` Double-Read Snapshot -* **Read-Your-Writes Acknowledgment Boundary:** Success is returned only after Phase 2 mutations are applied to column family `d` and GSI shadow tables, guaranteeing `ConsistentRead = true` (`GetItem`, `Query`, `Scan`) and `TransactGetItems` immediately observe the committed state. -* **Read Committed (No Dirty Reads):** Uncommitted transactions write only `m:intent:` in family `m`. Standard reads filter strictly on family `d` (`Chain([FamilyNameRegexFilter("^d$"), CellsPerColumnLimitFilter(1)])`) and never observe uncommitted writes. -* **Incarnation-Fenced Mutual Exclusion Between `try_commit_full` and `try_abort_pending` (`RFC-0003` §3.1):** Both `TxnCoordinator::try_commit_full` (`PENDING -> COMMITTED`) and `TxnCoordinator::try_abort_pending` (`PENDING -> ABORTED`) execute `CheckAndMutateRow` predicated on `build_pending_incarnation_predicate(started_at_micros)` (applying `CellsPerColumnLimitFilter(1)` **before** `ValueRegexFilter` on `t:state == "PENDING"` and `t:started_at == started_at_micros`), and `sweeper` / inline cooperative recovery always CAS-transitions `PENDING -> ABORTED` **before** clearing any participant intent (if CAS fails because the coordinator concurrently reached `COMMITTED`, recovery immediately invokes `roll_forward`). Row drops use `drop_matching_start(txn_id, started_at_micros)` and stale intent cleanup uses timestamp-bounded `clear_intent_up_to` so a stale cleaner can never delete a newer reused token incarnation. -* **Zero Wall-Clock Intent Bypass & Cooperative Resolution (`RFC-0003` §3.1, §3.5, §4.2):** `build_active_intent_filter` and `build_intent_presence_filter` carry **no** wall-clock `TimestampRangeFilter`, because an intent older than `intent_timeout_secs` may belong to a `COMMITTED` coordinator awaiting roll-forward. Whenever a writer or worker encounters an intent on a row, `resolve_blocking_intents` / `read_row_resolving_committed_intents` inspects `__extenddb_txn_log__`: `COMMITTED` transactions are rolled forward immediately, timed-out `PENDING` transactions are CAS-aborted and cleaned up, and `ABORTED`/`CLEANED`/dropped intents are cleared safely. -* **ABA-Safe Fenced Phase 2 Apply & Side-Effect Gating:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard (`(Some(v), _) -> m:v == v`; `(None, false) -> neither m:v nor d:* exists`; `(None, true) -> d:* exists && m:v absent`). Unified `roll_forward` tracks `materialized_participants` (`applied || (cur_ver == Some(new_version) && payload_matches)`), gating GSI shadow writes, `TxnTtlMutation` maintenance, **and** `TxnStreamRecord` emission so superseded coordinators emit zero phantom side effects. -* **Serializable `TransactGetItems` via Optimistic Double-Read Snapshot Validation (`RFC-0003` §3.5, §9.1, §9.2):** `TransactGetItems` validates keys upfront via `validate_key_only` (returning `TransactionCanceled` with `ValidationError` reasons on malformed keys), deduplicates physical row keys while preserving positional output mapping, and executes a non-mutating double-read loop: - * **Pass 1:** Batch-reads `RowSnapshot` (`d:*`, `m:v`, and all `(m:intent:, ts_micros)` regardless of age) across all unique keys and queries `TxnCoordinator::get_state` for every referenced `txn_id`. - * **Pass 2 Validation:** Re-reads `RowSnapshot`s across all unique keys and re-queries referenced coordinator states, accepting the snapshot if and only if `(m:v, intents, d:*)` and coordinator `(state, started_at)` match identically across Pass 1 and Pass 2—proving a single linearization point across concurrent `PENDING -> COMMITTED`, `COMMITTED -> CLEANED -> drop`, and OCC updates. - * **Monotonic Coordinator `SetCell` Transitions:** State transitions (`PENDING` at `t0`, `ABORTED`/`COMMITTED` at `t1 > t0`, `CLEANED` at `t2 > t1`) write monotonic `SetCell(t:state)` values without `DeleteFromColumn(t:state, ...)`, and `get_state` treats any row lacking `t:state` as `Ok(None)`, eliminating transient `StorageError::Internal` HTTP 500s on `cbtemulator`. +#### C. Read Isolation, Cooperative Read-Through & `TransactGetItems` Double-Read Snapshot +* **Consistent Read-Through on `GetItem` & `TransactGetItems`:** Whenever `DataEngine::get_item` or `TransactGetItems` encounters row intents (`m:intent:`), it consults `__extenddb_txn_log__`: if a referenced coordinator is `COMMITTED` and its post-image has not yet applied to family `d`, both `GetItem` (returning the committed post-image and kicking off best-effort roll-forward) and `TransactGetItems` serve the committed post-image immediately, while `PENDING` or `ABORTED` intents return the existing family `d` value without dirty reads. +* **Incarnation-Fenced Mutual Exclusion & Deleted-Table Tolerance (`RFC-0003` §3.1):** Both `TxnCoordinator::try_commit_full` (`PENDING -> COMMITTED`) and `TxnCoordinator::try_abort_pending` (`PENDING -> ABORTED`) execute `CheckAndMutateRow` predicated on `build_pending_incarnation_predicate(started_at_micros)`, and `sweeper` / inline cooperative recovery always CAS-transitions `PENDING -> ABORTED` **before** clearing any participant intent. If a table involved in a multi-table transaction is dropped via `DeleteTable` after `COMMITTED`, `roll_forward`, `apply_fenced_mutation`, and `clear_intent` treat Bigtable `NOT_FOUND` (`is_table_not_found_err`) on the deleted table as completed so the remaining tables finish rolling forward and the coordinator entry is cleaned cleanly. +* **Zero Wall-Clock Intent Bypass:** `build_active_intent_filter` and `build_intent_presence_filter` carry **no** wall-clock `TimestampRangeFilter`, because an intent older than `intent_timeout_secs` may belong to a `COMMITTED` coordinator awaiting roll-forward. +* **ABA-Safe Fenced Phase 2 Apply & Side-Effect Gating:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard. Unified `roll_forward` tracks `materialized_participants`, gating GSI/LSI shadow writes, `TxnTtlMutation` maintenance, **and** `TxnStreamRecord` emission so superseded coordinators emit zero phantom side effects. +* **`TransactGetItems` Optimistic Double-Read Snapshot Validation (`RFC-0003` §3.5, §9.1, §9.2):** `TransactGetItems` validates keys upfront via `validate_key_only`, deduplicates physical row keys while preserving positional output mapping, and executes a non-mutating Pass 1 / Pass 2 double-read loop across `RowSnapshot`s and referenced coordinator states so concurrent `PENDING -> COMMITTED`, `COMMITTED -> CLEANED -> drop`, and OCC updates trigger a retry rather than returning a torn cross-item view. -#### D. Deterministic OCC-Derived Cell Timestamps & Single-Row Concurrency Control -Using server-assigned cell timestamps (`timestamp_micros: -1`) is unsafe under `MaxNumVersions(1)`: if two writers pass filters within a narrow window, or tablet servers experience slight clock skew across tablet moves or recovery roll-forward, `MaxNumVersions(1)` compaction retains whichever cell had the higher wall-clock arrival timestamp per qualifier rather than the higher logical OCC version, risking torn rows (`d:*` from one write paired with `m:v` or attributes from another). - -To eliminate torn rows while satisfying Cloud Bigtable's **`TimestampGranularity::MILLIS`** rule (which rejects explicit `SetCell.timestamp_micros` and `TimestampRange` bounds not divisible by `1_000` with `INVALID_ARGUMENT`), all row writes and range filters derive deterministic millisecond-aligned timestamps directly from the monotonic OCC version: +#### D. Deterministic OCC-Derived Cell Timestamps, Chunked Mutations & Post-Commit Recovery +To prevent torn rows under `MaxNumVersions(1)` while satisfying Cloud Bigtable's **`TimestampGranularity::MILLIS`** rule (`timestamp_micros % 1_000 == 0`), all row writes and range filters derive deterministic millisecond-aligned timestamps directly from the monotonic OCC version: * **Hybrid Monotonic OCC Version (`item_ops::next_occ_version` & `next_millis_exclusive`):** * `now_ms = unix_timestamp_millis().max(1)` @@ -130,73 +126,60 @@ To eliminate torn rows while satisfying Cloud Bigtable's **`TimestampGranularity * `next_occ_version(Some(prev)) = prev.max(now_ms) + 1` * `version_to_timestamp_micros(v) = (v * 1_000) as i64` * `next_millis_exclusive(ts_micros) = ((ts_micros / 1_000) + 1) * 1_000` -* **Uniform Row-Wide & Version-Guarded GSI Shadow Stamping:** Every `SetCell` in a write—every attribute cell in `d:*`, the `m:v` version cell (followed by bounded `DeleteFromColumn(m:v, [0, occ_ts))`), and every projected cell + `m:v` guard in GSI shadow tables—is stamped with `version_to_timestamp_micros(next_version)`. GSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, and `ItemOps::delete_shadow_orphan_if_unchanged`) never issue unbounded `DeleteFromFamily("d")` or `DeleteFromRow`: instead, they inspect `(existing_quals, max_d_ts, cur_ver)` and execute `CheckAndMutateRow` predicated on exact `m:v == cur_ver` (or missing `m:v`), placing `SetCell` before bounded per-qualifier `DeleteFromColumn` (`[0, occ_ts)` / `[0, next_millis_exclusive(occ_ts))`) and rejecting (`Ok(false)`) any delayed writer or reconciler (`new_version < cur_ver`) so stale mutations never overwrite or delete newer `v2` shadow state. -* **Monotonic Tombstone Versioning on Delete:** Deleting an existing base or GSI shadow row advances `SetCell("m", "v", next_version)` at `version_to_timestamp_micros(next_version)` (with bounded `DeleteFromColumn("m", "v", [0, occ_ts))`). Retaining the monotonic `m:v` marker across deletes prevents ABA version reuse and timestamp regression on rapid `Put -> Delete -> Put` cycles, while `Query`, `Scan`, and `BatchGetItem` filter on `FamilyNameRegexFilter("^d$")` so version-only tombstones never appear as items or consume `rows_limit`. -* **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** Because Bigtable row filters have no boolean `NOT` operator, `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`: - * **Versioned Existing Row (`read_version = Some(v)`):** Predicate matches if `(any m:intent:* exists) OR (m:v != v)`. - * **Unversioned Pre-Existing Row (`read_version = None, row_existed = true`):** Predicate matches if `(any m:intent:* exists) OR (m:v exists) OR (d:* missing)`. - * **New Row (`read_version = None, row_existed = false`):** Predicate matches if `(any m:intent:* exists) OR (m:v exists) OR (d:* exists)`. - * **Conflict Classification & Contention Retry:** When `predicate_matched == true`, `BigtableEngine` classifies `CasOutcome::IntentPresent` vs. `CasOutcome::OccMismatch`, cooperatively resolves `COMMITTED` or expired `PENDING` intents via `resolve_blocking_intents` (waiting/retrying across transient `sgl-*` single-item fenced writes), returns `StorageError::TransactionConflict` if a live multi-item 2PC `txn-*` holds the row ([RFC-0003](0003-backend-acceptance-criteria.md) §4.3), or retries OCC mismatches with jittered backoff. +* **Single-`SetCell` Shadow Puts & 100,000-Mutation RPC Bound (`MAX_MUTATIONS_PER_RPC = 90_000`):** Because family `d` uses `MaxNumVersions(1)` and every reader applies `CellsPerColumnLimitFilter(1)`, `ItemOps::build_shadow_put_mutations` emits a single `SetCell` per retained projected attribute (`ts_micros >= max_d_ts`) plus `DeleteFromColumn` **only** for removed attributes—keeping a 50,000-attribute `ALL`-projected GSI/LSI shadow write at `50,002` mutations inside a single atomic `CheckAndMutateRow` RPC. As an additional safety bound, `put_cas`, `apply_shadow_version_cas`, `apply_fenced_mutation`, and `mutate_cells` cap the atomic `CheckAndMutateRow` batch (`m:v` + initial cells) to `<= 90,000` mutations and apply any overflow cells in bounded `90,000`-mutation `MutateRow` chunks at the identical `occ_ts`. +* **Version-Guarded Shadow Updates & Durable Post-Commit Side-Effect Recovery:** GSI and LSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, `ItemOps::delete_shadow_orphan_if_unchanged`—sharing `apply_shadow_version_cas`) execute `CheckAndMutateRow` predicated on exact `m:v == cur_ver` (or missing `m:v`) and reject (`Ok(false)`) any delayed writer (`new_version < cur_ver`). On single-item OCC writes (`execute_single_item_write`), shadow keys are pre-computed **before** `put_cas`. Once `put_cas` or `delete_cas` commits the base row, any transient error on GSI/LSI shadow maintenance or TTL index maintenance is retried via `BigtableClient` and, if still failing, recorded as a `COMMITTED` `post-` side-effect entry in `__extenddb_txn_log__` (`TxnCoordinator::write_committed_side_effects`) for `sweeper` replay while logging a warning and returning success to the caller—preventing both silent stale index entries and post-commit 503 double-execution on non-idempotent updates (`SET a = a + 1`). +* **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`, cooperatively resolving `COMMITTED` or expired `PENDING` intents, returning `StorageError::TransactionConflict` if a live multi-item 2PC `txn-*` holds the row ([RFC-0003](0003-backend-acceptance-criteria.md) §4.3), or retrying OCC mismatches with jittered backoff. -#### E. Cloud Bigtable App Profile & Single-Cluster Routing Requirements -Cloud Bigtable requires single-cluster routing (or multi-cluster routing with single-row transactions enabled) to execute `CheckAndMutateRow`. Multi-cluster profiles with eventual consistency reject `CheckAndMutateRow` with `FailedPrecondition`. `BigtableStorageConfig` exposes `app_profile_id` and forwards it on every `ReadRows`, `MutateRow`, `MutateRows`, and `CheckAndMutateRow` RPC so multi-cluster deployments can bind ExtendDB to a single-cluster profile. +#### E. Cloud Bigtable App Profile & Single-Cluster Routing Validation +Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on application profiles configured with **single-cluster routing and single-row transactions enabled** (`SingleClusterRouting { allow_transactional_writes: true }`). Multi-cluster routing profiles do not offer single-row transactions and reject `CheckAndMutateRow` with `FailedPrecondition`. `BigtableStorageConfig` exposes `app_profile_id`, forwards it on every `ReadRows`, `MutateRow`, `MutateRows`, and `CheckAndMutateRow` RPC, and validates the profile at `extenddb serve` startup via `BigtableInstanceAdminClient::get_app_profile` (`AdminClient::validate_app_profile`), refusing startup with an actionable error if the profile uses multi-cluster routing or disables single-row transactions (skipped when targeting `cbtemulator`, which does not implement Instance Admin). -#### F. Garbage Collection (GC) Rules & Recovery Sweeper -* **Column Family GC:** `d` and `m` on data/GSI tables, `c` on `__extenddb_catalog__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. -* **2PC Recovery Sweeper (`sweeper.rs`):** Spawned via `BigtableRuntimeHooks::spawn_workers` under a distributed catalog lease (`lock:sweeper`) with graceful `CancellationToken` shutdown. Timed-out `PENDING` coordinators are first CAS-transitioned to `ABORTED` (`try_abort_pending`) before clearing intents and calling `drop_matching_start` (rolling forward if concurrently `COMMITTED`); `COMMITTED` coordinators are rolled forward idempotently (`roll_forward` applying base rows, versioned GSI shadows, `t:ttl_mutations`, contiguous deduplicated stream records, and `idem::` before marking `CLEANED` and dropping); and stranded `CLEANED` rows persist `idem:` if `t:token_meta` is present before dropping. +#### F. Garbage Collection (GC), Version-Only Tombstone Reclamation & Recovery Sweeper +* **Column Family GC:** `d` and `m` on data/GSI/LSI tables, `c` on `__extenddb_catalog__` and `__extenddb_data_ledger__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. +* **Bounded Tombstone Reclamation (`tomb:` Queue & `reclaim_version_only_row`):** Deleting an item leaves a version-only `m:v` tombstone row to prevent rapid `Put -> Delete -> Put` timestamp regression, and enqueues a fixed 45-byte GC marker `b"tomb:" || ready_ms_be8 || sha256(table_name || 0x00 || row_key)` (`0x74 >= 16`, disjoint from TTL shards `0x00..=0x0F` and immune to 4 KiB key limits) with an `intent_timeout_secs` (`60 s` default) grace window in `__extenddb_ttl_index__`. Once `now_ms >= ready_ms`, `sweeper` calls `ItemOps::reclaim_version_only_row(row_key, expected_version)`, which executes an atomic `CheckAndMutateRow` (`DeleteFromRow` in `false_mutations`) that reclaims the physical Bigtable row **if and only if** zero `m:intent:*` cells exist, `m:v == expected_version`, and zero `d:*` cells exist—never deleting a concurrently re-inserted live item. +* **2PC & Side-Effect Recovery Sweeper (`sweeper.rs`):** Runs under a renewed distributed catalog lease (`lock:sweeper`), CAS-aborting timed-out `PENDING` coordinators, rolling forward `COMMITTED` transactions and `post-*` side-effect records, persisting `idem:` tokens, and draining due `b"tomb:"` tombstone GC entries. ### 3. Unified Fenced DynamoDB Streams Architecture & Stream Lineage -#### A. Write-Ahead Fenced Stream Emission & Labelled Shard Lineage (`stream_lineage`) -To satisfy [RFC-0003](0003-backend-acceptance-criteria.md) §3.2 and §5.1 ("a crash between a committed data write and its stream record insert must not be possible"), stream emission is **never** performed as an unfenced trailing write. Whenever a caller supplies `stream: Some(&StreamCapture)` on a table whose `StreamSpecification.stream_enabled` is active (`active_stream_target_for_capture`), single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through `BigtableEngine::execute_fenced_single_item_write`, sharing the exact same `__extenddb_txn_log__` commit fence as `TransactWriteItems` (while `DataEngine` writes with `stream: None`—such as `ImportTable` bulk imports—preserve the upstream stream-suppression contract without emitting stream events): +#### A. Write-Ahead Fenced Stream Emission, Pre-CAS Shard Creation & Stream Lineage +Whenever a caller supplies `stream: Some(&StreamCapture)` on a stream-enabled table, single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through the `__extenddb_txn_log__` commit fence (`commit_fenced_single_item_write` + `roll_forward`), while `stream: None` writes (`ImportTable` bulk imports) suppress stream emission: -1. **Labelled 4-Shard Stream Lineage (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and provisions `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) in `__extenddb_catalog__` at `stream_shard:`, where `shard_id = shardId-{table_id}-{label_millis:013}{view_digit:1}{index:02}` (61 characters, within the 65-character AWS SDK `ShardId` limit). `UpdateTable` commits `table_meta` via `Catalog::mutate_json_cas` **before** closing disabled shards (`close_shards_by_id` via CAS) or provisioning newly enabled shards (`put_shard_if_absent` followed by `stream_lineage::enable_still_current` re-verification so concurrent disable calls immediately close superseded shards). Writes and `StreamEngine::assign_shard` route partition keys deterministically across the 4 shards via `crc32fast::hash(pk_text.as_bytes()) % SHARDS_PER_STREAM`. -2. **Contention-Resilient Single-Item Serialization (`sgl-` Prefix):** Single-item fenced writes serialize same-process contention per `(data_table, row_key)` via an async mutex (`acquire_single_write_lock`) and tag their coordinator IDs with `sgl-` (`TxnCoordinator::new_single_txn_id`) so cross-process single-item contenders wait and retry cooperatively rather than aborting unconditional `PutItem`/`UpdateItem` calls with spurious `TransactionConflictException`. -3. **Wait-Free Contiguous Per-Shard Sequence Slot Append (`streams.rs`, `RFC-0003` §5.2):** Phase 1 constructs each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER` (`"00000000000000000000000000"`), its associated `ParticipantRow`, and `:` `dedup_key`. During Phase 2 (`streams::write_record_ordered`), under an in-process per-shard mutex (`shard_local_mutex`), the writer reads `ShardMeta.next_seq_num` (`>= 1`) **first**, checks `stream_dedup::` **second**, formats `slot_seq = slot_sequence_number(shard_id, slot)` (`{label_ms:013}{slot:011}{shard_idx:02}`), atomically claims `stream_record::` via `Catalog::put_if_absent` (on slot collision, persisting the slot winner's `stream_dedup` marker **before** advancing `ShardMeta.next_seq_num`), persists its own `stream_dedup` markers, and monotonically advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS (`advance_shard_cursor_at_least`, plus `ensure_shard_past_record` before 24h retention pruning). Because slots `1, 2, 3, ...` are filled strictly in publication order without gaps or duplicates, `get_stream_records` (`after_sequence`) never skips a delayed writer on the same shard. -4. **Atomic Commit Point & Phantom-Free Crash Recovery (`RFC-0003` §5.1, §5.4):** `try_commit_full` writes `COMMITTED` to `__extenddb_txn_log__` together with `t:mutations`, `t:stream_records`, and `t:ttl_mutations` *before* mutating column family `d`. During `roll_forward`, stream records are emitted **only** for `materialized_participants` whose base-row mutation actually materialized, and `stream_dedup` guarantees exact-once emission across arbitrary crash/recovery replays. +1. **Pre-CAS Shard Provisioning & Pre-Close Roll-Forward (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and pre-creates `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) at `stream_shard:` **before** publishing `latest_stream_label` in `table_meta` via `Catalog::mutate_json_cas` (cleaning up orphaned pre-created shards if CAS loses a race). Conversely, disabling a stream calls `roll_forward_committed_txns_for_table` **before** closing shards (`close_shards_by_id` using `O(1)` tail-probing `latest_sequence_for_shard` rather than scanning every historical record), and `streams::write_record_ordered` checks `ending_sequence_number.is_some()` and returns `Ok(None)` without writing past a closed shard's `EndingSequenceNumber`. +2. **Contention-Resilient Single-Item Serialization (`sgl-` Prefix):** Single-item fenced writes serialize same-process contention per `(data_table, row_key)` via an async mutex and tag their coordinator IDs with `sgl-` so cross-process single-item contenders wait and retry cooperatively rather than aborting unconditional writes with `TransactionConflictException`. +3. **Contiguous Per-Shard Sequence Slot Append & Bounded Range Reads (`streams.rs`):** Phase 1 constructs each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER`, its `ParticipantRow`, and `:` `dedup_key`. During Phase 2 (`streams::write_record_ordered`), the writer reads the existing `ShardMeta` (no clock-based sequence fallback), checks `stream_dedup::`, formats `slot_seq = slot_sequence_number(shard_id, slot)`, claims `stream_record::` via `Catalog::put_if_absent` (setting `dynamodb.size_bytes` via `item_size_bytes`), persists `stream_dedup`, and advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS. `StreamEngine::get_stream_records`, `cleanup_expired_stream_records`, and `cleanup_expired_idempotency_tokens` all page through `Catalog::scan_str_range` with server-side `StartKeyOpen`/`StartKeyClosed`, `EndKeyOpen`, and bounded `rows_limit` rather than prefix-scanning entire shards or tables into memory. #### B. Why the `__extenddb_catalog__` Table Ledger Beats Cloud Bigtable Native Change Streams -Cloud Bigtable offers a native Change Streams CDC feature (`ReadChangeStream`), which we evaluated and deliberately rejected in favor of the coordinator-fenced `__extenddb_catalog__` stream ledger for five architectural reasons: - -1. **Transactional Commit Gating:** Bigtable Change Streams emit low-level per-row storage mutations immediately upon `MutateRow` / `CheckAndMutateRow` without awareness of `__extenddb_txn_log__`. Intent placements (`m:intent:`), rolled-back intents, or multi-table 2PC writes in progress would require a complex stateful stream-join consumer to buffer and filter against coordinator state. -2. **Item-Level `StreamViewType` Fidelity:** DynamoDB Streams require complete item-level `OldImage` and `NewImage` projections (`KEYS_ONLY`, `NEW_IMAGE`, `OLD_IMAGE`, `NEW_AND_OLD_IMAGES`) and exact `INSERT` vs. `MODIFY` vs. `REMOVE` classification. Bigtable Change Streams emit cell-level deltas (`SetCell`, `DeleteFromColumn`, `DeleteFromFamily`) and do not materialize prior full-row item images on partial updates or deletes. -3. **Shard Stability & `u128` Sequence-Number Contract:** Bigtable Change Streams dynamically split and merge tablet partitions and address positions via opaque `ChangeStreamContinuationToken`s, which cannot satisfy DynamoDB's stable shard topology, `u128`-parseable decimal `SequenceNumber` ordering (`AT_SEQUENCE_NUMBER` / `AFTER_SEQUENCE_NUMBER`), or 15-minute `ShardIterator` semantics. -4. **TTL Service `UserIdentity` Attribution:** DynamoDB requires TTL deletions to carry `userIdentity = { type: "Service", principalId: "dynamodb.amazonaws.com" }`. Native storage-level CDC carries no application caller or TTL service identity metadata. -5. **Hermetic Emulator & Zero-Admin Portability:** The official `cbtemulator` does not implement `ReadChangeStream`, whereas the `__extenddb_catalog__` ledger runs identically in hermetic CI (`cbtemulator`) and production GCP without requiring separate change-stream retention DDL on every user table. +Cloud Bigtable native Change Streams (`ReadChangeStream`) were evaluated and rejected in favor of the coordinator-fenced `__extenddb_catalog__` stream ledger for five reasons: lack of `__extenddb_txn_log__` 2PC commit gating, cell-level deltas lacking pre-image `StreamViewType` reconstruction, dynamic tablet-split continuation tokens incompatible with DynamoDB `ShardIterator` and `u128` `SequenceNumber`s, missing TTL `Service` `UserIdentity` metadata, and lack of `cbtemulator` support. -### 4. Scalable TTL Indexing & Fenced Expiration +### 4. Scalable TTL Indexing, `ENABLING` Backfill & Fenced Expiration -#### A. Sharded TTL Index Schema (`__extenddb_ttl_index__`) -* **Row Key Binary Layout:** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` - * `shard_id = fnv1a(base_row_key) % 16` distributes writes and sweeps evenly across 16 prefixes instead of creating a monotonic timestamp hotspot. - * `expiry_epoch_secs_be` orders entries chronologically within each shard so each sweep reads only `[shard_id || 0, shard_id || (now + 1))`. -* **OCC-Ordered Write & Recovery Maintenance (`apply_ttl_mutation_versioned`):** `PutItem`, `UpdateItem`, `DeleteItem`, `TransactWriteItems`, and `roll_forward` (via `t:ttl_mutations`) parse TTL attributes via `parse_ttl_epoch_secs` (supporting integer, fractional, and scientific `AttributeValue::N` strings via `bigdecimal` while treating `<= 0` as non-expiring per DynamoDB semantics). Whenever `old_expiry != new_expiry`, old TTL index cells are cleared via bounded `DeleteFromColumn("d", b"", [0, occ_ts))`; whenever `new_expiry` is positive, `insert_ttl_index_entry_at` stamps `SetCell("d", b"", occ_ts)` first followed by bounded `DeleteFromColumn("d", b"", [0, occ_ts))` at `version_to_timestamp_micros(new_version)` (even when `old_expiry == new_expiry`, e.g., `"1000" -> "1000.5"`), making out-of-order `1000 -> 2000 -> 1000` ABA updates commute deterministically with millisecond-aligned timestamps. +#### A. Sharded TTL Index Schema & `ENABLING -> ENABLED` Backfill +* **Row Key Binary Layout:** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` across shards `0..16` (`fnv1a(base_row_key) % 16`), ordered chronologically within each shard. +* **Pre-Existing Item Backfill (`update_ttl` & `create_ttl_index`):** Enabling TTL (`MetadataEngine::update_ttl(..., true)`) sets `ttl.status = "ENABLING"` with a unique `generation` UUID in `table_meta` (reported as `TimeToLiveStatus::Enabling` by `describe_ttl`) and invalidates the metadata cache so live writes immediately begin maintaining `__extenddb_ttl_index__`. `MetadataEngine::create_ttl_index` (spawned asynchronously by `extenddb-engine` and resumed automatically on crash/restart by `ttl_worker`) acquires a renewed per-table `lock:ttl_backfill:` catalog lease, waits `1.35 s` (`await_schema_visibility_fence`) for sibling nodes' `1 s` metadata caches and `250 ms` fast writes to observe `ENABLING`, pages the base table (`read_base_row_for_worker`) inserting OCC-stamped TTL index entries for every item carrying a positive TTL attribute, and promotes `ttl.status` from `"ENABLING"` to `"ENABLED"` via generation-checked CAS. Disabling TTL invokes `MetadataEngine::drop_ttl_index` to purge the table's entries cleanly. +* **OCC-Ordered Write & Recovery Maintenance (`apply_ttl_mutation_versioned`):** Live writes and `roll_forward` parse integer, fractional, and scientific `AttributeValue::N` strings via `parse_ttl_epoch_secs` (treating `<= 0` as non-expiring) and stamp `SetCell("d", b"", occ_ts)` followed by bounded `DeleteFromColumn("d", b"", [0, occ_ts))` so out-of-order `1000 -> 2000 -> 1000` ABA updates commute deterministically. -#### B. Live Verification, Metrics & Fenced TTL Stream Emission (`ttl_worker.rs`) -1. Under the distributed `lock:ttl_worker` catalog lease, scan `[shard || 0, shard || (now + 1))` across all 16 shards, capturing each scanned index cell's `idx_ts_micros`. -2. Confirm the table still exists and has `TimeToLiveStatus::Enabled`. If the table was dropped or TTL was disabled, retire the stale index cell via bounded `DeleteFromColumn("d", b"", [0, next_millis_exclusive(idx_ts_micros)))` without touching base data. -3. Read the live base item + OCC version (`get_item_with_version`, cooperatively resolving any `COMMITTED` intent) and inspect its current TTL attribute (`parse_ttl_epoch_secs`): - * If the item was already deleted or updated to a non-positive value, retire only the scanned index cell up to `next_millis_exclusive(bound_ts)` so concurrent same-second TTL inserts at higher OCC timestamps are never wiped. - * If `live_secs > now` (extended into the future), re-assert `(live_secs, live_ver)` via `ensure_ttl_index_entry` before retiring the stale expired entry. - * Whenever `0 < live_secs <= now` (even if `live_secs != scanned_expiry` due to ABA index skew), proceed to eviction. -4. Issue `DataEngine::delete_item` with `#ttl = :live_exp_str` `ConditionExpression` and, when streams are enabled on the table, a `StreamCapture` carrying `UserIdentity { principal_id: "dynamodb.amazonaws.com", identity_type: "Service" }`, recording `TimeToLiveDeletedItemCount` and `TtlStalenessSeconds` in `MetricsCollector`, then retire the scanned TTL index cell via bounded `DeleteFromColumn("d", b"", [0, next_millis_exclusive(bound_ts)))`. +#### B. Live Verification, Preservation While Off/Enabling & Fenced TTL Stream Emission (`ttl_worker.rs`) +1. Under the renewed distributed `lock:ttl_worker` catalog lease, `ttl_worker` first resumes any interrupted `ENABLING` table backfills, then scans `[shard || 0, shard || (now + 1))` across shards `0..16`. +2. Check table status: if the table was deleted (`TableNotFound`), retire the orphan index cell; if TTL is `Enabling`, `Disabling`, or `Disabled`, **leave the index entry untouched** (`continue`) so entries coming due while TTL is off or mid-backfill are never destroyed prematurely. +3. For `Enabled` tables, read the live base item + OCC version (`get_item_with_version`), retiring stale/extended entries via bounded `DeleteFromColumn` (`[0, next_millis_exclusive(bound_ts))`), and evicting genuinely expired items (`0 < live_secs <= now`) via guarded `DataEngine::delete_item` (`#ttl = :live_exp_str`) with `Service` `UserIdentity` (`dynamodb.amazonaws.com`) stream capture and `TimeToLiveDeletedItemCount` / `TtlStalenessSeconds` metrics. -### 5. Query, Scan, LSI Ordering & Online GSI Lifecycle +### 5. Query, Scan, LSI Shadow Tables & Online GSI Lifecycle -* **Query Direction & `cbtemulator` Compatibility (`query_scan.rs`):** Forward and reverse `Query` calls (`ScanIndexForward`) construct tight byte-range bounds over `[pk_prefix, pk_upper]` (merging `ExclusiveStartKey` into the active sort-key range bound so `BETWEEN` and `begins_with` never lose their upper/lower bounds across pages, [RFC-0003](0003-backend-acceptance-criteria.md) §2.6, and short-circuiting inverted/empty bounds such as `BETWEEN :hi AND :lo` where `:hi > :lo` before issuing an RPC). Production Cloud Bigtable executes descending queries server-side via `ReadRowsRequest { reversed: true }`; when running against `cbtemulator` (which returns `UNIMPLEMENTED` or `FAILED_PRECONDITION` for `reversed: true`), `QueryScan::query` automatically falls back to a bounded partition scan plus in-memory reversal with identical `LastEvaluatedKey` semantics. -* **Exact `LastEvaluatedKey`, LSI `Scan` & Parallel Scan Completeness:** Base and GSI `Query`/`Scan` always resolve `base_key_schema` from catalog `TableDescription` (even when `extenddb-engine` rewrites `TableKeyInfo.key_schema` to the target index schema) and fetch `limit + 1` storage rows so `LastEvaluatedKey` is emitted if and only if unread items remain ([RFC-0003](0003-backend-acceptance-criteria.md) §7.2). `QueryScan::scan_lsi` streams base rows partition-by-partition, filters sparse items lacking `lsi_sk_name` **before** applying `limit`, sorts each partition by `(enc_lsi_sk, enc_base_sk)`, and emits/resumes `LastEvaluatedKey` tuples carrying `(pk, base_sk, lsi_sk)` (§7.1, §7.4). Parallel scans (`total_segments > 1`) page through storage in chunks until `limit + 1` in-segment items (`crc32(pk_prefix) % total_segments == segment`) are collected or the table exhausts (§7.3). -* **Online `UpdateTable` GSI Lifecycle, Version-Guarded Shadows & Background Reconciler (`engine.rs`, `gsi.rs`, `gsi_worker.rs`):** `UpdateTable` executes via `Catalog::mutate_json_cas` (`CatalogJsonAction`) on `table_meta` (matching `update_ttl`, `tag_resource`, `untag_resource`, IAM/policy/secret mutations, and `MetricsStore::insert_metrics`), supporting `GlobalSecondaryIndexUpdates` (`Create` with `CREATING -> backfill -> ACTIVE` transition under `BuildingGsiGuard` and `IndexNotFound` read refusal on `index_info`/`query`/`scan` while `index_status != "ACTIVE"`, `Update` of `WarmThroughput`, and `Delete` with shadow table teardown and orphaned `AttributeDefinitions` pruning), `TableClass`, `WarmThroughput`, and `NoOpUpdate` checks. Both live writes and `gsi_worker` repairs mutate GSI shadow rows exclusively through version-guarded `put_shadow_versioned` / `delete_shadow_versioned` / `delete_shadow_orphan_if_unchanged` (rolling forward committed transactions for the table prior to backfill/reconciliation), and `gsi_worker` promotes interrupted `CREATING` GSIs to `ACTIVE` via CAS only after reconciliation succeeds cleanly. +* **Exact Sort-Key Bounds, Explicit `is_index` Routing & `cbtemulator` Compatibility (`query_scan.rs`):** `BigtableEngine` passes an explicit `is_index: bool` flag (`index_name.is_some()`) into `QueryScan::query`, `QueryScan::scan`, and `QueryScan::key_belongs_to_segment`, ensuring base tables use `build_base_range_for_query` while both GSIs (even when sharing the base table's key schema) and LSIs use `build_gsi_range_for_query` over their respective `_g<8hex>` and `_l<8hex>` shadow tables. Both paths validate `ExclusiveStartKey` schema, scalar types, and partition boundaries, merge `ExclusiveStartKey` into active sort-key bounds, clamp bounds to 4,096 bytes, fetch `limit + 1` matching items for exact `LastEvaluatedKey` emission, and fall back cleanly when `cbtemulator` rejects `ReadRowsRequest { reversed: true }` with `UNIMPLEMENTED`. +* **Online `UpdateTable` GSI Build, Cache Visibility Fence & `CREATING`-Only `gsi_worker` (`engine.rs`, `gsi_worker.rs`):** + * Table metadata is cached for `1 s` (`METADATA_CACHE_TTL`). Any write taking `>= 250 ms` (`FAST_WRITE_BUDGET`) re-reads uncached `table_meta` post-commit (`repair_slow_write_schema_drift`) and repairs any GSI or TTL index added concurrently. + * When `UpdateTable` creates a GSI (`index_status = "CREATING"`), `run_gsi_backfill` acquires a renewed per-index catalog lease `lock:gsi_build::` (so `gsi_worker` never races a live build or rolls back a sibling GSI), waits `1.35 s` (`await_schema_visibility_fence` > `1 s + 250 ms`), rolls forward `COMMITTED` transactions for the table, backfills projected rows via version-guarded `put_shadow_versioned`, and promotes the GSI `"CREATING" -> "ACTIVE"` via CAS (rolling back **only** that GSI if still `"CREATING"` on failure). + * `gsi_worker` runs **only** on tables that currently have at least one `"CREATING"` GSI—resuming interrupted builds under the same `lock:gsi_build::` lease without scanning `ACTIVE` tables every cycle. -### 6. GCP Connectivity, Secret Key Ring, Catalog Stores & Error Classification +### 6. GCP Connectivity, Migrations, Serving Registration & Error Classification ```toml [storage.bigtable] project_id = "my-gcp-project" instance_id = "my-bt-instance" data_instance_id = "my-bt-data-instance" # Optional: separate catalog and data instances -app_profile_id = "single-cluster-profile" # Recommended: single-cluster routing for CheckAndMutateRow +app_profile_id = "single-cluster-profile" # Single-cluster routing with single-row transactions enabled credentials_path = "/etc/extenddb/sa.json" # Optional: explicit GCP service-account JSON key -# emulator_host = "127.0.0.1:8086" # Optional: local cbtemulator endpoint +# emulator_host = "127.0.0.1:8086" # Optional: local cbtemulator endpoint (or BIGTABLE_EMULATOR_HOST) pool_size = 20 catalog_pool_size = 8 sweeper_cadence_secs = 30 @@ -205,69 +188,69 @@ ttl_scan_cadence_secs = 60 gsi_reconcile_cadence_secs = 300 ``` -* **Safe Client Construction & Split-Instance Isolation (`data/client.rs`):** `BigtableClient::connect` builds emulator connections via `BigTableConnection::new_with_emulator` and explicit service-account connections via `gcp_auth::CustomServiceAccount::from_file` + `BigTableConnection::new_with_token_provider` without any `unsafe` process-environment mutation (`std::env::set_var`) or `Box::leak` allocations. When `data_instance_id` differs from `instance_id`, catalog tables, distributed worker leases (`lock:*`), and stream ledger records stay strictly on `instance_id` (`catalog_client` sized by `catalog_pool_size`) while user data tables, GSI shadow tables, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` live strictly on `data_instance_id` (`data_client` sized by `pool_size`). -* **Thin-Binary Compile-Time Registration (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` so standard `cargo build` / `cargo check` invocations work unchanged, while exposing a mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`) that installs `extenddb_storage_bigtable::backend()` via `extenddb_storage::set_backend` with zero edits to `crates/core`, `crates/engine`, `crates/auth`, or `crates/server`. -* **At-Rest Secret Encryption & KEK/DEK Key Ring (`extenddb_storage::secret_keys`):** `m0001_baseline` seeds a unique `setting:catalog_id` UUID, and `BigtableCatalogStore` / `BigtableCredentialStore` encrypt and decrypt `AKIA*` access-key secrets and `ASIA*` STS session secrets via `SecretKeys` (`SecretRow::access_key` and `SecretRow::session` AAD binding `(table, access_key_id, account_id, principal, session_name, expires_at)`). `SettingsStore::replace_setting` uses single-row `CheckAndMutateRow` compare-and-swap (`Catalog::mutate_json_cas` / `put_if_absent`), and `ManagementStore` implements cursor-paged `read_secret_page`, CAS `write_secrets`, `delete_secrets`, and `delete_setting` to support `extenddb encryption-key switch`, `rotate`, `rewrap`, and `reset`. -* **IAM Leftover Hygiene, Operational Metrics & Login Rate Limiting (`catalog_store.rs`):** Deleting or creating a user, group, role, or account atomically purges associated policies, permission boundaries, tags, memberships, access keys, and `failed_login:/` rate-limit entries (`iam_leftovers_conformance`). `MetricsStore::insert_metrics` accumulates minute-bucketed metrics keyed by `metric::` via `Catalog::mutate_json_cas` and supports retention pruning (`metrics_conformance`). -* **Frozen Baseline & Additive Migration Ledger (`m0001_baseline.rs`, `migrations.rs`):** `m0001_baseline.rs` (`#[rustfmt::skip]`) provisions `__extenddb_catalog__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__` plus `setting:catalog_id`; `MigrationId`s `2..=12` record cleanly as schema-less no-ops in `migration_ledger:catalog:` under `lock:catalog_migrations`. -* **gRPC Transient Error Classification (`data/client.rs`):** Data-plane and catalog errors are classified via `map_bigtable_err`, `map_catalog_err`, and `classify_grpc_status`: - * `Unavailable`, `DeadlineExceeded`, `Aborted`, `ResourceExhausted`, RPC timeouts, and transient I/O errors map to `StorageError::Transient` (surfaced by the server as retryable HTTP 503 `ServiceUnavailable` rather than opaque HTTP 500s). +* **Resilient Direct `tonic` Pool, Multi-Frame `ReadRowsAssembler`, `64 MiB` gRPC Limits & Split-Instance Isolation (`data/client.rs`, `config.rs`):** `BigtableClient::connect` builds a multi-channel `tonic::transport::Channel::balance_channel` pool directly over `googleapis_tonic_google_bigtable_v2` configured with `64 MiB` max encoding/decoding message sizes (`MAX_GRPC_MESSAGE_BYTES`), a stateful multi-frame `ReadRowsAssembler` (reassembling multi-megabyte cells and multi-cell rows split across consecutive `ReadRowsResponse` stream messages), `x-goog-request-params` regional routing metadata, OAuth2 bearer token injection via `gcp_auth` (skipped with a `BigtableClient::log_startup_endpoint` `tracing::warn!` warning when `emulator_host` or `BIGTABLE_EMULATOR_HOST` is resolved via `BigtableStorageConfig::resolve_emulator_host`, or logged via `tracing::info!` when connecting to Cloud Bigtable over TLS), and automatic pool replacement + bounded retry on HTTP/2 `GoAway` (`ENHANCE_YOUR_CALM`) or transport resets across `read_rows`, `mutate_row`, stream-draining `mutate_rows`, and idempotent/pre-execution `check_and_mutate_row` errors. +* **Compile-Time Backend Registration & Shared Storage Helpers (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` while exposing the mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`, linted in `.github/workflows/clippy.yml`). Shared IAM key/policy helpers (`generate_access_key_id`, `generate_secret_key`, `generate_session_key_id`, `generate_session_token`, `self_service_policy`) and `string_coerce::u64` live in `extenddb-storage` (reused across all five backends and `crates/server`), and `create_backup_unsupported("bigtable")` wires the startup banner/log notice in `crates/{engine,server,app}`. +* **At-Rest Secret Encryption & Fail-Closed Auth Redaction (`catalog_store.rs`):** `BigtableCatalogStore` and `BigtableCredentialStore` encrypt and decrypt `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions via `SecretKeys` (`CATALOG_KEY_SETTING = "catalog_encryption_key"`). Any corrupt catalog row, missing key ring, or AEAD decryption failure in `lookup_credential` logs details server-side via `tracing::error!` and returns a redacted `DynamoDbError::InternalServerError("Internal error during authentication")` without leaking internal identifiers. No unauthenticated development admin bypass exists in the crate. +* **`ADR-0023` / `ADR-0029` Baseline Migrations, Renewed Lock & `ServingRegistrar` (`m0001_baseline.rs`, `migrations.rs`, `runtime_hooks.rs`):** + * **Migration 1 (`MigrationId::Baseline`, `Kind::Breaking`, convergent):** Splits cleanly across `M0001CatalogBaseline` (`StoreKind::Catalog` on `instance_id`: provisions `__extenddb_catalog__` and `setting:catalog_id`) and `M0001DataBaseline` (`StoreKind::Data` on `effective_data_instance_id`: provisions `__extenddb_data_ledger__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__`), pinned under a single SHA-256 checksum verified by `devtools/check-released-through`. + * **Migrations 2–12 (`NotApplicable`):** Recorded in `migration_ledger:catalog:` alongside RFC 3339 `version:catalog` and `setting:catalog_version`. + * **Renewed Migration Lease & Serving Registration:** `BigtableCatalogMigrations::lock` creates `__extenddb_catalog__` if absent (during `init`), acquires `lock:catalog_migrations` (60 s lease renewed every 15 s on a background task with a 25 s safety margin before every step), and calls `wait_for_servers` (`server_registration:*`) before running migrations. `BigtableRuntimeHooks::serving_registrar` exposes the active `ServingRegistration` (`server_registration:`) and `register_and_check_as` verifies `Runner::status` is `Current` (or `AheadCompatible`) at `serve` startup (refusing `Uninitialized`, `Behind`, `AheadIncompatible`, `NeedsAttention`, `Changed`, `WrittenByOlderRelease`, and `Locked`). +* **gRPC Error Classification (`data/client.rs`):** + * `Unavailable`, `DeadlineExceeded`, `Aborted`, `ResourceExhausted`, RPC timeouts, and transient I/O errors map to `StorageError::Transient` (retryable HTTP 503 `ServiceUnavailable`). + * `NotFound` (missing/deleted Bigtable table) maps to `StorageError::TableNotFound`. * Transport connection failures map to `StorageError::Connection`. - * `InvalidArgument` and `OutOfRange` map to `StorageError::Validation` (HTTP 400). - * `Unimplemented` maps to `StorageError::Unsupported` (HTTP 400). + * All other unexpected gRPC status codes—including `InvalidArgument`, `OutOfRange`, and `Unimplemented` on backend-constructed requests—map to `StorageError::Internal` (HTTP 500) rather than blaming the caller with HTTP 400. -### 7. Backup, Snapshot, Restore & Point-in-Time Recovery +### 7. Backup, Restore, Export, Point-in-Time Recovery & Table Size Statistics -* **Explicit `StorageError::Unsupported` Refusal (`backup_stubs.rs`):** Cloud Bigtable does not provide cross-table point-in-time snapshot reads on the data plane, and GCP-native Cloud Bigtable Backups operate asynchronously through the GCP Admin API rather than ExtendDB's logical/store-backed backup format. `BigtableEngine` implements `SnapshotEngine`, `LegacyBackupReader`, `BackupCatalog`, and `RestoreEngine` by returning `StorageError::Unsupported` on all user-facing backup, snapshot, and restore operations (`CreateBackup`, `DescribeBackup`, `ListBackups`, `DeleteBackup`, `RestoreTableFromBackup`), which `extenddb-engine` maps cleanly to `ValidationException` (HTTP 400) rather than `InternalServerError` (HTTP 500). Passive background `BackupReconciler` queries (`check_maintenance_claim`, `list_dead_restore_jobs`, `abandoned_creating_backups`, `list_backup_rows`) return empty `Ok` results so `extenddb serve` runs cleanly without log noise. -* **Point-in-Time Recovery (`#335`):** `DescribeContinuousBackups`, `UpdateContinuousBackups`, and `RestoreTableToPointInTime` are owned directly by `extenddb-engine`, consulting `BigtableEngine::describe_table` solely for table existence. +* **On-Demand Backups (`backup_stubs.rs`):** Cloud Bigtable does not provide cross-row point-in-time snapshot reads on the data plane. `CreateBackup` (`SnapshotEngine::open_table_snapshot` and `BackupCatalog::claim_backup`) is refused with `StorageError::Unsupported("CreateBackup is not supported by this storage backend")` (`ValidationException` HTTP 400), and the `extenddb serve` startup banner and logs state that `CreateBackup` is not supported on this backend. Read/delete/restore operations (`ListBackups`, `DescribeBackup`, `DeleteBackup`, `RestoreTableFromBackup`) answer as on an empty catalog: `ListBackups` returns `[]`, and `DescribeBackup`, `DeleteBackup`, and `RestoreTableFromBackup` return `BackupNotFoundException`. +* **`ExportTableToPointInTime`:** As on the other backends without cross-table historical MVCC snapshots, `ExportTableToPointInTime` executes as a synchronous paged `Scan` of the current live table with no point-in-time snapshot (`docs/differences-from-dynamodb.md`). +* **Point-in-Time Recovery (`#335`):** `DescribeContinuousBackups`, `UpdateContinuousBackups`, and `RestoreTableToPointInTime` are owned by `extenddb-engine`, consulting `BigtableEngine::describe_table` for table existence. +* **`DescribeTable` `ItemCount` and `TableSizeBytes`:** Reported as `0` and `0` (`MetadataEngine::refresh_table_size` is a no-op and no background table-size full-scan worker is spawned), documented in `docs/differences-from-dynamodb.md`. ### 8. Deliverables & Trait Conformance Matrix -Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-acceptance-criteria.md), `crates/storage-bigtable` implements the full ExtendDB `v1.0.0` backend surface as follows: +Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-acceptance-criteria.md), `crates/storage-bigtable` implements the ExtendDB `v1.0.0` backend trait surface at the **Experimental** tier as follows: | Trait / Subsystem | Classification | Status | Implementation Module | Notes | |---|---|---|---|---| -| `TableEngine` | Mandatory (Data/Control) | Implemented | `src/engine.rs` | CAS `CreateTable`/`UpdateTable` (online GSI `Create`/`Update`/`Delete` + backfill, `TableClass`, `WarmThroughput`, post-CAS `stream_lineage` transitions), `DeleteTable`, `DescribeTable`, `ListTables`, `table_key_info`, `index_info` | -| `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with cooperative intent resolution & versioned GSI shadows, `GetItem`, `Query`, `Scan` (including sparse sorted `scan_lsi`), `scan_key_in_segment`, incarnation-fenced CAS 2PC `TransactWriteItems`, double-read snapshot `TransactGetItems` | -| `VectorSearchEngine` | Optional (`as_vector_search`) | Opted out (`None`) | `src/engine.rs` | Engine rejects vector index DDL and `SearchVectors` upfront | -| `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | CAS resource tagging (`TagResource`/`UntagResource`/`ListTagsOfResource`) + 16-shard `__extenddb_ttl_index__` with `parse_ttl_epoch_secs` & millisecond-aligned bounds | -| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item (`sgl-*`), TTL, and 2PC streams; 4-shard CRC32 partition-key routing + contiguous `put_if_absent` sequence slots (`write_record_ordered`) + `stream_dedup` + `stream_lineage` disable/re-enable history | +| `TableEngine` | Mandatory (Data/Control) | Implemented | `src/engine.rs` | CAS `CreateTable`/`UpdateTable` (`PROVISIONED` default billing, leased online GSI `Create`/`Update`/`Delete` + visibility-fenced backfill, LSI shadow creation, pre-CAS `stream_lineage` shard creation & pre-close roll-forward), `DeleteTable`, `DescribeTable` (`ItemCount = 0`, `TableSizeBytes = 0`), `ListTables`, `table_key_info`, `index_info` | +| `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | Unified OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with statement/item-size checks, pre-commit digest-bounded GSI/LSI shadow key validation, chunked `<= 90,000`-mutation writes, durable `post-*` side-effect recovery, read-through `GetItem`, explicit-`is_index` `Query`/`Scan`, incarnation-fenced 2PC `TransactWriteItems`, double-read `TransactGetItems` | +| `VectorSearchEngine` | Optional (`as_vector_search`) | Opted out (`None`) | `src/engine.rs` | Engine capability gate rejects `VectorIndexes` DDL and `SearchVectors` | +| `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | CAS resource tagging + 16-shard `__extenddb_ttl_index__` with `ENABLING` base-table backfill (`create_ttl_index`), `drop_ttl_index`, and no-op `refresh_table_size` | +| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item (`sgl-*`), TTL, and 2PC streams; pre-created 4-shard `ShardMeta`, closed-shard write suppression, `O(1)` tail sequence lookup, contiguous `put_if_absent` slots, bounded `scan_str_range` reads & retention GC | | `WorkerStore` | Optional (Lifecycle) | Implemented | `src/engine.rs` | Inline `ACTIVE` table creation (`process_control_plane_transitions` no-op) | -| `SnapshotEngine`, `BackupCatalog`, `LegacyBackupReader`, `RestoreEngine` | Optional (Backup/Restore) | Explicit Refusal | `src/backup_stubs.rs` | User operations return `StorageError::Unsupported` (`ValidationException` HTTP 400); passive reconciler probes return empty `Ok` | -| `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM users/groups/roles/policies/boundaries/tags, STS sessions, CAS password-hash persistence, `SecretKeys` KEK/DEK paging & rotation | +| `SnapshotEngine`, `BackupCatalog`, `LegacyBackupReader`, `RestoreEngine` | Optional (Backup/Restore) | `CreateBackup` Refused / Empty Catalog | `src/backup_stubs.rs` | `CreateBackup` returns `StorageError::Unsupported` (`ValidationException`); `ListBackups` returns `[]`; `DescribeBackup`/`DeleteBackup`/`RestoreTableFromBackup` return `BackupNotFoundException` | +| `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM principals/policies/boundaries/tags, STS sessions, CAS password hashes, `SecretKeys` KEK/DEK paging & rotation | | `AuthorizationStore` | Mandatory (Authz) | Implemented | `src/catalog_store.rs` | User/group/role policies, permission boundaries, resource/principal tags, RFC 3339 `created_at` | -| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, CAS SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, table/index diagnostics | -| `CredentialStore` | Mandatory (`SigV4` Auth) | Implemented | `src/catalog_store.rs` | `AKIA*` + `ASIA*` `SecretKeys` decryption with `SecretRow` AAD, `ExpiredTokenException`, and inactive-key S-5 propagation | -| `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | Idempotent catalog/key/account/admin bootstrap (`catalog_key_present`, `data_connection_present`) and `destroy` cleanup | -| `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | Exhaustive `MigrationId` 1..=12 coverage, frozen `m0001_baseline.rs` checksum, `lock:catalog_migrations` lease | -| `OperationsEngine` | Mandatory (CLI) | Implemented | `src/operations.rs` | Connection URL parsing, identifier validation, sensitive-key redaction | -| `ServerRuntimeHooks` | Mandatory (Workers) | Implemented | `src/runtime_hooks.rs` | Spawns 6 lease-guarded workers (`ttl_worker` with metrics, 2PC `sweeper`, `gsi_reconciler`, 24h `stream_record_cleanup`, 10m `idempotency_token_cleanup`, 5m `table_size_refresh`) with `CancellationToken` shutdown | +| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, `catalog_version` lookup, CAS SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, catalog + `data_instance_id` diagnostics | +| `CredentialStore` | Mandatory (`SigV4` Auth) | Implemented | `src/catalog_store.rs` | `AKIAEXTENDDB*` + `ASIAEXTENDDB*` `SecretKeys` decryption with `SecretRow` AAD, `ExpiredTokenException`, inactive-key S-5 propagation, and redacted fail-closed `InternalServerError` on corrupt/unreadable secrets | +| `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | `create_catalog_db`, `init_target`, `hold`, `bootstrap_encryption_key` (`CATALOG_KEY_SETTING`), `bootstrap_default_account`, `bootstrap_admin_user`, and catalog-scoped `drop_databases` preserving non-ExtendDB tables | +| `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | `MigrationId::Baseline` (`Kind::Breaking`: `M0001CatalogBaseline` + `M0001DataBaseline`) + `2..=12` (`NotApplicable`), pinned SHA-256 baseline checksum, renewed `lock:catalog_migrations` lease, and `wait_for_servers` fence | +| `OperationsEngine` | Mandatory (CLI) | Implemented | `src/operations.rs` | Connection URL & `BIGTABLE_EMULATOR_HOST` parsing, identifier validation, sensitive-key redaction, runtime setting defaults | +| `ServerRuntimeHooks` | Mandatory (Serve & Workers) | Implemented | `src/runtime_hooks.rs` | `serving_registrar` (`server_registration:`), startup `Runner::status` check & `GetAppProfile` validation, emulator auth warning, and 5 leased workers (`ttl_worker`, `sweeper`, `CREATING`-only `gsi_worker`, 24h `stream_record_cleanup`, 10m `idempotency_token_cleanup`) | ## Testing Strategy 1. **Pure Unit Tests (`cargo test -p extenddb-storage-bigtable --lib`):** * Exact 38-digit decimal `N` encoding/decoding, zero normalization, and full-spectrum lexicographic order (`number.rs`). - * Row-key 4 KiB limit enforcement, partition length prefixing, raw terminal sort-key ordering, FDB escape-encoded GSI sort-key roundtrips, and LSI `LastEvaluatedKey` / `ExclusiveStartKey` validation (`row_key.rs`, `gsi.rs`, `ttl_key.rs`, `query_scan.rs`). - * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`, `next_millis_exclusive`), `parse_ttl_epoch_secs` decimal/zero/negative parsing, wall-clock-free intent filters, 3-case De Morgan `select_occ_predicate`, and incarnation-fenced `build_pending_incarnation_predicate` / ABA-safe `build_fenced_apply_predicate` `RowFilter` construction (`item_ops.rs`, `transact.rs`), RE2 metacharacter escaping and `monotonic_timestamp_after_micros` (`client.rs`), URL-encoded query parameter / TOML / `string_coerce` env-var config roundtripping (`config.rs`, `bootstrapper.rs`), 26-digit `u128` stream sequence numbers (`slot_sequence_number`) and TTL `UserIdentity` propagation (`streams.rs`), gRPC transient error mapping (`client.rs`), `check_released` migration checksum invariants (`migrations.rs`), and `StorageError::Unsupported` backup/snapshot/restore stubs (`backup_stubs.rs`). -2. **Live Bigtable Emulator Integration & Conformance Suite (`tests/emulator_integration.rs` against `cbtemulator`):** - * Catalog bootstrap, `BigtableCatalogMigrations` baseline run, table DDL lifecycle, and split catalog-vs-data instance (`data_instance_id != instance_id`) isolation across `BigtableBootstrapper` and background workers (`sweeper`, `ttl_worker`, `gsi_worker`). - * Guarded single-row CRUD, `ConditionExpression` evaluation, arithmetic `UpdateItem`, `removes_only` missing-item no-ops, and `#478` invalid-operand rejection on missing items. - * Deterministic OCC cell timestamps (`m:v * 1000` shared across all cells), post-`DeleteItem` `m:v` tombstone retention and rapid re-insert monotonicity, concurrent 10-way `UpdateItem` counter increments (zero lost updates), and 8-way conditional `PutItem` races (1 winner, 7 `ConditionFailed`). - * Multi-table 2PC `TransactWriteItems`, incarnation-fenced `try_commit_full` vs. `sweeper` race (`AllOrNothing2PCAtomicity`), post-`COMMITTED` expired intent protection (`BUG-03`), canonical sorted `[k1, k2]` vs. `[k2, k1]` locking, `ReturnValuesOnConditionCheckFailure::None` vs. `AllOld` fidelity, 4-vector `ClientRequestToken` idempotency (`IdempotencyAtMostOnce`), and concurrent `TransactGetItems` linearizable snapshot verification (`NoTornTransactGetSnapshot`). - * Fenced single-item stream emission (`INSERT`/`MODIFY`/`REMOVE`) across `SHARDS_PER_STREAM` (`4`) CRC32-routed shards, out-of-order Phase 2 contiguous slot ordering (`NoSkippedStreamSequenceOnShard`), 12-way concurrent identical-`event_id` deduplication (`write_record_ordered`), superseded `roll_forward` phantom suppression (`NoPhantomStreamRecord`), 36-way single-item stream contention with live tailing consumer, `ImportTable` `stream: None` bulk-import suppression, and full stream disable/re-enable lineage (`stream_lineage`). - * Exact decimal range queries, inverted `BETWEEN` range guards, reverse `Query` (`ScanIndexForward = false`) pagination, sparse sorted LSI `Scan` (`scan_lsi`) with deleted-`ExclusiveStartKey` resumption, online `UpdateTable` GSI `Create`/`Update`/`Delete` + `CREATING` read refusal + version-guarded GSI shadow mutations (`QuiescentGsiShadowConsistency`), `roll_forward` TTL indexing + `1000 -> future -> 1000 -> 1000.5` ABA / millisecond-aligned TTL bounds (`QuiescentTtlIndexCompleteness`), runtime GC helpers (`cleanup_expired_idempotency_tokens`, `cleanup_expired_stream_records`), and concurrent CAS `MetricsStore::insert_metrics` / `tag_resource`. - * Upstream shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, `key_conformance::run` (`switch`/`rotate`/`rewrap`/`reset`), and `BigtableCredentialStore` `AKIA*` + `ASIA*` (`ExpiredTokenException`) verification. -3. **End-to-End Conformance (`devtools/run-tests`) & TLA+ Formal Verification (`tlc2.TLC`):** - * Wire-level Rust and pytest conformance suites against an `extenddb` binary built with `--no-default-features --features bigtable`. - * Exhaustive breadth-first `tlc2.TLC` model checking across 2PC CAS commit/rollback atomicity (`AllOrNothing2PCAtomicity`), double-read `TransactGetItems` linearizability (`NoTornTransactGetSnapshot`), post-commit lease expiry protection (`NoActiveIntentBypassAfterCommit`), multi-RPC per-shard stream sequence visibility & deduplication (`NoSkippedStreamSequenceOnShard`), superseded roll-forward stream gating (`NoPhantomStreamRecord`), TTL index completeness (`QuiescentTtlIndexCompleteness`), 4-vector `ClientRequestToken` idempotency (`IdempotencyAtMostOnce`), and versioned GSI shadow consistency (`QuiescentGsiShadowConsistency`). + * Base-table 4 KiB row-key enforcement and exact sort-key query bounds (`build_base_range_for_query`), SHA-256 partition-digest + FDB escape-encoded GSI/LSI shadow key bounds (`<= 4,096` bytes even at 2,048-byte partition keys), multi-range GSI query bounds (`build_gsi_range_for_query`), `tomb:` GC key encoding disjoint from TTL shards `0..16`, and base/GSI/LSI `LastEvaluatedKey` + `ExclusiveStartKey` validation (`row_key.rs`, `gsi.rs`, `ttl_key.rs`, `query_scan.rs`). + * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`, `next_millis_exclusive`), single-`SetCell` 50,000-attribute shadow put sizing (`shadow_put_50k_attributes_fits_within_single_check_and_mutate_row`), `reclaim_version_only_row` conflict filter construction, `parse_ttl_epoch_secs` decimal/zero/negative parsing, wall-clock-free intent filters, incarnation-fenced 2PC predicates, startup `validate_app_profile_proto` routing checks (`admin.rs`), `BIGTABLE_EMULATOR_HOST` config resolution (`config.rs`), multi-frame `ReadRowsAssembler`, `x-goog-request-params` header formatting, and gRPC `Internal` vs. `Transient` error classification (`client.rs`), redacted fail-closed `lookup_credential` (`catalog_store.rs`), `CreateBackup` refusal vs. empty-catalog `ListBackups`/`DescribeBackup`/`DeleteBackup`/`RestoreTableFromBackup` (`backup_stubs.rs`), and `migration_table_covers_all_ids_and_refuses_additive` (`migrations.rs`). +2. **Live Bigtable Emulator Integration & Conformance Suite (`cargo test -p extenddb-storage-bigtable --features test-hooks --test emulator_integration -- --nocapture` against `cbtemulator`, gated via `EXTENDDB_TEST_BIGTABLE_REQUIRED=1`):** + * Catalog + split `data_instance_id` baseline migrations (`__extenddb_catalog__`, `__extenddb_data_ledger__`, `__extenddb_txn_log__`, `__extenddb_ttl_index__`), renewed `lock:catalog_migrations` + `ServingRegistration` fencing, and `drop_databases` preservation of foreign tables alongside base/GSI/LSI cleanup. + * Exact 5-item `[a, ab, b, ba, c]` base sort-key range queries, 2,048-byte partition-key GSI round-trips and pre-commit `> 4,096`-byte multi-RANGE rejection, GSI sharing the base table's key schema, and ordered LSI shadow-table `Query`/`Scan`/projections. + * Read-through `GetItem` and double-read `TransactGetItems` on `COMMITTED` unapplied intents, multi-table `roll_forward` when one table was deleted, `post-*` side-effect replay, version-only `tomb:` row reclamation after grace expiry, pre-CAS stream shard creation & pre-close roll-forward, `CREATING`-only leased GSI builds, and TTL `ENABLING -> ENABLED` pre-existing item backfill + preservation while `DISABLED`. + * Shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, and `key_conformance::run`. +3. **End-to-End Wire Conformance (`devtools/run-bigtable-tests`):** + * Wire-level Rust (`--rust`, `--rust-integration`) and Python (`--pytest`, `--comprehensive`) conformance suites executed via `devtools/run-tests --extenddb --backend bigtable` against an `extenddb` binary built with `--no-default-features --features bigtable` backed by `cbtemulator`. ## Alternatives Considered -* **Server-Assigned Cell Timestamps (`timestamp_micros: -1`):** Simpler to construct, but risks torn rows under `MaxNumVersions(1)` when two writers or recovery sweeps touch the same row in a narrow window or under clock skew. Rejected in favor of deterministic OCC-derived millisecond-aligned timestamps (`occ_version * 1_000`). -* **Unfenced Trailing Stream Writes on Single-Item Operations:** Lower write amplification (1 RPC instead of coordinator log + fenced apply), but loses stream records if the process crashes after the base-row mutation lands. Rejected because [RFC-0003](0003-backend-acceptance-criteria.md) §5.1 requires strict atomicity between data visibility and stream record durability. -* **Cloud Bigtable Native Change Streams (`ReadChangeStream`):** Rejected for the five reasons detailed in §3.B (lack of 2PC coordinator commit gating, missing pre-image `StreamViewType` reconstruction, dynamic tablet-split continuations incompatible with DynamoDB `ShardIterator` / `u128` `SequenceNumber`s, missing TTL `Service` `UserIdentity`, and lack of `cbtemulator` support). -* **Unprotected Single-Row Writes / Full-Table Scan TTL / Length-Prefixed Sort Keys:** Rejected due to dirty-write isolation violations, $O(N)$ scan cost at scale, and lexicographic sort inversion respectively. -* **Cloud Spanner Backend:** Provides native multi-row serializable transactions without application-layer 2PC, and remains a viable separate backend candidate for relational/Spanner-invested GCP environments. +* **Server-Assigned Cell Timestamps (`timestamp_micros: -1`):** Risks torn rows under `MaxNumVersions(1)` when writers or recovery sweeps touch the same row in a narrow window or under clock skew. Rejected in favor of deterministic OCC-derived millisecond-aligned timestamps (`occ_version * 1_000`). +* **In-Memory Base-Partition Sorting for LSIs:** Scanning the entire base partition and sorting in Rust memory breaks at scale on wide partitions and duplicates query/pagination paths. Rejected in favor of ordered `_l<8hex>` LSI shadow tables using the same digest-bounded key encoding and synchronous write-path maintenance. +* **Periodic Full-Table `refresh_table_size` Scans:** Scanning every row of every table every 5 minutes turns idle tables into continuous background read load. Rejected in favor of reporting `ItemCount = 0` and `TableSizeBytes = 0` on `DescribeTable` and documenting the difference. +* **Cloud Bigtable Native Change Streams (`ReadChangeStream`):** Rejected for the five reasons in §3.B. +* **Cloud Spanner Backend:** Provides native multi-row serializable transactions without application-layer 2PC, and remains a viable separate backend candidate for Spanner-invested GCP environments. --- @@ -276,6 +259,6 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept Copyright 2026 ExtendDB contributors. Licensed under the Apache License, Version 2.0. See [LICENSE](../../LICENSE) for the full text. -This software is provided "as is" without warranty of any kind. ExtendDB is not -affiliated with, endorsed by, or sponsored by Amazon Web Services. "DynamoDB" is -a trademark of Amazon.com, Inc. +This software is provided "as is" without warranty of any kind. ExtendDB is an open +source project maintained by AWS. It is not Amazon DynamoDB or an AWS service. +"DynamoDB" is a trademark of Amazon.com, Inc. or its affiliates. From 4943a000e7d2b933ea05e0f314ba7261e28fd469 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Tue, 24 Nov 2026 01:58:03 +0000 Subject: [PATCH 09/11] docs(rfc): sync Bigtable reverse-scan header, admin routing, and chunk/recovery invariants - Document bigtable-features: CAE= reverse-scan metadata, URL-encoded AdminClient x-goog-request-params routing metadata, and AlreadyExists-gated missing-family ModifyColumnFamilies reconciliation. - Sync multi-chunk CheckAndMutateRow stage fencing, (m:v, m:chunk) shadow preemption, bounded inline post-commit side effects with t:base_guard recovery, wall-clock-gated tombstone reclamation, CAS-verified stream shard sealing, and slow-write GSI drift repair in docs/rfcs/0000-bigtable-backend.md. --- docs/rfcs/0000-bigtable-backend.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index b0d0a4013..8f024a105 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -126,8 +126,8 @@ To prevent torn rows under `MaxNumVersions(1)` while satisfying Cloud Bigtable's * `next_occ_version(Some(prev)) = prev.max(now_ms) + 1` * `version_to_timestamp_micros(v) = (v * 1_000) as i64` * `next_millis_exclusive(ts_micros) = ((ts_micros / 1_000) + 1) * 1_000` -* **Single-`SetCell` Shadow Puts & 100,000-Mutation RPC Bound (`MAX_MUTATIONS_PER_RPC = 90_000`):** Because family `d` uses `MaxNumVersions(1)` and every reader applies `CellsPerColumnLimitFilter(1)`, `ItemOps::build_shadow_put_mutations` emits a single `SetCell` per retained projected attribute (`ts_micros >= max_d_ts`) plus `DeleteFromColumn` **only** for removed attributes—keeping a 50,000-attribute `ALL`-projected GSI/LSI shadow write at `50,002` mutations inside a single atomic `CheckAndMutateRow` RPC. As an additional safety bound, `put_cas`, `apply_shadow_version_cas`, `apply_fenced_mutation`, and `mutate_cells` cap the atomic `CheckAndMutateRow` batch (`m:v` + initial cells) to `<= 90,000` mutations and apply any overflow cells in bounded `90,000`-mutation `MutateRow` chunks at the identical `occ_ts`. -* **Version-Guarded Shadow Updates & Durable Post-Commit Side-Effect Recovery:** GSI and LSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, `ItemOps::delete_shadow_orphan_if_unchanged`—sharing `apply_shadow_version_cas`) execute `CheckAndMutateRow` predicated on exact `m:v == cur_ver` (or missing `m:v`) and reject (`Ok(false)`) any delayed writer (`new_version < cur_ver`). On single-item OCC writes (`execute_single_item_write`), shadow keys are pre-computed **before** `put_cas`. Once `put_cas` or `delete_cas` commits the base row, any transient error on GSI/LSI shadow maintenance or TTL index maintenance is retried via `BigtableClient` and, if still failing, recorded as a `COMMITTED` `post-` side-effect entry in `__extenddb_txn_log__` (`TxnCoordinator::write_committed_side_effects`) for `sweeper` replay while logging a warning and returning success to the caller—preventing both silent stale index entries and post-commit 503 double-execution on non-idempotent updates (`SET a = a + 1`). +* **Single-`SetCell` Shadow Puts & Intent-Fenced 100,000-Mutation Chunking (`MAX_MUTATIONS_PER_RPC = 90_000`):** Because family `d` uses `MaxNumVersions(1)` and every reader applies `CellsPerColumnLimitFilter(1)`, `ItemOps::build_shadow_put_mutations` emits a single `SetCell` per retained projected attribute (`ts_micros >= max_d_ts`) plus `DeleteFromColumn` **only** for removed attributes—keeping a 50,000-attribute `ALL`-projected GSI/LSI shadow write at `50,002` mutations inside a single atomic `CheckAndMutateRow` RPC. Whenever a write exceeds `MAX_MUTATIONS_PER_RPC` (`90_000`), single-item `PutItem` and `UpdateItem` writes route through the coordinator-fenced `sgl-*` commit path so `GetItem` and `TransactGetItems` resolve the full committed item from `__extenddb_txn_log__` (with `RowSnapshot.in_progress_chunk` retry guards preventing torn mid-chunk reads), while `apply_fenced_mutation`, `put_cas`, and `apply_shadow_version_cas` execute progressive single-`Condition` `CheckAndMutateRow` batches fenced on `m:intent:*` (`attr:`) or `m:chunk` stage markers and `m:v`—placing primary-key attributes in the initial chunk and advancing `m:v` only on the final chunk. +* **Version-Guarded Shadow Updates & Durable Post-Commit Side-Effect Recovery:** GSI and LSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, `ItemOps::delete_shadow_orphan_if_unchanged`—sharing `apply_shadow_version_cas`, which predicates on `(m:v, m:chunk)` so higher-version writes and deletes immediately preempt incomplete lower-version shadow chunks) execute `CheckAndMutateRow` predicated on exact `(m:v, m:chunk)` state and reject (`Ok(false)`) any delayed writer (`new_version < cur_ver`). On single-item OCC writes (`execute_single_item_write`), shadow keys are pre-computed **before** `put_cas`. Once `put_cas` or `delete_cas` commits the base row, inline GSI/LSI shadow and TTL maintenance runs under a bounded post-commit timeout (`inline_side_effect_budget`) strictly below the tombstone grace horizon and, on timeout or transient error, records a `COMMITTED` `post-` side-effect entry anchored to `(data_table, row_key, base_version)` (`t:base_guard` via `TxnCoordinator::write_committed_side_effects_guarded`) in `__extenddb_txn_log__` for `sweeper` replay while logging a warning and returning success to the caller—preventing both silent stale index entries and post-commit 503 double-execution on non-idempotent updates (`SET a = a + 1`). * **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`, cooperatively resolving `COMMITTED` or expired `PENDING` intents, returning `StorageError::TransactionConflict` if a live multi-item 2PC `txn-*` holds the row ([RFC-0003](0003-backend-acceptance-criteria.md) §4.3), or retrying OCC mismatches with jittered backoff. #### E. Cloud Bigtable App Profile & Single-Cluster Routing Validation @@ -135,7 +135,7 @@ Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on #### F. Garbage Collection (GC), Version-Only Tombstone Reclamation & Recovery Sweeper * **Column Family GC:** `d` and `m` on data/GSI/LSI tables, `c` on `__extenddb_catalog__` and `__extenddb_data_ledger__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. -* **Bounded Tombstone Reclamation (`tomb:` Queue & `reclaim_version_only_row`):** Deleting an item leaves a version-only `m:v` tombstone row to prevent rapid `Put -> Delete -> Put` timestamp regression, and enqueues a fixed 45-byte GC marker `b"tomb:" || ready_ms_be8 || sha256(table_name || 0x00 || row_key)` (`0x74 >= 16`, disjoint from TTL shards `0x00..=0x0F` and immune to 4 KiB key limits) with an `intent_timeout_secs` (`60 s` default) grace window in `__extenddb_ttl_index__`. Once `now_ms >= ready_ms`, `sweeper` calls `ItemOps::reclaim_version_only_row(row_key, expected_version)`, which executes an atomic `CheckAndMutateRow` (`DeleteFromRow` in `false_mutations`) that reclaims the physical Bigtable row **if and only if** zero `m:intent:*` cells exist, `m:v == expected_version`, and zero `d:*` cells exist—never deleting a concurrently re-inserted live item. +* **Bounded Tombstone Reclamation (`tomb:` Queue & `reclaim_version_only_row`):** Deleting an item leaves a version-only `m:v` tombstone row to prevent rapid `Put -> Delete -> Put` timestamp regression, and enqueues a fixed 45-byte GC marker `b"tomb:" || ready_ms_be8 || sha256(table_name || 0x00 || row_key)` (`0x74 >= 16`, disjoint from TTL shards `0x00..=0x0F` and immune to 4 KiB key limits) anchored at `expected_version.saturating_add(1).max(now_ms) + grace_ms` (`intent_timeout_secs`, `60 s` default) in `__extenddb_ttl_index__`. Once `sweep_txn_log` finishes cleanly (with `post-*` replays skipping stale shadow `Put` and TTL `new_expiry` writes whenever the base row has moved past `t:base_guard.base_version` while still applying prior `Delete` cleanups) and `now_ms >= ready_ms` with `now_millis() > expected_version`, `sweeper` calls `ItemOps::reclaim_version_only_row(row_key, expected_version)`, which enforces `now_millis() > expected_version` and executes an atomic `CheckAndMutateRow` (`DeleteFromRow` in `false_mutations`) that reclaims the physical Bigtable row **if and only if** zero `m:intent:*` cells exist, zero `m:chunk` cells exist, `m:v == expected_version`, and zero `d:*` cells exist—never deleting a concurrently re-inserted live item or allowing subsequent `next_occ_version(None)` inserts to regress below a surviving shadow version. * **2PC & Side-Effect Recovery Sweeper (`sweeper.rs`):** Runs under a renewed distributed catalog lease (`lock:sweeper`), CAS-aborting timed-out `PENDING` coordinators, rolling forward `COMMITTED` transactions and `post-*` side-effect records, persisting `idem:` tokens, and draining due `b"tomb:"` tombstone GC entries. ### 3. Unified Fenced DynamoDB Streams Architecture & Stream Lineage @@ -143,7 +143,7 @@ Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on #### A. Write-Ahead Fenced Stream Emission, Pre-CAS Shard Creation & Stream Lineage Whenever a caller supplies `stream: Some(&StreamCapture)` on a stream-enabled table, single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through the `__extenddb_txn_log__` commit fence (`commit_fenced_single_item_write` + `roll_forward`), while `stream: None` writes (`ImportTable` bulk imports) suppress stream emission: -1. **Pre-CAS Shard Provisioning & Pre-Close Roll-Forward (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and pre-creates `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) at `stream_shard:` **before** publishing `latest_stream_label` in `table_meta` via `Catalog::mutate_json_cas` (cleaning up orphaned pre-created shards if CAS loses a race). Conversely, disabling a stream calls `roll_forward_committed_txns_for_table` **before** closing shards (`close_shards_by_id` using `O(1)` tail-probing `latest_sequence_for_shard` rather than scanning every historical record), and `streams::write_record_ordered` checks `ending_sequence_number.is_some()` and returns `Ok(None)` without writing past a closed shard's `EndingSequenceNumber`. +1. **Pre-CAS Shard Provisioning & Pre-Close Roll-Forward (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and pre-creates `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) at `stream_shard:` **before** publishing `latest_stream_label` in `table_meta` via `Catalog::mutate_json_cas` (cleaning up orphaned pre-created shards if CAS loses a race). Conversely, disabling a stream calls `roll_forward_committed_txns_for_table` **before** closing shards (`close_shards_by_id` serializing under `shard_local_mutex` and using `O(1)` tail-probing `latest_sequence_for_shard` rather than scanning every historical record), `streams::write_record_ordered` persists `stream_dedup` markers before atomically verifying `ShardMeta` remains open via `advance_shard_cursor_if_open` (`Catalog::mutate_json_cas`—deleting any unexposed record/dedup slot `> ending_sequence_number` and returning `Ok(None)`), and `StreamEngine::get_stream_records` clamps both `scan_str_range` bounds and returned records at `ending_sequence_number`. 2. **Contention-Resilient Single-Item Serialization (`sgl-` Prefix):** Single-item fenced writes serialize same-process contention per `(data_table, row_key)` via an async mutex and tag their coordinator IDs with `sgl-` so cross-process single-item contenders wait and retry cooperatively rather than aborting unconditional writes with `TransactionConflictException`. 3. **Contiguous Per-Shard Sequence Slot Append & Bounded Range Reads (`streams.rs`):** Phase 1 constructs each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER`, its `ParticipantRow`, and `:` `dedup_key`. During Phase 2 (`streams::write_record_ordered`), the writer reads the existing `ShardMeta` (no clock-based sequence fallback), checks `stream_dedup::`, formats `slot_seq = slot_sequence_number(shard_id, slot)`, claims `stream_record::` via `Catalog::put_if_absent` (setting `dynamodb.size_bytes` via `item_size_bytes`), persists `stream_dedup`, and advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS. `StreamEngine::get_stream_records`, `cleanup_expired_stream_records`, and `cleanup_expired_idempotency_tokens` all page through `Catalog::scan_str_range` with server-side `StartKeyOpen`/`StartKeyClosed`, `EndKeyOpen`, and bounded `rows_limit` rather than prefix-scanning entire shards or tables into memory. @@ -164,9 +164,9 @@ Cloud Bigtable native Change Streams (`ReadChangeStream`) were evaluated and rej ### 5. Query, Scan, LSI Shadow Tables & Online GSI Lifecycle -* **Exact Sort-Key Bounds, Explicit `is_index` Routing & `cbtemulator` Compatibility (`query_scan.rs`):** `BigtableEngine` passes an explicit `is_index: bool` flag (`index_name.is_some()`) into `QueryScan::query`, `QueryScan::scan`, and `QueryScan::key_belongs_to_segment`, ensuring base tables use `build_base_range_for_query` while both GSIs (even when sharing the base table's key schema) and LSIs use `build_gsi_range_for_query` over their respective `_g<8hex>` and `_l<8hex>` shadow tables. Both paths validate `ExclusiveStartKey` schema, scalar types, and partition boundaries, merge `ExclusiveStartKey` into active sort-key bounds, clamp bounds to 4,096 bytes, fetch `limit + 1` matching items for exact `LastEvaluatedKey` emission, and fall back cleanly when `cbtemulator` rejects `ReadRowsRequest { reversed: true }` with `UNIMPLEMENTED`. +* **Exact Sort-Key Bounds, Explicit `is_index` Routing & Reverse-Scan Compatibility (`query_scan.rs`):** `BigtableEngine` passes an explicit `is_index: bool` flag (`index_name.is_some()`) into `QueryScan::query`, `QueryScan::scan`, and `QueryScan::key_belongs_to_segment`, ensuring base tables use `build_base_range_for_query` while both GSIs (even when sharing the base table's key schema) and LSIs use `build_gsi_range_for_query` over their respective `_g<8hex>` and `_l<8hex>` shadow tables. Both paths validate `ExclusiveStartKey` schema, scalar types, and partition boundaries, merge `ExclusiveStartKey` into active sort-key bounds, clamp bounds to 4,096 bytes, fetch `limit + 1` matching items for exact `LastEvaluatedKey` emission, execute native server-side `ReadRowsRequest { reversed: true }` against Cloud Bigtable (enabled via `bigtable-features: CAE=`), and fall back cleanly when `cbtemulator` rejects `reversed: true` with `UNIMPLEMENTED`. * **Online `UpdateTable` GSI Build, Cache Visibility Fence & `CREATING`-Only `gsi_worker` (`engine.rs`, `gsi_worker.rs`):** - * Table metadata is cached for `1 s` (`METADATA_CACHE_TTL`). Any write taking `>= 250 ms` (`FAST_WRITE_BUDGET`) re-reads uncached `table_meta` post-commit (`repair_slow_write_schema_drift`) and repairs any GSI or TTL index added concurrently. + * Table metadata is cached for `1 s` (`METADATA_CACHE_TTL`). Any write taking `>= 250 ms` (`FAST_WRITE_BUDGET`) re-reads uncached `table_meta` post-commit (`repair_slow_write_schema_drift`) and repairs any GSI or TTL index added concurrently—deleting stale shadow keys only when `old_rk != new_rk`, anchoring versions to `live_ver.unwrap_or(committed_version)` rather than synthesizing versions on absent rows, bounding inline repair RPCs with `post-*` recovery fallback, and re-verifying the base row after GSI insertion to retire entries superseded before `SCHEMA_VISIBILITY_FENCE`. * When `UpdateTable` creates a GSI (`index_status = "CREATING"`), `run_gsi_backfill` acquires a renewed per-index catalog lease `lock:gsi_build::` (so `gsi_worker` never races a live build or rolls back a sibling GSI), waits `1.35 s` (`await_schema_visibility_fence` > `1 s + 250 ms`), rolls forward `COMMITTED` transactions for the table, backfills projected rows via version-guarded `put_shadow_versioned`, and promotes the GSI `"CREATING" -> "ACTIVE"` via CAS (rolling back **only** that GSI if still `"CREATING"` on failure). * `gsi_worker` runs **only** on tables that currently have at least one `"CREATING"` GSI—resuming interrupted builds under the same `lock:gsi_build::` lease without scanning `ACTIVE` tables every cycle. @@ -188,7 +188,7 @@ ttl_scan_cadence_secs = 60 gsi_reconcile_cadence_secs = 300 ``` -* **Resilient Direct `tonic` Pool, Multi-Frame `ReadRowsAssembler`, `64 MiB` gRPC Limits & Split-Instance Isolation (`data/client.rs`, `config.rs`):** `BigtableClient::connect` builds a multi-channel `tonic::transport::Channel::balance_channel` pool directly over `googleapis_tonic_google_bigtable_v2` configured with `64 MiB` max encoding/decoding message sizes (`MAX_GRPC_MESSAGE_BYTES`), a stateful multi-frame `ReadRowsAssembler` (reassembling multi-megabyte cells and multi-cell rows split across consecutive `ReadRowsResponse` stream messages), `x-goog-request-params` regional routing metadata, OAuth2 bearer token injection via `gcp_auth` (skipped with a `BigtableClient::log_startup_endpoint` `tracing::warn!` warning when `emulator_host` or `BIGTABLE_EMULATOR_HOST` is resolved via `BigtableStorageConfig::resolve_emulator_host`, or logged via `tracing::info!` when connecting to Cloud Bigtable over TLS), and automatic pool replacement + bounded retry on HTTP/2 `GoAway` (`ENHANCE_YOUR_CALM`) or transport resets across `read_rows`, `mutate_row`, stream-draining `mutate_rows`, and idempotent/pre-execution `check_and_mutate_row` errors. +* **Resilient Direct `tonic` Pool, Multi-Frame `ReadRowsAssembler`, `64 MiB` gRPC Limits & Split-Instance Isolation (`data/client.rs`, `data/admin.rs`, `config.rs`):** `BigtableClient::connect` builds a multi-channel `tonic::transport::Channel::balance_channel` pool directly over `googleapis_tonic_google_bigtable_v2` configured with `64 MiB` max encoding/decoding message sizes (`MAX_GRPC_MESSAGE_BYTES`), a stateful multi-frame `ReadRowsAssembler` (reassembling multi-megabyte cells and multi-cell rows split across consecutive `ReadRowsResponse` stream messages), URL-encoded `x-goog-request-params` regional routing metadata across both data-plane `BigtableClient` and control-plane `AdminClient` RPCs (with `AdminClient::create_table` invoking `ensure_families` strictly on `AlreadyExists` and adding only missing column families after `GetTable(SchemaView)`), `bigtable-features: CAE=` (`FeatureFlags { reverse_scans: true }`) metadata enabling server-side reverse `ReadRows`, OAuth2 bearer token injection via `gcp_auth` (skipped with a `BigtableClient::log_startup_endpoint` `tracing::warn!` warning when `emulator_host` or `BIGTABLE_EMULATOR_HOST` is resolved via `BigtableStorageConfig::resolve_emulator_host`, or logged via `tracing::info!` when connecting to Cloud Bigtable over TLS), and automatic pool replacement + bounded retry on HTTP/2 `GoAway` (`ENHANCE_YOUR_CALM`) or transport resets across `read_rows`, `mutate_row`, stream-draining `mutate_rows`, and idempotent/pre-execution `check_and_mutate_row` errors. * **Compile-Time Backend Registration & Shared Storage Helpers (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` while exposing the mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`, linted in `.github/workflows/clippy.yml`). Shared IAM key/policy helpers (`generate_access_key_id`, `generate_secret_key`, `generate_session_key_id`, `generate_session_token`, `self_service_policy`) and `string_coerce::u64` live in `extenddb-storage` (reused across all five backends and `crates/server`), and `create_backup_unsupported("bigtable")` wires the startup banner/log notice in `crates/{engine,server,app}`. * **At-Rest Secret Encryption & Fail-Closed Auth Redaction (`catalog_store.rs`):** `BigtableCatalogStore` and `BigtableCredentialStore` encrypt and decrypt `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions via `SecretKeys` (`CATALOG_KEY_SETTING = "catalog_encryption_key"`). Any corrupt catalog row, missing key ring, or AEAD decryption failure in `lookup_credential` logs details server-side via `tracing::error!` and returns a redacted `DynamoDbError::InternalServerError("Internal error during authentication")` without leaking internal identifiers. No unauthenticated development admin bypass exists in the crate. * **`ADR-0023` / `ADR-0029` Baseline Migrations, Renewed Lock & `ServingRegistrar` (`m0001_baseline.rs`, `migrations.rs`, `runtime_hooks.rs`):** From 6dbfb7982165369d0fe02622fd7141c2a33a3773 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Wed, 25 Nov 2026 00:01:30 +0000 Subject: [PATCH 10/11] docs(rfc): align Bigtable RFC symbols, fencing rules, and key/read-through protocols MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Align §1.B `gsi::hash_partition_values` framing (`[count:u32BE:4]([tag_i:1][len_i:4][bytes_i]){1..4}`), §4.A `<= 4,096`-byte `[0x44][SHA-256:32]` + `tv1:` TTL index keys, and §1.A monotonic per-row catalog overwrites (`get_raw_cell_bytes_with_ts` / `compare_and_swap_raw_after`) and `O(1)` `table_id_index:` lookups with `crates/storage-bigtable`. - Sync §2.A/§2.C/§2.D/§2.F pre-execution CAS retry rules and `t:open_nonce` coordinator disambiguation (`DataHandle::check_and_mutate_row_idempotent_with_attempt`), `GetItem`/`Query`/`Scan` committed-intent read-through (read-committed across rows on `Query`/`Scan`), `ensure_lsi_read_after_write` pre-read flush + roll-forward, buffered/backoff `post-*` recovery, and per-row non-starving `b"tomb:"` tombstone GC (`blocked_tables` + `unsettled_committed_rows`). - Sync §5 online GSI build symbols (`TableEngine::update_table` and `gsi_worker::recover_creating_gsi`), §6/§8 `ADR-0023` migration lease fencing (`resolve_status` raw row-key foreign-catalog check, `TimestampRangeFilter`-guarded `renew_lock`, lease-wrapped `LockedStores::management()`), `1h` `stream_record_cleanup` cadence (`24h` retention), `AdminError::Rpc { context, status }`, `EffectiveStore::Configured` backup banner behavior, and `devtools/check-bigtable-catalog-lock`. --- docs/rfcs/0000-bigtable-backend.md | 63 +++++++++++++++--------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index 8f024a105..496a84e27 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -7,7 +7,7 @@ ## Summary -This RFC defines the design and implementation of an **Experimental** Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0` (evaluation tier per `README.md`, not for production use). It addresses single-row concurrency control and cooperative read-through / optimistic double-read snapshot validation for `GetItem` and `TransactGetItems`, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection and Cloud Bigtable's millisecond granularity, incarnation-fenced two-phase commit (2PC) apply and deleted-table recovery, write-ahead fenced DynamoDB Streams emission with pre-created shard metadata (`stream_lineage`) and contiguous per-shard sequence slots, SHA-256 partition-digest and FoundationDB tuple escape-encoded Global Secondary Index (GSI) and Local Secondary Index (LSI) shadow tables bounded within Bigtable's 4 KiB row-key limit, sharded Time-to-Live (TTL) indexing with `ENABLING` base-table backfill and version-only tombstone reclamation, `SecretKeys` KEK/DEK envelope encryption and `encryption-key` lifecycle commands, `ADR-0023` renewed migration leases and `ServingRegistrar` fencing, `ADR-0029` catalog + data-instance baseline migrations, gRPC HTTP/2 pool resilience and internal-fault error classification, startup single-cluster transactional app-profile verification, and Google Cloud Platform (GCP) authentication. +This RFC defines the design and implementation of an **Experimental** Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.0.0` (evaluation tier per `README.md`, not for production use). It addresses single-row concurrency control, cooperative `COMMITTED`-intent resolution across `GetItem`, `Query`, `Scan` (read-committed across rows), and optimistic double-read snapshot validation for `TransactGetItems`, deterministic Optimistic Concurrency Control (OCC) cell timestamps compatible with `MaxNumVersions(1)` garbage collection and Cloud Bigtable's millisecond granularity, incarnation-fenced two-phase commit (2PC) apply and deleted-table recovery, write-ahead fenced DynamoDB Streams emission with pre-created shard metadata (`stream_lineage`) and contiguous per-shard sequence slots, SHA-256 partition-digest and FoundationDB tuple escape-encoded Global Secondary Index (GSI) and Local Secondary Index (LSI) shadow tables bounded within Bigtable's 4 KiB row-key limit, sharded Time-to-Live (TTL) indexing with `<= 4,096`-byte `table_id`-tagged entries, `ENABLING` base-table backfill, and per-table version-only tombstone reclamation, `SecretKeys` KEK/DEK envelope encryption and lease-guarded `encryption-key` lifecycle commands, `ADR-0023` renewed migration leases and `ServingRegistrar` fencing, `ADR-0029` catalog + data-instance baseline migrations, gRPC HTTP/2 pool resilience and internal-fault error classification, startup single-cluster transactional app-profile verification, and Google Cloud Platform (GCP) authentication. ## Motivation @@ -26,12 +26,12 @@ Mapping DynamoDB's API contract onto Cloud Bigtable's wide-column, single-row-at ### 1. Table Mapping & Key Encoding #### A. Table Structure & Naming -* **Catalog & Stream Ledger (`__extenddb_catalog__` on `instance_id`):** Stores system settings (`setting:catalog_id`, `setting:catalog_version`, `setting:catalog_encryption_key`, `setting:encryption_key_ring`, `setting:default_account_id`), accounts, admins, IAM users/groups/roles/policies/boundaries/tags, `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:` + `version:catalog`), renewed migration & worker leases (`lock:`), live server registrations (`server_registration:`), stream shard lineage/cursor rows (`stream_shard:` carrying `next_seq_num` and `last_sequence_number`), per-event stream deduplication markers (`stream_dedup::`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). +* **Catalog & Stream Ledger (`__extenddb_catalog__` on `instance_id`):** Stores system settings (`setting:catalog_id`, `setting:catalog_version`, `setting:catalog_encryption_key`, `setting:encryption_key_ring`, `setting:default_account_id`), accounts, admins, table descriptions (`table_meta::`) and `O(1)` reverse table-ID index rows (`table_id_index:`), IAM users/groups/roles/policies/boundaries/tags, `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions (`iam_session:` + secondary index `iam_session_ak:`), login rate-limit windows (`failed_login:\x00:`), minute-bucketed operational metrics (`metric::`), idempotency tokens (`idem::`), catalog migration ledger rows (`migration_ledger:catalog:` + `version:catalog`), renewed migration & worker leases (`lock:`), live server registrations (`server_registration:`), stream shard lineage/cursor rows (`stream_shard:` carrying `next_seq_num` and `last_sequence_number`), per-event stream deduplication markers (`stream_dedup::`), and stream records (`stream_record::`) in column family `c` (qualifier `j`). Because the four system table names are fixed, one Bigtable instance (or `instance_id` / `data_instance_id` pair) holds one ExtendDB catalog. * **Data Migration Ledger (`__extenddb_data_ledger__` on `effective_data_instance_id`):** Stores the `StoreKind::Data` baseline ledger rows (`migration_ledger:data:0001`) in column family `c` (qualifier `j`) so separate `data_instance_id` deployments track data-store initialization independently of `__extenddb_catalog__`. -* **Coordinator Transaction & Side-Effect Log (`__extenddb_txn_log__` on `effective_data_instance_id`):** Stores coordinator state (`t:state`), incarnation start timestamp (`t:started_at`), canonical sorted participant list (`t:participants`), pre-computed mutations (`t:mutations`), pre-generated stream records (`t:stream_records`), logged TTL index transitions (`t:ttl_mutations`), and `ClientRequestToken` metadata (`t:token_meta`) in column family `t`—covering 2PC transactions (`txn-*`), stream-fenced single-item writes (`sgl-*`), and post-commit side-effect recovery records (`post-*`). -* **Sharded TTL Index & Tombstone GC Queue (`__extenddb_ttl_index__` on `effective_data_instance_id`):** Stores OCC-timestamped, millisecond-aligned expiration index entries across 16 hash shards (`0x00..=0x0F`) and disjoint `b"tomb:"` (`0x74`) version-only tombstone reclamation entries in column family `d`. -* **Data Tables (`t`):** Each DynamoDB table maps to a dedicated Bigtable table named `t` followed by the first 16 lowercase hex characters of the table's unique `table_id` UUID (17 characters total). Deriving physical table names from `table_id` rather than `table_name` guarantees clean isolation across accounts and across `DeleteTable` + `CreateTable` name reuse ([RFC-0003](0003-backend-acceptance-criteria.md) §8.2). Data attributes live in column family `d` (one qualifier per top-level attribute); OCC row versions (`m:v`) and 2PC intent locks (`m:intent:`) live in column family `m`; column family `t` is reserved. -* **GSI & LSI Shadow Tables (`t_g` and `t_l`):** Each GSI (`_g`) and each LSI (`_l`) maps to an ordered shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit), storing projected item attributes (plus full HASH key attributes for defense-in-depth collision filtering) in column family `d` and base-row OCC version guards (`m:v`) in column family `m`. Storing LSIs in dedicated ordered shadow tables avoids loading entire partitions into memory on `Query`/`Scan` while preserving synchronous `ConsistentRead = true` maintenance on the write path. +* **Coordinator Transaction & Side-Effect Log (`__extenddb_txn_log__` on `effective_data_instance_id`):** Stores coordinator state (`t:state`), incarnation start timestamp (`t:started_at`), per-attempt open disambiguation nonce (`t:open_nonce`), canonical sorted participant list (`t:participants`), pre-computed mutations (`t:mutations`), pre-generated stream records (`t:stream_records`), logged TTL index transitions (`t:ttl_mutations`), `ClientRequestToken` metadata (`t:token_meta`), and post-commit base-version guards (`t:base_guard`) in column family `t`—covering 2PC transactions (`txn-*`), stream/chunk-fenced single-item writes (`sgl-*`), and post-commit side-effect recovery records (`post-*`). +* **Sharded TTL Index & Tombstone GC Queue (`__extenddb_ttl_index__` on `effective_data_instance_id`):** Stores OCC-timestamped, millisecond-aligned, digest-bounded (`<= 4,096`-byte) expiration index entries (`tv1:[tid_len:u16BE][table_id][base_row_key]` cell values) across 16 hash shards (`0x00..=0x0F`) and disjoint `b"tomb:"` (`0x74`) version-only tombstone reclamation entries in column family `d`. +* **Data Tables (`t`):** Each DynamoDB table maps to a dedicated Bigtable table named `t` followed by the first 16 lowercase hex characters of the table's unique `table_id` UUID (17 characters total). Deriving physical table names from `table_id` rather than `table_name` guarantees clean isolation across accounts and across `DeleteTable` + `CreateTable` name reuse ([RFC-0003](0003-backend-acceptance-criteria.md) §8.2). Data attributes live in column family `d` (one qualifier per top-level attribute); OCC row versions (`m:v`), chunk progress markers (`m:chunk`), and 2PC intent locks (`m:intent:`) live in column family `m`; column family `t` is reserved. +* **GSI & LSI Shadow Tables (`t_g` and `t_l`):** Each GSI (`_g`) and each LSI (`_l`) maps to an ordered shadow Bigtable table where `idx_hash_8hex` is the 8-character hex FNV-1a hash of `index_name` (27 characters total, well within Cloud Bigtable's 50-character table-ID limit), storing projected item attributes (plus full HASH key attributes for defense-in-depth collision filtering) in column family `d` and base-row OCC version guards (`m:v`) plus chunk markers (`m:chunk`) in column family `m`. Storing LSIs in dedicated ordered shadow tables avoids loading entire partitions into memory on `Query`/`Scan` while preserving synchronous write-path maintenance (with `ensure_lsi_read_after_write` flushing any in-memory `pending_side_effect_recoveries` and rolling forward `COMMITTED` coordinator/`post-*` entries for the table before reading the LSI shadow table, and `sweeper` replaying any deferred recovery if Bigtable is transiently unreachable; see `docs/differences-from-dynamodb.md`). #### B. Exact Decimal, Digest-Bounded & Order-Preserving Key Encoding Cloud Bigtable sorts row keys by unsigned raw byte lexicographical order and enforces a **4 KiB (4,096-byte)** row-key limit, validated upfront in `row_key::encode_key` and `gsi::shadow_row_key_for_item` **before** any base-table `put_cas` or 2PC commit executes. @@ -58,14 +58,14 @@ Where `pk_tag` and `sk_tag` identify the DynamoDB scalar type (`0x53` for `S`, ` Base Key Tie-Breaker: [base_pk_tag:1] [escape_encoded(base_pk_bytes[..min(64)])] [0x00, 0x00|0x01] [SHA-256(base_pk):32] ([base_sk_tag:1] [base_sk_bytes])? ``` * **Bounded Size & Order-Preserving Tie-Breaking:** Every single-`RANGE` GSI and LSI shadow key is at most `37 + (1 + 2048 + 2) + (1 + 128 + 2 + 32) + (1 + 1024) = 3,276 <= 4,096` bytes—even with 2,048-byte partition keys and 1,024-byte all-`0x00` sort keys—while items sharing identical `(gsi_pk, gsi_sk)` with `<= 64`-byte base partition keys sort in exact DynamoDB lexicographical base-PK order. Multi-`RANGE` GSIs (`2..=4` `RANGE` keys) additionally validate the assembled shadow key against `row_key::MAX_ROW_KEY_SIZE` (`4,096`) in `prepare_shadow_plan` **before** mutating the base table. - * **Multi-Attribute Partition Envelope (`1..=4` `HASH` Keys) & Exact Equality Filtering:** The hashed `index_pk_envelope` frames single-`HASH` (`[tag:1][len:4][bytes]`) and multi-`HASH` (`[0x4D][inner_len:4]([tag_i:1][len_i:4][bytes_i]){2..4}`) keys unambiguously, and `QueryScan::query` (guided by an explicit `is_index: bool` flag from `BigtableEngine` so a GSI sharing the base table's key schema still uses shadow-key bounds) verifies the decoded HASH attributes in column family `d` before counting toward `limit`. Items missing any index `HASH` or `RANGE` key attribute are omitted from the shadow table (sparse-index semantics). + * **Multi-Attribute Partition Envelope (`1..=4` `HASH` Keys) & Exact Equality Filtering:** `gsi::hash_partition_values` hashes `index_pk_envelope` uniformly as `[count:u32BE:4]([tag_i:1][len_i:4][bytes_i]){1..4}` across `1..=4` `HASH` keys, and `QueryScan::query` (guided by an explicit `is_index: bool` flag from `BigtableEngine` so a GSI sharing the base table's key schema still uses shadow-key bounds) verifies the decoded HASH attributes in column family `d` before counting toward `limit`. Items missing any index `HASH` or `RANGE` key attribute are omitted from the shadow table (sparse-index semantics). * **Non-Terminal Sort Key Escape Encoding (`0..=4` `RANGE` Keys):** Every `0x00` byte in each `idx_sk_bytes_j` is escaped as `0x00 0xFF` and terminated by `0x00 0x00` (FoundationDB tuple encoding), preserving DynamoDB's lexicographic order across all `RANGE` attributes and base-key tie-breakers without sort-key boundary inversion. ### 2. Transaction Rules, Deterministic OCC Timestamps & Isolation Guarantees #### A. Transaction Validation & Idempotency Rules * **`ClientRequestToken` Idempotency (`RFC-0003` §3.3):** `TransactWriteItems` scopes idempotency keys by `(account_id, token)` (`idem::`) over a strict **10-minute (`600 s`) `applied_at` window** (`check_idempotency_record` evicts expired entries via `Catalog::mutate_json_cas`) and derives a deterministic coordinator ID `SHA-256(account_id || ":" || token)`: - * `TxnCoordinator::open_with_token` atomically persists `TxnTokenMeta` (`account_id`, `token`, `fingerprint`) in `t:token_meta` alongside `t:state = PENDING` and `t:started_at`, returning `(created, started_at_micros)`. + * `TxnCoordinator::open_with_token` atomically persists `TxnTokenMeta` (`account_id`, `token`, `fingerprint`) in `t:token_meta` alongside `t:state = PENDING`, `t:started_at`, and a unique per-call `t:open_nonce` via `DataHandle::check_and_mutate_row_idempotent_with_attempt` (verifying `(t:state == "PENDING", t:started_at, t:open_nonce)` via `is_own_retried_open` whenever `predicate_matched == true` on `attempt > 0`, and dropping its own row via `drop_matching_start` if all retries fail, so a lost response never causes a caller to collide with its own newly created coordinator row), returning `(created, started_at_micros)`. * When `created == true`, the caller immediately re-verifies `idem::` (rolling back and dropping its nascent `PENDING` incarnation if a prior winner persisted `idem:` and dropped `txn:` between pre-check and `open_with_token`). * When `created == false`, the caller never strips intents belonging to an active concurrent owner; instead, the follower loop validates `t:token_meta.fingerprint` across `PENDING`, `COMMITTED`, and `CLEANED` states (returning `IdempotentMismatch` immediately on payload mismatch without poisoning `idem:`, and cooperatively rolling forward `COMMITTED` transactions before returning `IdempotentReplay`). * Both inline Phase 2 (`roll_forward`) and `sweeper::sweep_once` (on both `COMMITTED` and `CLEANED` coordinator rows) persist `idem::` via `persist_idempotency_if_unexpired` **before** marking `CLEANED` and calling `drop_matching_start`, while Phase 1 `ConditionFailed` rollbacks drop `txn:` without writing `idem:` so retries with the same token can execute cleanly. @@ -111,7 +111,7 @@ sequenceDiagram ``` #### C. Read Isolation, Cooperative Read-Through & `TransactGetItems` Double-Read Snapshot -* **Consistent Read-Through on `GetItem` & `TransactGetItems`:** Whenever `DataEngine::get_item` or `TransactGetItems` encounters row intents (`m:intent:`), it consults `__extenddb_txn_log__`: if a referenced coordinator is `COMMITTED` and its post-image has not yet applied to family `d`, both `GetItem` (returning the committed post-image and kicking off best-effort roll-forward) and `TransactGetItems` serve the committed post-image immediately, while `PENDING` or `ABORTED` intents return the existing family `d` value without dirty reads. +* **Consistent Read-Through on `GetItem`, `Query`, `Scan` & `TransactGetItems`:** `DataEngine::get_item`, `QueryScan::query`/`scan` (using a `^d$` + `^m$` `Interleave` filter), and `TransactGetItems` all inspect column family `m` alongside `d`, retry or defer `in_progress_chunk` rows, and consult `__extenddb_txn_log__` whenever row intents (`m:intent:`) are present: if a referenced coordinator is `COMMITTED` and its post-image has not yet applied to family `d`, readers serve the committed post-image immediately (with `GetItem`, `Query`, and `Scan` kicking off best-effort cooperative roll-forward, providing read-committed cross-row visibility on `Query`/`Scan`), while `PENDING` or `ABORTED` intents return the existing family `d` value without dirty reads. * **Incarnation-Fenced Mutual Exclusion & Deleted-Table Tolerance (`RFC-0003` §3.1):** Both `TxnCoordinator::try_commit_full` (`PENDING -> COMMITTED`) and `TxnCoordinator::try_abort_pending` (`PENDING -> ABORTED`) execute `CheckAndMutateRow` predicated on `build_pending_incarnation_predicate(started_at_micros)`, and `sweeper` / inline cooperative recovery always CAS-transitions `PENDING -> ABORTED` **before** clearing any participant intent. If a table involved in a multi-table transaction is dropped via `DeleteTable` after `COMMITTED`, `roll_forward`, `apply_fenced_mutation`, and `clear_intent` treat Bigtable `NOT_FOUND` (`is_table_not_found_err`) on the deleted table as completed so the remaining tables finish rolling forward and the coordinator entry is cleaned cleanly. * **Zero Wall-Clock Intent Bypass:** `build_active_intent_filter` and `build_intent_presence_filter` carry **no** wall-clock `TimestampRangeFilter`, because an intent older than `intent_timeout_secs` may belong to a `COMMITTED` coordinator awaiting roll-forward. * **ABA-Safe Fenced Phase 2 Apply & Side-Effect Gating:** `TxnCoordinator::apply_fenced_mutation` predicates its `CheckAndMutateRow` via an outer `Filter::Condition` asserting **both** `m:intent:` presence (`exact_re2_bytes`) **and** the 3-case `(expected_version, row_existed)` OCC state guard. Unified `roll_forward` tracks `materialized_participants`, gating GSI/LSI shadow writes, `TxnTtlMutation` maintenance, **and** `TxnStreamRecord` emission so superseded coordinators emit zero phantom side effects. @@ -126,8 +126,9 @@ To prevent torn rows under `MaxNumVersions(1)` while satisfying Cloud Bigtable's * `next_occ_version(Some(prev)) = prev.max(now_ms) + 1` * `version_to_timestamp_micros(v) = (v * 1_000) as i64` * `next_millis_exclusive(ts_micros) = ((ts_micros / 1_000) + 1) * 1_000` -* **Single-`SetCell` Shadow Puts & Intent-Fenced 100,000-Mutation Chunking (`MAX_MUTATIONS_PER_RPC = 90_000`):** Because family `d` uses `MaxNumVersions(1)` and every reader applies `CellsPerColumnLimitFilter(1)`, `ItemOps::build_shadow_put_mutations` emits a single `SetCell` per retained projected attribute (`ts_micros >= max_d_ts`) plus `DeleteFromColumn` **only** for removed attributes—keeping a 50,000-attribute `ALL`-projected GSI/LSI shadow write at `50,002` mutations inside a single atomic `CheckAndMutateRow` RPC. Whenever a write exceeds `MAX_MUTATIONS_PER_RPC` (`90_000`), single-item `PutItem` and `UpdateItem` writes route through the coordinator-fenced `sgl-*` commit path so `GetItem` and `TransactGetItems` resolve the full committed item from `__extenddb_txn_log__` (with `RowSnapshot.in_progress_chunk` retry guards preventing torn mid-chunk reads), while `apply_fenced_mutation`, `put_cas`, and `apply_shadow_version_cas` execute progressive single-`Condition` `CheckAndMutateRow` batches fenced on `m:intent:*` (`attr:`) or `m:chunk` stage markers and `m:v`—placing primary-key attributes in the initial chunk and advancing `m:v` only on the final chunk. -* **Version-Guarded Shadow Updates & Durable Post-Commit Side-Effect Recovery:** GSI and LSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, `ItemOps::delete_shadow_orphan_if_unchanged`—sharing `apply_shadow_version_cas`, which predicates on `(m:v, m:chunk)` so higher-version writes and deletes immediately preempt incomplete lower-version shadow chunks) execute `CheckAndMutateRow` predicated on exact `(m:v, m:chunk)` state and reject (`Ok(false)`) any delayed writer (`new_version < cur_ver`). On single-item OCC writes (`execute_single_item_write`), shadow keys are pre-computed **before** `put_cas`. Once `put_cas` or `delete_cas` commits the base row, inline GSI/LSI shadow and TTL maintenance runs under a bounded post-commit timeout (`inline_side_effect_budget`) strictly below the tombstone grace horizon and, on timeout or transient error, records a `COMMITTED` `post-` side-effect entry anchored to `(data_table, row_key, base_version)` (`t:base_guard` via `TxnCoordinator::write_committed_side_effects_guarded`) in `__extenddb_txn_log__` for `sweeper` replay while logging a warning and returning success to the caller—preventing both silent stale index entries and post-commit 503 double-execution on non-idempotent updates (`SET a = a + 1`). +* **Single-`SetCell` Shadow Puts & Intent-Fenced 100,000-Mutation Chunking (`MAX_MUTATIONS_PER_RPC = 90_000`):** Because family `d` uses `MaxNumVersions(1)` and every reader applies `CellsPerColumnLimitFilter(1)`, `ItemOps::build_shadow_put_mutations` emits a single `SetCell` per retained projected attribute (`ts_micros >= max_d_ts`) plus `DeleteFromColumn` **only** for removed attributes—keeping a 50,000-attribute `ALL`-projected GSI/LSI shadow write at `50,002` mutations inside a single atomic `CheckAndMutateRow` RPC. Whenever a base-table write exceeds `MAX_MUTATIONS_PER_RPC` (`90_000`), single-item `PutItem` and `UpdateItem` writes route exclusively through the coordinator-logged `sgl-*` commit path (`ItemOps::put_cas` rejects `> MAX_MUTATIONS_PER_RPC` rather than staging unlogged multi-chunk writes) so `GetItem`, `Query`, `Scan`, and `TransactGetItems` resolve the full committed item from `__extenddb_txn_log__` (with `in_progress_chunk` retry guards preventing torn mid-chunk reads), while `apply_fenced_mutation` and `apply_shadow_version_cas` execute progressive single-`Condition` `CheckAndMutateRow` batches fenced on `m:intent:*` (`attr:`) or `m:chunk` stage markers and `m:v`—placing primary-key attributes in the initial chunk and advancing `m:v` only on the final chunk. +* **Non-Idempotent CAS Pre-Execution Retry Only & Wall-Clock Per-Row Timestamps:** `ItemOps::put_cas`, `ItemOps::delete_cas`, and `ItemOps::apply_shadow_version_cas` invoke `DataHandle::check_and_mutate_row` (retrying only pre-execution transport rejections, never post-execution `Unavailable`/`DeadlineExceeded`/`GoAway` without write disambiguation) so a lost response after Attempt 1 commits never triggers an `OccMismatch` re-execution of `UpdateItem` (`ADD`) or spurious `ConditionalCheckFailedException`. Non-OCC metadata cells (coordinator, catalog, stream, and chunk markers) use wall-clock millisecond-aligned timestamps (`monotonic_timestamp_micros`) paired with per-row `monotonic_timestamp_after_micros(existing_ts)` rather than advancing a process-wide counter that could drift ahead of wall clock under high QPS. +* **Version-Guarded Shadow Updates, LSI Read-After-Write Flush & Durable Post-Commit Side-Effect Recovery:** GSI and LSI shadow updates (`ItemOps::put_shadow_versioned`, `ItemOps::delete_shadow_versioned`, `ItemOps::delete_shadow_orphan_if_unchanged`—sharing `apply_shadow_version_cas`, which predicates on `(m:v, m:chunk)` so higher-version writes and deletes immediately preempt incomplete lower-version shadow chunks) execute `CheckAndMutateRow` predicated on exact `(m:v, m:chunk)` state and reject (`Ok(false)`) any delayed writer (`new_version < cur_ver`). On single-item OCC writes (`execute_single_item_write`), shadow keys are pre-computed **before** `put_cas`. Once `put_cas` or `delete_cas` commits the base row, inline GSI/LSI shadow and TTL maintenance runs under a bounded post-commit timeout (`inline_side_effect_budget`) strictly below the tombstone grace horizon and, on timeout or transient error, records a `COMMITTED` `post-` side-effect entry anchored to `(data_table, row_key, base_version)` (`t:base_guard` via `TxnCoordinator::write_committed_side_effects_guarded`) with exponential-backoff retries—retaining an in-memory `PendingSideEffectRecovery` queue (`pending_side_effect_recoveries`) if `__extenddb_txn_log__` itself is momentarily unreachable and running `ensure_lsi_read_after_write` (flushing `pending_side_effect_recoveries` and rolling forward `COMMITTED` coordinator/`post-*` entries for the table) before LSI `Query` and `Scan` read the LSI shadow table—preventing silent index drift, stale LSI reads, and post-commit 503 double-execution on non-idempotent updates (`SET a = a + 1`). * **De Morgan OCC CAS & Retry Loop (`select_occ_predicate`):** `ItemOps::put_cas` and `ItemOps::delete_cas` express OCC guards in De Morgan conflict form with mutations in `false_mutations`, cooperatively resolving `COMMITTED` or expired `PENDING` intents, returning `StorageError::TransactionConflict` if a live multi-item 2PC `txn-*` holds the row ([RFC-0003](0003-backend-acceptance-criteria.md) §4.3), or retrying OCC mismatches with jittered backoff. #### E. Cloud Bigtable App Profile & Single-Cluster Routing Validation @@ -135,8 +136,8 @@ Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on #### F. Garbage Collection (GC), Version-Only Tombstone Reclamation & Recovery Sweeper * **Column Family GC:** `d` and `m` on data/GSI/LSI tables, `c` on `__extenddb_catalog__` and `__extenddb_data_ledger__`, and `d` on `__extenddb_ttl_index__` are provisioned with `MaxNumVersions(1)`. -* **Bounded Tombstone Reclamation (`tomb:` Queue & `reclaim_version_only_row`):** Deleting an item leaves a version-only `m:v` tombstone row to prevent rapid `Put -> Delete -> Put` timestamp regression, and enqueues a fixed 45-byte GC marker `b"tomb:" || ready_ms_be8 || sha256(table_name || 0x00 || row_key)` (`0x74 >= 16`, disjoint from TTL shards `0x00..=0x0F` and immune to 4 KiB key limits) anchored at `expected_version.saturating_add(1).max(now_ms) + grace_ms` (`intent_timeout_secs`, `60 s` default) in `__extenddb_ttl_index__`. Once `sweep_txn_log` finishes cleanly (with `post-*` replays skipping stale shadow `Put` and TTL `new_expiry` writes whenever the base row has moved past `t:base_guard.base_version` while still applying prior `Delete` cleanups) and `now_ms >= ready_ms` with `now_millis() > expected_version`, `sweeper` calls `ItemOps::reclaim_version_only_row(row_key, expected_version)`, which enforces `now_millis() > expected_version` and executes an atomic `CheckAndMutateRow` (`DeleteFromRow` in `false_mutations`) that reclaims the physical Bigtable row **if and only if** zero `m:intent:*` cells exist, zero `m:chunk` cells exist, `m:v == expected_version`, and zero `d:*` cells exist—never deleting a concurrently re-inserted live item or allowing subsequent `next_occ_version(None)` inserts to regress below a surviving shadow version. -* **2PC & Side-Effect Recovery Sweeper (`sweeper.rs`):** Runs under a renewed distributed catalog lease (`lock:sweeper`), CAS-aborting timed-out `PENDING` coordinators, rolling forward `COMMITTED` transactions and `post-*` side-effect records, persisting `idem:` tokens, and draining due `b"tomb:"` tombstone GC entries. +* **Bounded Tombstone Reclamation (`tomb:` Queue & `reclaim_version_only_row`):** Deleting an item (including `delete_cas`, 2PC `roll_forward` deletes and self-matched deletes, shadow version deletes, and `gsi_worker` `delete_shadow_orphan_if_unchanged`) leaves a version-only `m:v` tombstone row to prevent rapid `Put -> Delete -> Put` timestamp regression, and enqueues a fixed 45-byte GC marker `b"tomb:" || ready_ms_be8 || sha256(table_name || 0x00 || row_key)` (`0x74 >= 16`, disjoint from TTL shards `0x00..=0x0F` and immune to 4 KiB key limits) anchored at `expected_version.saturating_add(1).max(now_ms) + grace_ms` (`intent_timeout_secs`, `60 s` default) in `__extenddb_ttl_index__`. `sweep_txn_log` tracks failed recovery table families (`blocked_tables`) alongside per-row `(data_table, row_key)` guards for young `COMMITTED` entries (`unsettled_committed_rows`) rather than blocking global tombstone reclamation on unrelated young `< 60 s` transactions; for every unblocked row where `now_ms >= ready_ms` and `now_millis() > expected_version` (with `post-*` replays skipping stale shadow `Put` and TTL `new_expiry` writes whenever the base row has moved past `t:base_guard.base_version` while still applying prior `Delete` cleanups), `sweeper` calls `ItemOps::reclaim_version_only_row(row_key, expected_version)`, which enforces `now_millis() > expected_version` and executes an atomic `CheckAndMutateRow` (`DeleteFromRow` in `false_mutations`) that reclaims the physical Bigtable row **if and only if** zero `m:intent:*` cells exist, zero `m:chunk` cells exist, `m:v == expected_version`, and zero `d:*` cells exist—never deleting a concurrently re-inserted live item or allowing subsequent `next_occ_version(None)` inserts to regress below a surviving shadow version. +* **2PC & Side-Effect Recovery Sweeper (`sweeper.rs`):** Runs under a renewed distributed catalog lease (`lock:sweeper`), flushing any in-memory `pending_side_effect_recoveries`, CAS-aborting timed-out `PENDING` coordinators, rolling forward `COMMITTED` transactions and `post-*` side-effect records, persisting `idem:` tokens, and draining due `b"tomb:"` tombstone GC entries across unblocked tables while honoring `pass_token` cancellation on lease loss. ### 3. Unified Fenced DynamoDB Streams Architecture & Stream Lineage @@ -153,13 +154,13 @@ Cloud Bigtable native Change Streams (`ReadChangeStream`) were evaluated and rej ### 4. Scalable TTL Indexing, `ENABLING` Backfill & Fenced Expiration #### A. Sharded TTL Index Schema & `ENABLING -> ENABLED` Backfill -* **Row Key Binary Layout:** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [encoded_base_row_key]` across shards `0..16` (`fnv1a(base_row_key) % 16`), ordered chronologically within each shard. -* **Pre-Existing Item Backfill (`update_ttl` & `create_ttl_index`):** Enabling TTL (`MetadataEngine::update_ttl(..., true)`) sets `ttl.status = "ENABLING"` with a unique `generation` UUID in `table_meta` (reported as `TimeToLiveStatus::Enabling` by `describe_ttl`) and invalidates the metadata cache so live writes immediately begin maintaining `__extenddb_ttl_index__`. `MetadataEngine::create_ttl_index` (spawned asynchronously by `extenddb-engine` and resumed automatically on crash/restart by `ttl_worker`) acquires a renewed per-table `lock:ttl_backfill:` catalog lease, waits `1.35 s` (`await_schema_visibility_fence`) for sibling nodes' `1 s` metadata caches and `250 ms` fast writes to observe `ENABLING`, pages the base table (`read_base_row_for_worker`) inserting OCC-stamped TTL index entries for every item carrying a positive TTL attribute, and promotes `ttl.status` from `"ENABLING"` to `"ENABLED"` via generation-checked CAS. Disabling TTL invokes `MetadataEngine::drop_ttl_index` to purge the table's entries cleanly. -* **OCC-Ordered Write & Recovery Maintenance (`apply_ttl_mutation_versioned`):** Live writes and `roll_forward` parse integer, fractional, and scientific `AttributeValue::N` strings via `parse_ttl_epoch_secs` (treating `<= 0` as non-expiring) and stamp `SetCell("d", b"", occ_ts)` followed by bounded `DeleteFromColumn("d", b"", [0, occ_ts))` so out-of-order `1000 -> 2000 -> 1000` ABA updates commute deterministically. +* **Digest-Bounded Row Key & `table_id`-Tagged Cell Layout (`ttl_key.rs`):** `[shard_id:1] [expiry_epoch_secs_be:i64:8] [account_id_len:1] [account_id] [table_name_len:1] [table_name] [base_rk_or_digest]` across shards `0..16` (`fnv1a(base_row_key) % 16`), ordered chronologically within each shard. When raw `base_row_key` concatenation would exceed `4,096` bytes (e.g., long account/table names combined with a near-`3,078`-byte composite base key), `encode_ttl_key` replaces the suffix with `[0x44 ('D')][SHA-256(base_rk):32]` (`33` bytes, `<= 4,096` bytes guaranteed) and stores the full `base_row_key` inside the cell payload (`tv1:[tid_len:u16BE][table_id][base_rk]`, `encode_ttl_value`). +* **Pre-Existing Item Backfill (`update_ttl` & `create_ttl_index`) & `O(due)` Orphan Retirement:** Enabling TTL (`MetadataEngine::update_ttl(..., true)`) sets `ttl.status = "ENABLING"` with a unique `generation` UUID in `table_meta` (reported as `TimeToLiveStatus::Enabling` by `describe_ttl`) and invalidates the metadata cache so live writes immediately begin maintaining `__extenddb_ttl_index__`. `MetadataEngine::create_ttl_index` (spawned asynchronously by `extenddb-engine` and resumed automatically on crash/restart by `ttl_worker`) acquires a renewed per-table `lock:ttl_backfill:` catalog lease, waits `1.35 s` (`await_schema_visibility_fence`) for sibling nodes' `1 s` metadata caches and `250 ms` fast writes to observe `ENABLING`, pages the base table (`read_base_row_for_worker`) inserting OCC-stamped `table_id`-tagged TTL index entries for every item carrying a positive TTL attribute, and promotes `ttl.status` from `"ENABLING"` to `"ENABLED"` via generation-checked CAS. Disabling TTL (`drop_ttl_index`) or deleting a table (`DeleteTable`) updates/removes `table_meta` without scanning all 16 shards across all tables; orphaned entries from dropped or recreated (`entry_table_id != live_table_id`) tables are lazily retired in `O(due)` as their timestamps come due in `ttl_worker`, while entries on `DISABLED` or `ENABLING` tables remain intact so re-enabling never misses due items. +* **OCC-Ordered Write & Recovery Maintenance (`apply_ttl_mutation_versioned`):** Live writes and `roll_forward` parse integer, fractional, and scientific `AttributeValue::N` strings via `parse_ttl_epoch_secs` (treating `<= 0` as non-expiring) and stamp `SetCell("d", b"", encode_ttl_value(table_id, base_rk), occ_ts)` followed by bounded `DeleteFromColumn("d", b"", [0, occ_ts))` so out-of-order `1000 -> 2000 -> 1000` ABA updates commute deterministically. -#### B. Live Verification, Preservation While Off/Enabling & Fenced TTL Stream Emission (`ttl_worker.rs`) -1. Under the renewed distributed `lock:ttl_worker` catalog lease, `ttl_worker` first resumes any interrupted `ENABLING` table backfills, then scans `[shard || 0, shard || (now + 1))` across shards `0..16`. -2. Check table status: if the table was deleted (`TableNotFound`), retire the orphan index cell; if TTL is `Enabling`, `Disabling`, or `Disabled`, **leave the index entry untouched** (`continue`) so entries coming due while TTL is off or mid-backfill are never destroyed prematurely. +#### B. Live Verification, Preservation While Disabled/Enabling & Fenced TTL Stream Emission (`ttl_worker.rs`) +1. Under the renewed distributed `lock:ttl_worker` catalog lease, `ttl_worker` first resumes any interrupted `ENABLING` table backfills, then scans `[shard || 0, shard || (now + 1))` across shards `0..16` (checking `pass_token.is_cancelled()` across shards and entries). +2. Check table status and `table_id`: if the table was deleted (`TableNotFound`) or recreated under a new `table_id` (`entry_table_id != live_table_id`), retire the orphaned index cell (`delete_ttl_index_entry_up_to` bounded by `[0, next_millis_exclusive(idx_ts_micros))`); if TTL is `Disabled`, `Enabling`, or `Disabling` on the matching `table_id`, **leave the index entry untouched** (`continue`) so entries coming due while disabled or enabling are never lost before `ENABLED` settles or if TTL is re-enabled. 3. For `Enabled` tables, read the live base item + OCC version (`get_item_with_version`), retiring stale/extended entries via bounded `DeleteFromColumn` (`[0, next_millis_exclusive(bound_ts))`), and evicting genuinely expired items (`0 < live_secs <= now`) via guarded `DataEngine::delete_item` (`#ttl = :live_exp_str`) with `Service` `UserIdentity` (`dynamodb.amazonaws.com`) stream capture and `TimeToLiveDeletedItemCount` / `TtlStalenessSeconds` metrics. ### 5. Query, Scan, LSI Shadow Tables & Online GSI Lifecycle @@ -167,7 +168,7 @@ Cloud Bigtable native Change Streams (`ReadChangeStream`) were evaluated and rej * **Exact Sort-Key Bounds, Explicit `is_index` Routing & Reverse-Scan Compatibility (`query_scan.rs`):** `BigtableEngine` passes an explicit `is_index: bool` flag (`index_name.is_some()`) into `QueryScan::query`, `QueryScan::scan`, and `QueryScan::key_belongs_to_segment`, ensuring base tables use `build_base_range_for_query` while both GSIs (even when sharing the base table's key schema) and LSIs use `build_gsi_range_for_query` over their respective `_g<8hex>` and `_l<8hex>` shadow tables. Both paths validate `ExclusiveStartKey` schema, scalar types, and partition boundaries, merge `ExclusiveStartKey` into active sort-key bounds, clamp bounds to 4,096 bytes, fetch `limit + 1` matching items for exact `LastEvaluatedKey` emission, execute native server-side `ReadRowsRequest { reversed: true }` against Cloud Bigtable (enabled via `bigtable-features: CAE=`), and fall back cleanly when `cbtemulator` rejects `reversed: true` with `UNIMPLEMENTED`. * **Online `UpdateTable` GSI Build, Cache Visibility Fence & `CREATING`-Only `gsi_worker` (`engine.rs`, `gsi_worker.rs`):** * Table metadata is cached for `1 s` (`METADATA_CACHE_TTL`). Any write taking `>= 250 ms` (`FAST_WRITE_BUDGET`) re-reads uncached `table_meta` post-commit (`repair_slow_write_schema_drift`) and repairs any GSI or TTL index added concurrently—deleting stale shadow keys only when `old_rk != new_rk`, anchoring versions to `live_ver.unwrap_or(committed_version)` rather than synthesizing versions on absent rows, bounding inline repair RPCs with `post-*` recovery fallback, and re-verifying the base row after GSI insertion to retire entries superseded before `SCHEMA_VISIBILITY_FENCE`. - * When `UpdateTable` creates a GSI (`index_status = "CREATING"`), `run_gsi_backfill` acquires a renewed per-index catalog lease `lock:gsi_build::` (so `gsi_worker` never races a live build or rolls back a sibling GSI), waits `1.35 s` (`await_schema_visibility_fence` > `1 s + 250 ms`), rolls forward `COMMITTED` transactions for the table, backfills projected rows via version-guarded `put_shadow_versioned`, and promotes the GSI `"CREATING" -> "ACTIVE"` via CAS (rolling back **only** that GSI if still `"CREATING"` on failure). + * When `UpdateTable` creates a GSI (`index_status = "CREATING"`), `TableEngine::update_table` (and `gsi_worker::recover_creating_gsi` on crash recovery) acquires a renewed per-index catalog lease `lock:gsi_build::` (so `gsi_worker` never races a live build or rolls back a sibling GSI), waits `1.35 s` (`await_schema_visibility_fence` > `1 s + 250 ms`), rolls forward `COMMITTED` transactions for the table, backfills projected rows via version-guarded `put_shadow_versioned`, and promotes the GSI `"CREATING" -> "ACTIVE"` via CAS (rolling back **only** that GSI if still `"CREATING"` on failure). * `gsi_worker` runs **only** on tables that currently have at least one `"CREATING"` GSI—resuming interrupted builds under the same `lock:gsi_build::` lease without scanning `ACTIVE` tables every cycle. ### 6. GCP Connectivity, Migrations, Serving Registration & Error Classification @@ -188,13 +189,13 @@ ttl_scan_cadence_secs = 60 gsi_reconcile_cadence_secs = 300 ``` -* **Resilient Direct `tonic` Pool, Multi-Frame `ReadRowsAssembler`, `64 MiB` gRPC Limits & Split-Instance Isolation (`data/client.rs`, `data/admin.rs`, `config.rs`):** `BigtableClient::connect` builds a multi-channel `tonic::transport::Channel::balance_channel` pool directly over `googleapis_tonic_google_bigtable_v2` configured with `64 MiB` max encoding/decoding message sizes (`MAX_GRPC_MESSAGE_BYTES`), a stateful multi-frame `ReadRowsAssembler` (reassembling multi-megabyte cells and multi-cell rows split across consecutive `ReadRowsResponse` stream messages), URL-encoded `x-goog-request-params` regional routing metadata across both data-plane `BigtableClient` and control-plane `AdminClient` RPCs (with `AdminClient::create_table` invoking `ensure_families` strictly on `AlreadyExists` and adding only missing column families after `GetTable(SchemaView)`), `bigtable-features: CAE=` (`FeatureFlags { reverse_scans: true }`) metadata enabling server-side reverse `ReadRows`, OAuth2 bearer token injection via `gcp_auth` (skipped with a `BigtableClient::log_startup_endpoint` `tracing::warn!` warning when `emulator_host` or `BIGTABLE_EMULATOR_HOST` is resolved via `BigtableStorageConfig::resolve_emulator_host`, or logged via `tracing::info!` when connecting to Cloud Bigtable over TLS), and automatic pool replacement + bounded retry on HTTP/2 `GoAway` (`ENHANCE_YOUR_CALM`) or transport resets across `read_rows`, `mutate_row`, stream-draining `mutate_rows`, and idempotent/pre-execution `check_and_mutate_row` errors. -* **Compile-Time Backend Registration & Shared Storage Helpers (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` while exposing the mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`, linted in `.github/workflows/clippy.yml`). Shared IAM key/policy helpers (`generate_access_key_id`, `generate_secret_key`, `generate_session_key_id`, `generate_session_token`, `self_service_policy`) and `string_coerce::u64` live in `extenddb-storage` (reused across all five backends and `crates/server`), and `create_backup_unsupported("bigtable")` wires the startup banner/log notice in `crates/{engine,server,app}`. -* **At-Rest Secret Encryption & Fail-Closed Auth Redaction (`catalog_store.rs`):** `BigtableCatalogStore` and `BigtableCredentialStore` encrypt and decrypt `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions via `SecretKeys` (`CATALOG_KEY_SETTING = "catalog_encryption_key"`). Any corrupt catalog row, missing key ring, or AEAD decryption failure in `lookup_credential` logs details server-side via `tracing::error!` and returns a redacted `DynamoDbError::InternalServerError("Internal error during authentication")` without leaking internal identifiers. No unauthenticated development admin bypass exists in the crate. -* **`ADR-0023` / `ADR-0029` Baseline Migrations, Renewed Lock & `ServingRegistrar` (`m0001_baseline.rs`, `migrations.rs`, `runtime_hooks.rs`):** - * **Migration 1 (`MigrationId::Baseline`, `Kind::Breaking`, convergent):** Splits cleanly across `M0001CatalogBaseline` (`StoreKind::Catalog` on `instance_id`: provisions `__extenddb_catalog__` and `setting:catalog_id`) and `M0001DataBaseline` (`StoreKind::Data` on `effective_data_instance_id`: provisions `__extenddb_data_ledger__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__`), pinned under a single SHA-256 checksum verified by `devtools/check-released-through`. - * **Migrations 2–12 (`NotApplicable`):** Recorded in `migration_ledger:catalog:` alongside RFC 3339 `version:catalog` and `setting:catalog_version`. - * **Renewed Migration Lease & Serving Registration:** `BigtableCatalogMigrations::lock` creates `__extenddb_catalog__` if absent (during `init`), acquires `lock:catalog_migrations` (60 s lease renewed every 15 s on a background task with a 25 s safety margin before every step), and calls `wait_for_servers` (`server_registration:*`) before running migrations. `BigtableRuntimeHooks::serving_registrar` exposes the active `ServingRegistration` (`server_registration:`) and `register_and_check_as` verifies `Runner::status` is `Current` (or `AheadCompatible`) at `serve` startup (refusing `Uninitialized`, `Behind`, `AheadIncompatible`, `NeedsAttention`, `Changed`, `WrittenByOlderRelease`, and `Locked`). +* **Resilient Direct `tonic` Pool, Multi-Frame `ReadRowsAssembler`, `64 MiB` gRPC Limits & Split-Instance Isolation (`data/client.rs`, `data/admin.rs`, `config.rs`):** `BigtableClient::connect` builds a multi-channel `tonic::transport::Channel::balance_channel` pool directly over `googleapis_tonic_google_bigtable_v2` configured with `64 MiB` max encoding/decoding message sizes (`MAX_GRPC_MESSAGE_BYTES`), per-message `tokio::time::timeout` guards on streaming `ReadRows` and `MutateRows` responses, a stateful multi-frame `ReadRowsAssembler` (reassembling multi-megabyte cells and multi-cell rows split across consecutive `ReadRowsResponse` stream messages), URL-encoded `x-goog-request-params` regional routing metadata across both data-plane `BigtableClient` and control-plane `AdminClient` RPCs (with `AdminClient` configuring `.connect_timeout` / `.timeout`, sharing a cached `TokenProvider`, preserving structured `AdminError::Rpc { context, status }` codes via `classify_grpc_status`, and `AdminClient::create_table` invoking `ensure_families` strictly on `AlreadyExists` to add only missing column families after `GetTable(SchemaView)`), `bigtable-features: CAE=` (`FeatureFlags { reverse_scans: true }`) metadata enabling server-side reverse `ReadRows`, OAuth2 bearer token injection via `gcp_auth` (skipped with a `BigtableClient::log_startup_endpoint` `tracing::warn!` warning when `emulator_host` or `BIGTABLE_EMULATOR_HOST` is resolved via `BigtableStorageConfig::resolve_emulator_host`, or logged via `tracing::info!` when connecting to Cloud Bigtable over TLS), and automatic pool replacement + bounded retry on HTTP/2 `GoAway` (`ENHANCE_YOUR_CALM`) or transport resets across `read_rows`, `mutate_row`, stream-draining `mutate_rows`, and pre-execution `check_and_mutate_row` errors. +* **Compile-Time Backend Registration & Shared Storage Helpers (`default = ["postgres"]` Preserved):** `crates/bin` preserves `default = ["postgres"]` while exposing the mutually exclusive `bigtable` Cargo feature (`cargo build --no-default-features --features bigtable`, linted in `.github/workflows/clippy.yml`). Shared IAM key/policy helpers (`generate_access_key_id`, `generate_secret_key`, `generate_session_key_id`, `generate_session_token`, `self_service_policy`) and `string_coerce::u64` live in `extenddb-storage` (reused across all five backends and `crates/server`), and `create_backup_unsupported("bigtable")` wires the startup banner/log notice in `crates/{engine,server,app}` across both `EffectiveStore::Unconfigured` and `EffectiveStore::Configured`. +* **CAS Catalog Overwrites, At-Rest Secret Encryption & Fail-Closed Auth Redaction (`catalog/mod.rs`, `catalog_store.rs`):** `Catalog::put`, `Catalog::put_if_present`, and `Catalog::mutate_json_cas` read raw cell bytes + timestamps via `get_raw_cell_bytes_with_ts` and overwrite via `compare_and_swap_raw_after` (`monotonic_timestamp_after_micros(existing_ts)` + `DeleteFromColumn([0, write_ts))`) so overwrites always supersede any future-skewed or corrupt prior cell under `CellsPerColumnLimitFilter(1)`. `BigtableCatalogStore` and `BigtableCredentialStore` encrypt and decrypt `AKIAEXTENDDB*` access keys and `ASIAEXTENDDB*` STS sessions via `SecretKeys` (`CATALOG_KEY_SETTING = "catalog_encryption_key"`), paging secrets in `O(page_size)` via `Catalog::scan_str_range` (`StartKeyOpen` + `rows_limit = page_size + 1`). Any corrupt catalog row, missing key ring, or AEAD decryption failure in `lookup_credential` logs details server-side via `tracing::error!` and returns a redacted `DynamoDbError::InternalServerError("Internal error during authentication")` without leaking internal identifiers. No unauthenticated development admin bypass exists in the crate. +* **`ADR-0023` / `ADR-0029` Baseline Migrations, Renewed Lock, Lease-Guarded `LockedStores` & `ServingRegistrar` (`m0001_baseline.rs`, `migrations.rs`, `runtime_hooks.rs`):** + * **Migration 1 (`MigrationId::Baseline`, `Kind::Breaking`, convergent):** Splits cleanly across `M0001CatalogBaseline` (`StoreKind::Catalog` on `instance_id`: provisions `__extenddb_catalog__` and `setting:catalog_id`, with a `detect` check flagging `CatalogStatus::NeedsAttention` if application rows already exist without ledger/version rows) and `M0001DataBaseline` (`StoreKind::Data` on `effective_data_instance_id`: provisions `__extenddb_data_ledger__`, `__extenddb_txn_log__`, and `__extenddb_ttl_index__`), pinned under a single SHA-256 checksum verified by `devtools/check-released-through`. + * **Migrations 2–12 (`NotApplicable`):** Recorded in `migration_ledger:catalog:` alongside RFC 3339 `version:catalog` and `setting:catalog_version` (both checked by `read_traces`). + * **Renewed Migration Lease, Guarded `LockedStores` & Serving Registration:** `BigtableCatalogMigrations::lock` refuses foreign non-ExtendDB rows before writing, creates `__extenddb_catalog__` if absent (during `init`), acquires `lock:catalog_migrations` (`60 s` lease renewed every `15 s` via `Catalog::renew_lock` chaining `ValueRegexFilter(exact_owner)` + `TimestampRangeFilter(now_micros, 0)`, cancelling immediately if local wall-clock passes the confirmed expiry deadline even on RPC errors, and checking a `25 s` safety margin before every step), wraps `LockedStores` (`LeasedBigtableStores`) so `ManagementStore` and `SettingsStore` calls during `extenddb encryption-key rotate`/`rewrap`/`retire` enforce `check_lease()` and record `progressed()`, and calls `wait_for_servers` (`server_registration:*`) before running migrations. `BigtableRuntimeHooks::serving_registrar` exposes the active `ServingRegistration` (`server_registration:`) and `register_and_check_as` verifies `resolve_status` (`Runner::status` + `unexpected_uninitialized_catalog_rows`) is `Current` (or `AheadCompatible`) at `serve` startup (refusing `Uninitialized`, `Behind`, `AheadIncompatible`, `NeedsAttention`, `Changed`, `WrittenByOlderRelease`, and `Locked`). * **gRPC Error Classification (`data/client.rs`):** * `Unavailable`, `DeadlineExceeded`, `Aborted`, `ResourceExhausted`, RPC timeouts, and transient I/O errors map to `StorageError::Transient` (retryable HTTP 503 `ServiceUnavailable`). * `NotFound` (missing/deleted Bigtable table) maps to `StorageError::TableNotFound`. @@ -228,7 +229,7 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept | `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | `create_catalog_db`, `init_target`, `hold`, `bootstrap_encryption_key` (`CATALOG_KEY_SETTING`), `bootstrap_default_account`, `bootstrap_admin_user`, and catalog-scoped `drop_databases` preserving non-ExtendDB tables | | `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | `MigrationId::Baseline` (`Kind::Breaking`: `M0001CatalogBaseline` + `M0001DataBaseline`) + `2..=12` (`NotApplicable`), pinned SHA-256 baseline checksum, renewed `lock:catalog_migrations` lease, and `wait_for_servers` fence | | `OperationsEngine` | Mandatory (CLI) | Implemented | `src/operations.rs` | Connection URL & `BIGTABLE_EMULATOR_HOST` parsing, identifier validation, sensitive-key redaction, runtime setting defaults | -| `ServerRuntimeHooks` | Mandatory (Serve & Workers) | Implemented | `src/runtime_hooks.rs` | `serving_registrar` (`server_registration:`), startup `Runner::status` check & `GetAppProfile` validation, emulator auth warning, and 5 leased workers (`ttl_worker`, `sweeper`, `CREATING`-only `gsi_worker`, 24h `stream_record_cleanup`, 10m `idempotency_token_cleanup`) | +| `ServerRuntimeHooks` | Mandatory (Serve & Workers) | Implemented | `src/runtime_hooks.rs` | `serving_registrar` (`server_registration:`), startup `Runner::status` check & `GetAppProfile` validation, emulator auth warning, and 5 leased workers (`ttl_worker`, `sweeper`, `CREATING`-only `gsi_worker`, 1h `stream_record_cleanup` [24h retention], 10m `idempotency_token_cleanup`) | ## Testing Strategy @@ -239,10 +240,10 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept 2. **Live Bigtable Emulator Integration & Conformance Suite (`cargo test -p extenddb-storage-bigtable --features test-hooks --test emulator_integration -- --nocapture` against `cbtemulator`, gated via `EXTENDDB_TEST_BIGTABLE_REQUIRED=1`):** * Catalog + split `data_instance_id` baseline migrations (`__extenddb_catalog__`, `__extenddb_data_ledger__`, `__extenddb_txn_log__`, `__extenddb_ttl_index__`), renewed `lock:catalog_migrations` + `ServingRegistration` fencing, and `drop_databases` preservation of foreign tables alongside base/GSI/LSI cleanup. * Exact 5-item `[a, ab, b, ba, c]` base sort-key range queries, 2,048-byte partition-key GSI round-trips and pre-commit `> 4,096`-byte multi-RANGE rejection, GSI sharing the base table's key schema, and ordered LSI shadow-table `Query`/`Scan`/projections. - * Read-through `GetItem` and double-read `TransactGetItems` on `COMMITTED` unapplied intents, multi-table `roll_forward` when one table was deleted, `post-*` side-effect replay, version-only `tomb:` row reclamation after grace expiry, pre-CAS stream shard creation & pre-close roll-forward, `CREATING`-only leased GSI builds, and TTL `ENABLING -> ENABLED` pre-existing item backfill + preservation while `DISABLED`. + * Read-through `GetItem`, `Query`, and `Scan` plus double-read `TransactGetItems` on `COMMITTED` unapplied intents, multi-table `roll_forward` when one table was deleted, `post-*` side-effect replay, version-only `tomb:` row reclamation after grace expiry, pre-CAS stream shard creation & pre-close roll-forward, `CREATING`-only leased GSI builds, and TTL `ENABLING -> ENABLED` pre-existing item backfill + `<= 4,096`-byte SHA-256 digest eviction + preservation while `DISABLED`. * Shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, and `key_conformance::run`. -3. **End-to-End Wire Conformance (`devtools/run-bigtable-tests`):** - * Wire-level Rust (`--rust`, `--rust-integration`) and Python (`--pytest`, `--comprehensive`) conformance suites executed via `devtools/run-tests --extenddb --backend bigtable` against an `extenddb` binary built with `--no-default-features --features bigtable` backed by `cbtemulator`. +3. **End-to-End Wire & Catalog-Lock Conformance (`devtools/run-bigtable-tests`, `devtools/check-bigtable-catalog-lock`):** + * Wire-level Rust (`--rust`, `--rust-integration`) and Python (`--pytest`, `--comprehensive`) conformance suites executed via `devtools/run-tests --extenddb --backend bigtable` against an `extenddb` binary built with `--no-default-features --features bigtable` backed by `cbtemulator`, plus `devtools/check-bigtable-catalog-lock` exercising `init`, `migrate`, `verify`, `serve`, `backup`, `SIGKILL` lease expiry, and `SIGSTOP` registration-loss shutdown. ## Alternatives Considered From 063be74468e53c59b1407b997f83e888f622b177 Mon Sep 17 00:00:00 2001 From: An Nguyen Date: Wed, 25 Nov 2026 19:15:45 +0000 Subject: [PATCH 11/11] docs(rfc): reverse-sync AT_TIMESTAMP seeks, retention fencing, DiagnosticsStore defaults, and U+10FFFF query coverage --- docs/rfcs/0000-bigtable-backend.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md index 496a84e27..b6d0bcd4d 100644 --- a/docs/rfcs/0000-bigtable-backend.md +++ b/docs/rfcs/0000-bigtable-backend.md @@ -144,9 +144,9 @@ Cloud Bigtable offers single-row transactions (`CheckAndMutateRow`) **only** on #### A. Write-Ahead Fenced Stream Emission, Pre-CAS Shard Creation & Stream Lineage Whenever a caller supplies `stream: Some(&StreamCapture)` on a stream-enabled table, single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`—including TTL sweeper deletions) execute through the `__extenddb_txn_log__` commit fence (`commit_fenced_single_item_write` + `roll_forward`), while `stream: None` writes (`ImportTable` bulk imports) suppress stream emission: -1. **Pre-CAS Shard Provisioning & Pre-Close Roll-Forward (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and pre-creates `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) at `stream_shard:` **before** publishing `latest_stream_label` in `table_meta` via `Catalog::mutate_json_cas` (cleaning up orphaned pre-created shards if CAS loses a race). Conversely, disabling a stream calls `roll_forward_committed_txns_for_table` **before** closing shards (`close_shards_by_id` serializing under `shard_local_mutex` and using `O(1)` tail-probing `latest_sequence_for_shard` rather than scanning every historical record), `streams::write_record_ordered` persists `stream_dedup` markers before atomically verifying `ShardMeta` remains open via `advance_shard_cursor_if_open` (`Catalog::mutate_json_cas`—deleting any unexposed record/dedup slot `> ending_sequence_number` and returning `Ok(None)`), and `StreamEngine::get_stream_records` clamps both `scan_str_range` bounds and returned records at `ending_sequence_number`. +1. **Pre-CAS Shard Provisioning & Pre-Close Roll-Forward (`extenddb_storage::stream_lineage`):** Each stream enablement (`CreateTable` or `UpdateTable`) allocates a monotonic stream label via `stream_lineage::next_stream_label` and pre-creates `SHARDS_PER_STREAM` (`4`) open `ShardMeta::new_open` rows (`00..03`) at `stream_shard:` **before** publishing `latest_stream_label` in `table_meta` via `Catalog::mutate_json_cas` (cleaning up orphaned pre-created shards if CAS loses a race). Conversely, disabling a stream calls `roll_forward_committed_txns_for_table` **before** closing shards (`close_shards_by_id` serializing under `shard_local_mutex` and using `O(1)` tail-probing `latest_sequence_for_shard` clamped at `ending_sequence_number` via `advance_shard_cursor_if_open` rather than scanning every historical record), `streams::write_record_ordered_at` persists `stream_dedup` markers before atomically verifying `ShardMeta` remains open via `advance_shard_cursor_if_open` (`Catalog::mutate_json_cas`—deleting any unexposed record/dedup slot `> ending_sequence_number` and returning `Ok(None)`), `streams::ensure_shard_past_record` uses the same `advance_shard_cursor_if_open` fence during retention pruning so expired post-seal orphans never advance `ShardMeta.last_sequence_number` past `ending_sequence_number`, and `StreamEngine::get_stream_records` and `StreamEngine::first_sequence_number_at_or_after` clamp both `scan_str_range` bounds and returned records at `ending_sequence_number`. 2. **Contention-Resilient Single-Item Serialization (`sgl-` Prefix):** Single-item fenced writes serialize same-process contention per `(data_table, row_key)` via an async mutex and tag their coordinator IDs with `sgl-` so cross-process single-item contenders wait and retry cooperatively rather than aborting unconditional writes with `TransactionConflictException`. -3. **Contiguous Per-Shard Sequence Slot Append & Bounded Range Reads (`streams.rs`):** Phase 1 constructs each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER`, its `ParticipantRow`, and `:` `dedup_key`. During Phase 2 (`streams::write_record_ordered`), the writer reads the existing `ShardMeta` (no clock-based sequence fallback), checks `stream_dedup::`, formats `slot_seq = slot_sequence_number(shard_id, slot)`, claims `stream_record::` via `Catalog::put_if_absent` (setting `dynamodb.size_bytes` via `item_size_bytes`), persists `stream_dedup`, and advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS. `StreamEngine::get_stream_records`, `cleanup_expired_stream_records`, and `cleanup_expired_idempotency_tokens` all page through `Catalog::scan_str_range` with server-side `StartKeyOpen`/`StartKeyClosed`, `EndKeyOpen`, and bounded `rows_limit` rather than prefix-scanning entire shards or tables into memory. +3. **Contiguous Per-Shard Sequence Slot Append, `AT_TIMESTAMP` Seeks & Bounded Range Reads (`streams.rs`):** Phase 1 calls `streams::build_record_with_timestamp` (taking a single UTC clock read via `current_stream_clock` so `ApproximateCreationDateTime` and `created_at_ms` always agree) to construct each `TxnStreamRecord` with `UNASSIGNED_SEQUENCE_NUMBER`, its `ParticipantRow`, `:` `dedup_key`, and `created_at_ms`. During Phase 2 (`streams::write_record_ordered_at`), the writer reads the existing `ShardMeta` (no clock-based sequence fallback), checks `stream_dedup::`, formats `slot_seq = slot_sequence_number(shard_id, slot)`, claims `stream_record::` via `Catalog::put_if_absent` (setting `dynamodb.size_bytes` via `item_size_bytes` and persisting top-level `created_at_ms`, or deriving `ApproximateCreationDateTime * 1_000` for direct `write_stream_record` callers without a second clock read; wire `StreamRecord` deserialization drops the extra field cleanly via `decode_stored_record`), persists `stream_dedup`, and advances `ShardMeta.next_seq_num` / `last_sequence_number` via CAS. `StreamEngine::first_sequence_number_at_or_after` (`first_sequence_number_at_or_after_paged`, 512 rows/page) pages `stream_record::*` in ascending sequence-number order via `Catalog::scan_str_range` (bounded at `ending_sequence_number` when closed), returning the lowest qualifying sequence number (`created_at_ms >= at_ms`, falling back to `ApproximateCreationDateTime * 1_000` on legacy rows) even under non-monotonic clocks. `StreamEngine::get_stream_records`, millisecond-precision `cleanup_expired_stream_records`, and `cleanup_expired_idempotency_tokens` all page through `Catalog::scan_str_range` with server-side `StartKeyOpen`/`StartKeyClosed`, `EndKeyOpen`, and bounded `rows_limit` rather than prefix-scanning entire shards or tables into memory. #### B. Why the `__extenddb_catalog__` Table Ledger Beats Cloud Bigtable Native Change Streams Cloud Bigtable native Change Streams (`ReadChangeStream`) were evaluated and rejected in favor of the coordinator-fenced `__extenddb_catalog__` stream ledger for five reasons: lack of `__extenddb_txn_log__` 2PC commit gating, cell-level deltas lacking pre-image `StreamViewType` reconstruction, dynamic tablet-split continuation tokens incompatible with DynamoDB `ShardIterator` and `u128` `SequenceNumber`s, missing TTL `Service` `UserIdentity` metadata, and lack of `cbtemulator` support. @@ -219,12 +219,12 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept | `DataEngine` | Mandatory (Data Plane) | Implemented | `src/engine.rs`, `src/data/` | Unified OCC CAS `PutItem`/`UpdateItem`/`DeleteItem` with statement/item-size checks, pre-commit digest-bounded GSI/LSI shadow key validation, chunked `<= 90,000`-mutation writes, durable `post-*` side-effect recovery, read-through `GetItem`, explicit-`is_index` `Query`/`Scan`, incarnation-fenced 2PC `TransactWriteItems`, double-read `TransactGetItems` | | `VectorSearchEngine` | Optional (`as_vector_search`) | Opted out (`None`) | `src/engine.rs` | Engine capability gate rejects `VectorIndexes` DDL and `SearchVectors` | | `MetadataEngine` | Optional (TTL & Tags) | Implemented | `src/engine.rs`, `src/ttl_worker.rs` | CAS resource tagging + 16-shard `__extenddb_ttl_index__` with `ENABLING` base-table backfill (`create_ttl_index`), `drop_ttl_index`, and no-op `refresh_table_size` | -| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item (`sgl-*`), TTL, and 2PC streams; pre-created 4-shard `ShardMeta`, closed-shard write suppression, `O(1)` tail sequence lookup, contiguous `put_if_absent` slots, bounded `scan_str_range` reads & retention GC | +| `StreamEngine` | Optional (Streams) | Implemented | `src/engine.rs`, `src/streams.rs` | Fenced write-ahead single-item (`sgl-*`), TTL, and 2PC streams; pre-created 4-shard `ShardMeta`, closed-shard write suppression, `O(1)` tail sequence lookup (`latest_sequence_for_shard` fenced via `advance_shard_cursor_if_open`), contiguous `put_if_absent` slots, millisecond-precision `first_sequence_number_at_or_after` (`AT_TIMESTAMP`) seeks, bounded `scan_str_range` reads & millisecond retention GC | | `WorkerStore` | Optional (Lifecycle) | Implemented | `src/engine.rs` | Inline `ACTIVE` table creation (`process_control_plane_transitions` no-op) | | `SnapshotEngine`, `BackupCatalog`, `LegacyBackupReader`, `RestoreEngine` | Optional (Backup/Restore) | `CreateBackup` Refused / Empty Catalog | `src/backup_stubs.rs` | `CreateBackup` returns `StorageError::Unsupported` (`ValidationException`); `ListBackups` returns `[]`; `DescribeBackup`/`DeleteBackup`/`RestoreTableFromBackup` return `BackupNotFoundException` | | `ManagementStore`, `AdminStore`, `PasswordHashStore` | Mandatory (IAM & Admin) | Implemented | `src/catalog_store.rs` | Accounts, admins, IAM principals/policies/boundaries/tags, STS sessions, CAS password hashes, `SecretKeys` KEK/DEK paging & rotation | | `AuthorizationStore` | Mandatory (Authz) | Implemented | `src/catalog_store.rs` | User/group/role policies, permission boundaries, resource/principal tags, RFC 3339 `created_at` | -| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, `catalog_version` lookup, CAS SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, catalog + `data_instance_id` diagnostics | +| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, `catalog_version` lookup, CAS SHA-256 dimension metrics accumulation/pruning, failed-login rate-limit store, catalog + `data_instance_id` diagnostics (`check_storage_relations` / `drop_orphaned_relations` inherit default `DiagError::Unsupported`, matching SQLite/MongoDB/Cassandra) | | `CredentialStore` | Mandatory (`SigV4` Auth) | Implemented | `src/catalog_store.rs` | `AKIAEXTENDDB*` + `ASIAEXTENDDB*` `SecretKeys` decryption with `SecretRow` AAD, `ExpiredTokenException`, inactive-key S-5 propagation, and redacted fail-closed `InternalServerError` on corrupt/unreadable secrets | | `Bootstrapper` | Mandatory (`extenddb init`) | Implemented | `src/bootstrapper.rs` | `create_catalog_db`, `init_target`, `hold`, `bootstrap_encryption_key` (`CATALOG_KEY_SETTING`), `bootstrap_default_account`, `bootstrap_admin_user`, and catalog-scoped `drop_databases` preserving non-ExtendDB tables | | `CatalogMigrations` & `MigrationBackend` | Mandatory (`extenddb migrate`) | Implemented | `src/migrations.rs`, `src/m0001_baseline.rs` | `MigrationId::Baseline` (`Kind::Breaking`: `M0001CatalogBaseline` + `M0001DataBaseline`) + `2..=12` (`NotApplicable`), pinned SHA-256 baseline checksum, renewed `lock:catalog_migrations` lease, and `wait_for_servers` fence | @@ -239,8 +239,8 @@ Per [RFC-0002](0002-backend-plugin-policy.md) and [RFC-0003](0003-backend-accept * Monotonic millisecond-aligned OCC version generation (`next_occ_version`, `version_to_timestamp_micros`, `next_millis_exclusive`), single-`SetCell` 50,000-attribute shadow put sizing (`shadow_put_50k_attributes_fits_within_single_check_and_mutate_row`), `reclaim_version_only_row` conflict filter construction, `parse_ttl_epoch_secs` decimal/zero/negative parsing, wall-clock-free intent filters, incarnation-fenced 2PC predicates, startup `validate_app_profile_proto` routing checks (`admin.rs`), `BIGTABLE_EMULATOR_HOST` config resolution (`config.rs`), multi-frame `ReadRowsAssembler`, `x-goog-request-params` header formatting, and gRPC `Internal` vs. `Transient` error classification (`client.rs`), redacted fail-closed `lookup_credential` (`catalog_store.rs`), `CreateBackup` refusal vs. empty-catalog `ListBackups`/`DescribeBackup`/`DeleteBackup`/`RestoreTableFromBackup` (`backup_stubs.rs`), and `migration_table_covers_all_ids_and_refuses_additive` (`migrations.rs`). 2. **Live Bigtable Emulator Integration & Conformance Suite (`cargo test -p extenddb-storage-bigtable --features test-hooks --test emulator_integration -- --nocapture` against `cbtemulator`, gated via `EXTENDDB_TEST_BIGTABLE_REQUIRED=1`):** * Catalog + split `data_instance_id` baseline migrations (`__extenddb_catalog__`, `__extenddb_data_ledger__`, `__extenddb_txn_log__`, `__extenddb_ttl_index__`), renewed `lock:catalog_migrations` + `ServingRegistration` fencing, and `drop_databases` preservation of foreign tables alongside base/GSI/LSI cleanup. - * Exact 5-item `[a, ab, b, ba, c]` base sort-key range queries, 2,048-byte partition-key GSI round-trips and pre-commit `> 4,096`-byte multi-RANGE rejection, GSI sharing the base table's key schema, and ordered LSI shadow-table `Query`/`Scan`/projections. - * Read-through `GetItem`, `Query`, and `Scan` plus double-read `TransactGetItems` on `COMMITTED` unapplied intents, multi-table `roll_forward` when one table was deleted, `post-*` side-effect replay, version-only `tomb:` row reclamation after grace expiry, pre-CAS stream shard creation & pre-close roll-forward, `CREATING`-only leased GSI builds, and TTL `ENABLING -> ENABLED` pre-existing item backfill + `<= 4,096`-byte SHA-256 digest eviction + preservation while `DISABLED`. + * Exact 5-item `[a, ab, b, ba, c]` base sort-key range queries, `begins_with` (forward, reverse, and `Limit = 1` pagination) and `BETWEEN` near `U+10FFFF` and binary `0xFF` across base tables, GSIs, and LSIs, 2,048-byte partition-key GSI round-trips and pre-commit `> 4,096`-byte multi-RANGE rejection, GSI sharing the base table's key schema, and ordered LSI shadow-table `Query`/`Scan`/projections. + * Read-through `GetItem`, `Query`, and `Scan` plus double-read `TransactGetItems` on `COMMITTED` unapplied intents, multi-table `roll_forward` when one table was deleted, `post-*` side-effect replay, version-only `tomb:` row reclamation after grace expiry, pre-CAS stream shard creation, pre-close roll-forward, millisecond-precision `AT_TIMESTAMP` seeks (including cross-shard isolation, backward clock steps, legacy whole-second fallback, multi-page cursor advancement, `ending_sequence_number` fencing on `first_sequence_number_at_or_after` and `latest_sequence_number`, and millisecond `cleanup_expired_stream_records` retention + closed-shard orphan pruning), `CREATING`-only leased GSI builds, and TTL `ENABLING -> ENABLED` pre-existing item backfill + `<= 4,096`-byte SHA-256 digest eviction + preservation while `DISABLED`. * Shared backend conformance suites: `iam_leftovers_conformance::run`, `metrics_conformance::run`, and `key_conformance::run`. 3. **End-to-End Wire & Catalog-Lock Conformance (`devtools/run-bigtable-tests`, `devtools/check-bigtable-catalog-lock`):** * Wire-level Rust (`--rust`, `--rust-integration`) and Python (`--pytest`, `--comprehensive`) conformance suites executed via `devtools/run-tests --extenddb --backend bigtable` against an `extenddb` binary built with `--no-default-features --features bigtable` backed by `cbtemulator`, plus `devtools/check-bigtable-catalog-lock` exercising `init`, `migrate`, `verify`, `serve`, `backup`, `SIGKILL` lease expiry, and `SIGSTOP` registration-loss shutdown.