diff --git a/docs/rfcs/0000-bigtable-backend.md b/docs/rfcs/0000-bigtable-backend.md new file mode 100644 index 000000000..936b5661a --- /dev/null +++ b/docs/rfcs/0000-bigtable-backend.md @@ -0,0 +1,265 @@ +# RFC-0000: 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 an **Experimental** Google Cloud Bigtable storage backend (`crates/storage-bigtable`) for ExtendDB `v1.1.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 + +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, 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, 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__` 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`), 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. + +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`). 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. 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`. +* **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 + 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])? + ``` + * **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:** `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::`, where `token` is the engine's escaped stored form) 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`, `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. +* **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 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 / 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 + C->>B: place_intent_once (CheckAndMutateRow: fail if any m:intent:* exists; cooperatively resolve stale/COMMITTED) + end + 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 (CancellationReason::transaction_conflict) + end + C->>B: Read locked participant rows & capture OCC versions (m:v) + 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: 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; 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 & 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) + loop Each locked participant + 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 +``` + +#### C. Read Isolation, Cooperative Read-Through & `TransactGetItems` Double-Read Snapshot +* **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. +* **`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, 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)` + * `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` + * `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 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 +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), 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 (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 + +#### 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` 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, `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. + +### 4. Scalable TTL Indexing, `ENABLING` Backfill & Fenced Expiration + +#### A. Sharded TTL Index Schema & `ENABLING -> ENABLED` Backfill +* **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 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 + +* **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"`), `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 + +```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" # 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 (or BIGTABLE_EMULATOR_HOST) +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 +``` + +* **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`. + * Transport connection failures map to `StorageError::Connection`. + * 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, Restore, Export, Point-in-Time Recovery & Table Size Statistics + +* **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 ExtendDB `v1.1.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` (`PROVISIONED` default billing, pre-companion stream-state check & refused-disable shard-close non-commit, 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 (`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, `O(1)` access-key-indexed `fetch_session_data` (`iam_session_ak:` -> `iam_session:`, including expired sessions), and RFC 3339 `created_at` | +| `SettingsStore`, `MetricsStore`, `RateLimitStore`, `DiagnosticsStore` | Infrastructure / Management | Implemented | `src/catalog_store.rs` | CAS `replace_setting`, default lock-free `get_setting_bounded`, `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, 4 KiB key-length bounds, `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` (`write_bootstrap_rows` environment-variable handling), 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`, 1h `stream_record_cleanup` [24h retention], 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`). + * 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`), `decode_session_data_for_key` + 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, `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, escaped `ClientRequestToken` NUL/backslash/UTF-8 replay & non-collision, 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-companion stream-state refusal, 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`, `session_data_conformance::run`, `metrics_conformance::run`, and `key_conformance::run`) and `write_bootstrap_rows` admin environment-variable matrix coverage. +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 + +* **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. + +--- + +## 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 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.