Skip to content

docs: add RFC draft for Cloud Bigtable storage backend - #186

Open
annguy3n wants to merge 12 commits into
ExtendDB:mainfrom
annguy3n:rfc/bigtable-backend
Open

annguy3n wants to merge 12 commits into
ExtendDB:mainfrom
annguy3n:rfc/bigtable-backend

Conversation

@annguy3n

Copy link
Copy Markdown

What

This PR introduces the draft design for the Cloud Bigtable storage backend (RFC-0003).

Key design highlights include:

  • Lock-then-Read 2PC Flow
  • Single-Row Write Guarding
  • Transactional Streams
  • Sharded TTL Index shadow table
  • GSI Validation and Reconciler
  • Secure Credentials Path

Why

Cloud Bigtable is GCP's managed wide-column store and serves as the natural target for DynamoDB workloads migrating to GCP. A robust connector allows AWS-to-GCP migration for high-throughput, low-latency applications with zero code changes.

Checklist

ADR / RFC: #185


By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.

@annguy3n
annguy3n force-pushed the rfc/bigtable-backend branch 2 times, most recently from 88190c4 to e0d1d91 Compare June 29, 2026 20:07
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator

Thank you for this RFC. At a quick glance, this looks solid. Let me do a thorough review and circle back to you early next week (week commencing 6 July).

@LeeroyHannigan LeeroyHannigan added the RFC Request for Comments, a proposal open for discussion before implementation label Jul 3, 2026
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator

Thanks for the detailed RFC, @annguy3n this is a strong design and we're happy to accept a Cloud Bigtable backend on these lines. You've clearly thought hard about the DynamoDB semantics: the lock-then-read 2PC, single-row write guarding, stream replay via the txn log, and the sharded TTL index are exactly the right calls given Bigtable's single-row atomicity.

A few DynamoDB-parity points to fold in, split into what must match vs. what's fine to differ if documented:

Must match DynamoDB

  • TTL + Streams: the TTL sweeper's deletes must emit DynamoDB-compatible REMOVE stream records (with the TTL principal) when streams are enabled, please make that explicit in the design, since silently dropping them is a breaking behavior gap.

  • Key encoding: DynamoDB sorts Number keys numerically (exact to 38 significant digits) and String/Binary keys by byte order. In a byte-lexicographic store that means numeric keys need an order-preserving byte encoding, and numbers must round-trip as exact decimals (not floats). This currently only shows up under Testing but it's a core design detail and should be promoted into the row-key format and GSI index-key sections.

  • Transaction rules: TransactWriteItems needs ClientRequestToken idempotency (10-minute window) and must reject two operations on the same item, worth noting alongside the 2PC flow.

  • Read isolation: DynamoDB gives read-committed for GetItem/Query/Scan/BatchGetItem and serializable for TransactGetItems. Two things fall out of the 2PC apply window: (1) a row's new value must not be visible until the transaction's commit point, applying mutations before the commit decision is durable would expose a write that can still roll back, which is a dirty read and breaks read-committed; and (2) TransactGetItems must observe the committed set atomically (read through the coordinator / at the commit boundary), otherwise it can see partial state and violate serializable. Please spell out how both are guaranteed.

Fine to differ, just call it out

  • GSI consistency: shadow tables make GSIs eventually consistent, which matches DynamoDB, good. Please still reject ConsistentRead=true on a GSI (API parity), and make sure the reconciler keeps GSI reads from returning orphaned/phantom rows during the divergence window.

  • Cross-row visibility for standard reads: during the apply window a Query/Scan may see some rows of a committed transaction updated and others not. That's within read-committed (each row still returns a committed value), so it's fine, just document it, and confirm the read-committed and TransactGetItems guarantees above hold.

  • Backup / PITR / export: not covered here, fine to defer to a follow-up RFC, but let's note that the effective PITR/export window will differ from DynamoDB's 35 days.

Overall: accepted in principle, let's tighten the TTL-stream path, key-encoding, and the read-isolation guarantees in the doc, then move to implementation behind the opt-in feature. Really nice write-up.

@annguy3n
annguy3n marked this pull request as ready for review August 11, 2026 13:14
@annguy3n

Copy link
Copy Markdown
Author

@LeeroyHannigan Thanks for the feedback, I've updated the RFC to address them. Let me know if you have any other questions/comments.

@annguy3n
annguy3n force-pushed the rfc/bigtable-backend branch 2 times, most recently from 0a09a0f to aa6a7a5 Compare August 12, 2026 15:21
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator

Hi @annguy3n ,

Thanks for the update to the RFC, please find below my findings

Blocking

B1. Internal phase-numbering is self-contradictory. The 2PC mermaid in 2.B defines exactly three labeled phases (Phase 1 Open, Phase 2 Commit, Phase 3 Clean up), with intent placement and data apply as unlabeled steps. But the prose references non-existent/contradictory phases: 2.C says intents are written in "Phase 3" (the diagram's Phase 3 is Clean up) and data is applied "only in Phase 7"; 3 says log enrichment in "Phase 2" and stream records written in "Phase 5"; the recovery sweeper (2.E) and streams (3.4) roll forward against these. There is no Phase 4–7 anywhere. This must be reconciled to a single consistent phase list before implementation, because the commit/visibility ordering (see B2) hinges on which phase is the durable commit point.

B2. TransactGetItems serializable guarantee is asserted but the mechanism is missing. 2.C claims TransactGetItems "coordinates with __extenddb_txn_log__ to observe the snapshot at the transaction commit boundary." No snapshot/MVCC mechanism is specified. The design keeps a single committed value per row in family d (mutations applied post-commit), and Bigtable cell timestamps are per-row, not a global read timestamp, so there is no described way to obtain a cross-row atomic snapshot at a commit boundary. As written this reads as read-committed, not serializable. Either specify the mechanism (e.g. read-through-log to reconstruct pre/post images, or a commit-timestamp read) or downgrade the claimed guarantee.

Non-blocking

N1. Commit-point vs client-ack visibility gap (needs to be pinned down). 2.C states data in d is applied only after COMMITTED is durable, and the sweeper rolls forward on crash. It never states when success is returned to the client. If the coordinator acks at the durable-COMMITTED point but applies to d afterward, a strongly-consistent GetItem/Query issued between ack and apply returns the pre-transaction (still-committed) value. DynamoDB reflects a succeeded TransactWriteItems in a subsequent strongly-consistent read. Read-committed per-row is preserved, but read-your-writes after a 200 is not, unless the client ack is deferred until apply completes. State the ack point explicitly.

N2. GSI row-key delimiter contradicts the string-key encoding rule. 1.B first says String/Binary keys use "null-byte / length-prefixed terminators to preserve lexicographical sort order," then defines the GSI shadow row key as [pk_val]\0[sk_val]\0[base_pk_val]\0[base_sk_val] — bare \0 separators. DynamoDB String/Binary values can contain 0x00 bytes; bare-\0 delimiting breaks both uniqueness and sort parity when a value embeds a null, and is inconsistent with the length-prefixed scheme stated one paragraph earlier. Use the same length-prefixed/order-preserving composite encoding for the GSI key.

N3. Trait name is stale vs main. 5.B says the reconciler is "spawned via RuntimeHooks." The actual trait is ServerRuntimeHooks with async fn spawn_workers(&self, ctx: &WorkerContext) at crates/storage/src/hooks.rs:47,58; postgres/sqlite/mongodb all implement it (crates/storage-postgres/src/lib.rs:376, crates/storage-sqlite/src/hooks.rs, crates/storage-mongodb/src/lib.rs:50). Align the name so the RFC points at the real extension surface (TTL/GSI/recovery workers should all register through spawn_workers).

Notes (positive / low-risk)

  • Config shape is consistent with repo convention: [storage] backend = "..." selects the backend and backend tables are [storage.<name>] (crates/config/src/lib.rs:186), so [storage.bigtable] with pool_size = 20 matches the existing postgres default. Good.
  • The design is docs-only and adds no code; it does not touch or break any current subsystem (backends on main: postgres, sqlite, mongodb; no bigtable dir).
  • Core-level operations the RFC leans on already exist, so the Bigtable work is a backend implementation of established contracts, not new surface: TransactWriteItemsInput/ClientRequestToken (crates/core/src/types/transaction.rs:83-89), IdempotentParameterMismatch (crates/core/src/error/mod.rs:37), transact_write_helpers.rs.

Thanks again, looking forward to seeing your implementation of Bigtable here.

@annguy3n
annguy3n requested a review from robinnsc as a code owner August 20, 2026 18:20
@annguy3n

Copy link
Copy Markdown
Author

@LeeroyHannigan, would you mind to take another pass at it?

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator

Hi @annguy3n,

Third pass done. B1 (phase numbering), N2 (bare-\0 delimiters), and N3 (ServerRuntimeHooks::spawn_workers) are all cleanly resolved, and the new material is strong - the fenced apply, OCC versioning, GC rules, and the app-profile constraint are all accurate against Bigtable's actual behavior. One new blocking item, unfortunately introduced by the N2 fix itself, plus two carry-overs.

Blocking

B3. The GSI composite key has a non-terminal raw sort-key segment (1.B, GSI Index Row Keys). gsi_sk_bytes is raw and unterminated, but the base key follows it, so the byte after a short sort key is base_pk_tag (0x53), which participates in comparisons. Two proven consequences (simulated the byte layout directly): (1) sort inversion - for the same gsi_pk, sort key "A" orders after "AB" because 0x53 > 0x42, breaking GSI Query ordering, begins_with, and between; and (2) the segment boundary is undecodable - I constructed two distinct (gsi_sk, base_pk) pairs with byte-identical row keys, which breaks uniqueness and the reconciler's parsing. Raw-to-end-of-key is only safe for the terminal segment (the base composite key gets this right). Suggested fix: escape-encode the non-terminal gsi_sk segment order-preservingly (0x00 -> 0x00 0xFF, terminate with 0x00 0x00 - the FDB tuple pattern); base_sk stays raw since it is terminal. This is the same inversion class your Alternatives section rejects for length prefixes, one level down.

Should-fix

B2 (carry-over, much improved). The mutation payloads stored in the coordinator row at COMMITTED (section 3) now make the serializable TransactGetItems claim mechanically achievable - but 2.C still says "coordinates with the txn log to observe the snapshot" without stating the rule. One paragraph closes it: intent present + txn COMMITTED -> serve the logged post-image; intent present + txn PENDING -> serve the current d value (apply cannot have started).

N1 (carry-over). The success ack point is still unstated - failure paths return TransactionConflict/Canceled, but nothing says whether the client's 200 comes after COMMITTED is durable or after fenced apply completes. Read-your-writes on a subsequent strongly-consistent read hinges on it; one sentence in 2.B or 2.C.

Nit

The OCC existing-row predicate is written as (no active intent) AND (m:v == v) with true_mutations; Bigtable filters have no NOT, so that literal form isn't expressible. The equivalent De Morgan form (intent-exists OR m:v != v as an interleave, mutations in false_mutations) is - and your insert case already uses that trick. Worth stating so the implementer doesn't hit the dead end.

Close on B3 and the two paragraphs and this is ready to land as an accepted RFC from my side. The design has gotten genuinely tight across the three rounds.

@annguy3n

Copy link
Copy Markdown
Author

Hi @LeeroyHannigan,

Thanks again for the thorough review! We have updated both the RFC (docs/rfcs/0000-bigtable-backend.md) and the reference implementation to close on all 4 items:

1. B3: FoundationDB Tuple Escape-Encoding for Non-Terminal GSI Sort Keys (§1.B)

  • Encoded non-terminal gsi_sk segments using FDB tuple order-preserving escape encoding: each 0x00 is escaped as 0x00 0xFF, and the segment is terminated with 0x00 0x00 (terminal base_sk remains raw bytes to end-of-key).
  • Completely eliminates sort inversion (e.g. "A" vs "AB") and ensures unambiguous, reversible segment boundaries for GSI shadow key decoders and the background reconciler.

2. B2: Explicit TransactGetItems Read-Through-Log Snapshot Rule (§2.C)

  • Codified the exact snapshot resolution rule when an active intent marker (m:intent:<txn_id>) is encountered:
    • Txn COMMITTED: Serves the logged post-image from __extenddb_txn_log__ coordinator mutation payloads.
    • Txn PENDING: Serves the pre-transaction value from family d (apply has not started).
    • No active intent / CLEANED: Serves family d directly.

3. N1: Success Acknowledgment Boundary (§2.B & §2.C)

  • Explicitly specified in the text and Mermaid sequence diagram that HTTP 200 OK is returned to the client after all Phase 2 fenced mutations are durably applied to column family d and GSI shadow tables, guaranteeing monotonic Read-Your-Writes consistency.

4. Nit: De Morgan Form for Bigtable OCC CAS Predicates (§2.D)

  • Documented that because Bigtable row filters lack a NOT operator, OCC CAS predicates use the equivalent De Morgan conflict form: (active intent in m) OR (m:v != read_version) via RowFilter::Interleave with mutations placed in false_mutations.

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator

Hi @annguy3n,

Thanks for the quick turnaround on pass three, all previous points are cleanly resolved.

Before anything else, an apology: some of the items below existed in the first draft and should have been caught in my first pass rather than trickling out over four rounds. To close this out fairly, I did a full front-to-back review of the RFC against the Bigtable documentation, and I also checked out your feat/bigtable-backend branch, built it, and ran the emulator integration suite against a live Bigtable emulator.

The good news first: formatting is clean, clippy has zero errors, the feature-gating is exactly right (the default binary builds without the crate), all 44 unit tests pass, and 5 of 7 emulator integration tests pass. The 2PC design held up well under a hard look.

Three items block acceptance, all confirmed in the branch:

  1. Cell timestamps vs MaxVersions(1). Every SetCell uses timestamp_micros: -1, so when two writers pass their filters in a narrow window, GC keeps the cell with the later wall clock, not the higher OCC version, and because timestamps are per-cell the row can end up torn (one writer's data, the other's m:v). The emulator can't surface this (single node, single clock). Deriving the timestamp from the OCC version so all cells of one write share it makes GC deterministic.

  2. Single-item stream emission is unfenced. put/update/delete_item and the TTL sweeper write the base row, then streams::emit as a trailing write; a crash between them loses the stream record. Your 2PC path already solves this correctly by persisting stream_records in the coordinator row before commit, so the pattern exists in your own code, it just needs to cover the single-item paths.

  3. test_transact_get_items_read_through_log_rule fails against a live emulator: TransactGetItems returns the pre-image (initial1) instead of the committed post-image. Worth a look, this one is your own test.

Handled by the rebase you'll need anyway (the branch is 84 commits behind and Cargo.lock, the workspace Cargo.toml, and extenddb.sample.toml will conflict): main now has a StorageError::Unsupported variant, which is what the BackupEngine stubs should return instead of Internal (Internal maps to HTTP 500 plus error logs; Unsupported maps to ValidationException). Please also update the RFC text to match, and keep the title at RFC-0000 until a number is assigned at acceptance, since 0003 is already referenced in shipped code.

Everything else I found (deliverables matrix, clippy warnings under -D warnings, transient-error classification, a line on why the table ledger beats change streams) is non-blocking and fine for the implementation PR. With the three items above addressed and the rebase done, we'd love to see your code in a PR.

Thanks for your patience across the rounds, the quality of this contribution is excellent and we're really looking forward to supporting it as a 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.
- 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.
…coding, TransactGetItems rule, and ack boundary
…ced streams, Unsupported stubs, and deliverables matrix
@annguy3n
annguy3n force-pushed the rfc/bigtable-backend branch from 88a7659 to 0632fbd Compare November 19, 2026 02:19
@annguy3n
annguy3n requested a review from eliseong as a code owner November 19, 2026 02:19
@annguy3n

annguy3n commented Nov 19, 2026 •

Copy link
Copy Markdown
Author

Hi @LeeroyHannigan,

Thanks for the front-to-back review and live emulator run! Both rfc/bigtable-backend and feat/bigtable-backend are rebased onto main (v1.0.0) with all items resolved:

  1. Deterministic OCC Cell Timestamps (§2.D): Replaced timestamp_micros: -1 with millisecond-aligned timestamps derived from a hybrid monotonic OCC version (timestamp_micros = v * 1_000) shared across d:*, m:v, and GSI shadow cells, plus monotonic m:v tombstones on DeleteItem so MaxNumVersions(1) compaction cannot produce torn rows.
  2. Fenced Single-Item & TTL Streams (§3.A, §4.B): Routed stream-enabled PutItem/UpdateItem/DeleteItem and ttl_worker (dynamodb.amazonaws.com Service UserIdentity + #ttl = :ttl_exp guard) through the __extenddb_txn_log__ COMMITTED write-ahead fence with deterministic stream_record:<shard_id>:<seq_26> keys for idempotent crash roll-forward.
  3. Live Emulator Suite (§2.C, §5): Fixed test_transact_get_items_read_through_log_rule by adding CellsPerColumnLimitFilter(1) and rank-ordered timestamps on __extenddb_txn_log__ reads (preventing pre-compaction PENDING cells from shadowing COMMITTED), plus a cbtemulator fallback for reversed: true scans.
  4. Rebase, StorageError::Unsupported, & RFC Updates (§3.B, §6–§8): Adapted to v1.0.0 traits, switched backup/snapshot/restore stubs to StorageError::Unsupported, kept the # RFC-0000 title, and added the Change Streams vs. catalog ledger rationale, transient gRPC error mapping, and Deliverables Matrix.

Verified on rebased feat/bigtable-backend: cargo fmt --check, cargo clippy --all-targets -- -D warnings, 55/55 unit tests, and 14/14 live cbtemulator integration/conformance tests pass.

Implementation PR is now open at #1154.

@annguy3n

annguy3n commented Nov 19, 2026 •

Copy link
Copy Markdown
Author

@LeeroyHannigan the pass-4 items are in 0632fbd, summarized in my comment above. 1150651 then updates the RFC for a later change to the implementation (44f067f), which is described in #1154. CI on this PR is also waiting for approval.

Two corrections to what I have written here:

  • The test counts in my comment above (55 unit, 14 emulator) are for the tree before 44f067f. Current numbers, and what has not been run, are in the feat(bigtable): add Google Cloud Bigtable storage backend #1154 description. The wire-level conformance suites from RFC-0003 are among the things not run.
  • 1150651 also added a model-checking item and some internal labels to the Testing Strategy section. They refer to material that is not in this repository, so I will remove them in a follow-up commit.

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read this against the implementation in #1154 at 44f067f. The three pass-4 items hold there. Every cell timestamp comes from the OCC version, and single-item writes and the TTL worker write their stream records through the transaction log. test_transact_get_items_read_through_log_rule passes on the emulator.

Since my last pass, the RFC has become a description of the backend as built. It "implements the full ExtendDB v1.0.0 backend surface", and each row of section 8 says Implemented. RFC-0003 §6.3 asks an RFC not to present a mechanism as working unless it is in the live code path. Parts of the new text don't match the code, so before it merges:

  1. Section 8 says the bootstrapper works through catalog_key_present and data_connection_present (line 241). Neither is a function in the crate. catalog_key_present is a field of the shared key status report, and data_connection_present exists nowhere in the tree.
  2. Section 8 marks CatalogMigrations and ServerRuntimeHooks as Implemented, with a lock:catalog_migrations lease (lines 242 and 244). In the crate nothing renews the lease, a fresh catalog takes no lock row, and serve takes no serving registration and reads no catalog status.
  3. Section 6 says migrations 2 to 12 are recorded under the lock, and that m0001_baseline provisions the transaction log and the TTL index (line 212). Migration 1 is Kind::Breaking. With data_instance_id set, the engine uses a transaction log and a TTL index on the data instance that no migration creates.
  4. Section 1.B describes a GSI key of one HASH and one RANGE segment, but since #429 main's GSIs take several of each. Section 2.D says version-guarded shadow updates never leave a stale entry. But when the delete of the old entry fails, the engine only logs it and the write succeeds (engine.rs:963-970 in #1154).
  5. Section 7 no longer mentions export. The August text noted it, as my 7 July review asked. On this backend, as on the others, ExportTableToPointInTime is a paged Scan with no point in time, and section 7 should say so.
  6. The Motivation says the design solves out-of-order shard visibility in streams and the online GSI build (items 4 and 6). In #1154 at 44f067f these don't hold yet. A stream record written before its shard row exists gets a clock-based sequence number that sorts after later records. A reader of that shard then gets nothing more. A new GSI can go ACTIVE without the writes of a node that hadn't seen the index yet. My review of #1154 has the detail. The RFC shouldn't claim these as solved until the code solves them.
  7. Testing Strategy 3 names TLC model checking, but no TLA+ spec or config is in the tree. You've said you'll delete it, which covers this.

These were in the text at my last pass, so they aren't conditions, but please fix them in the same change:

  • The summary calls the backend production-grade (line 10). The crate's description and the sample config call it experimental, and README.md:53 defines Experimental as not for production use. 139 of our 1,388 wire tests fail on it today. Please state the tier as Experimental.
  • On 21 August I called the app-profile text accurate, and one part isn't. Section 2.E says CheckAndMutateRow needs single-cluster routing "or multi-cluster routing with single-row transactions enabled". The API offers single-row transactions only on single-cluster routing. Nothing checks the app profile at startup either.
  • The TTL index design has no step that indexes the items written before TTL is enabled, so TTL never deletes them. #1154 needs one, and the RFC should describe it.

The RFC also doesn't mention dev_mode, which gives any user named __dev_admin__ allow-all in a production build (catalog_store.rs:2650-2656 in #1154). I've asked #1154 to delete that code path. If it stays, section 6 should describe it.

On the process: I put the accepted label on with my 7 July "accepted in principle" comment, but the process in docs/rfcs/README.md hasn't run yet. There are no maintainer reviews and no final comment period, the file still says Status: Draft, and it has no number. #1154 carries a byte-identical copy of this file, so merging #1154 first would land it as 0000. I'd keep the file only in this PR, and have #1154 reference the RFC by number once this one merges.

… 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.
@annguy3n
annguy3n force-pushed the rfc/bigtable-backend branch from 1150651 to 0730036 Compare November 20, 2026 16:10
annguy3n added a commit to annguy3n/extenddb that referenced this pull request Nov 20, 2026
…artup notice, and drop duplicate RFC

- Share AKIAEXTENDDB/ASIAEXTENDDB key generators, self_service_policy, and string_coerce::u64 in extenddb-storage across all backends and crates/server.
- Report CreateBackup unsupported in startup logs and banner when built with the bigtable backend while keeping ListBackups/DescribeBackup/DeleteBackup/RestoreTableFromBackup empty-catalog semantics.
- Document bigtable feature in crates/bin while preserving default = ["postgres"].
- Remove duplicate docs/rfcs/0000-bigtable-backend.md from implementation branch so RFC PR ExtendDB#186 is the sole owner.
@annguy3n

annguy3n commented Nov 20, 2026 •

Copy link
Copy Markdown
Author

Thanks for the thorough review against #1154, @LeeroyHannigan! I've updated the RFC (4c02b8e, merged with main v1.1.0 at 222d80a and synced 1:1 with #1154 at 523548f and docs/differences-from-dynamodb.md) and removed the duplicate copy of docs/rfcs/0000-bigtable-backend.md from #1154 so this PR is the sole owner (Status: Draft, title kept at RFC-0000 until numbered on merge).

Summary of changes:

  1. §8 Bootstrapper (#1): Removed the nonexistent catalog_key_present / data_connection_present names and listed the live Bootstrapper methods (create_catalog_db, init_target, hold, bootstrap_encryption_key (CATALOG_KEY_SETTING), bootstrap_default_account, bootstrap_admin_user delegating to write_bootstrap_rows, drop_databases).
  2. §6 & §8 CatalogMigrations, LockedStores, AuthorizationStore, SettingsStore, DiagnosticsStore & ServerRuntimeHooks (#2): Matched #1154's v1.1.0 implementation of ADR-0023 — creating __extenddb_catalog__ before acquiring lock:catalog_migrations (60 s lease renewed every 15 s with TimestampRangeFilter and local deadline cancellation), flagging populated uninitialized catalogs as NeedsAttention via raw row-key sampling, lease-guarded LockedStores::management(), O(1) access-key-indexed AuthorizationStore::fetch_session_data (including expired sessions, with symmetric 4 KiB key bounds #1523), default SettingsStore::get_setting_bounded (#1449), DiagnosticsStore inheriting default DiagError::Unsupported for Postgres-only storage-relation checks, wait_for_servers, ServingRegistration (server_registration:<token>), startup Runner::status verification, and the 5 leased background workers (ttl_worker, sweeper, CREATING-only gsi_worker, 1h stream_record_cleanup [24h millisecond-precision retention], 10m idempotency_token_cleanup).
  3. §1.A, §6 & §8 Baseline migration & data_instance_id (#3): Documented MigrationId::Baseline (Kind::Breaking) split across M0001CatalogBaseline (StoreKind::Catalog on instance_id, single catalog per instance, per-row CAS-after monotonic catalog overwrites via compare_and_swap_raw_after) and M0001DataBaseline (StoreKind::Data on effective_data_instance_id: __extenddb_data_ledger__, __extenddb_txn_log__, __extenddb_ttl_index__), with migrations 2..=12 recorded as NotApplicable.
  4. §1.B Multi-attribute GSI/LSI keys & §2.A/§2.C/§2.D/§2.F read-through & shadow recovery (#4): Updated §1.B to 1..=4 HASH ([count:u32BE:4]([tag_i:1][len_i:4][bytes_i]){1..4}) and 0..=4 RANGE digest-bounded + FDB escape-encoded shadow keys (<= 4,096 bytes), updated §2.C to cover GetItem/Query/Scan committed-intent read-through (read-committed across rows on Query/Scan) and escaped ClientRequestToken stored forms (#1375), and synced §2.A/§2.D/§2.F/§4.A with #1154 (pre-execution-only retries on non-disambiguated CAS calls + t:open_nonce open disambiguation, coordinator-fenced > 90,000-mutation writes, backoff-journaled/buffered post-<uuid> recovery in __extenddb_txn_log__ + ensure_lsi_read_after_write before LSI reads, per-row non-starving tomb: GC, O(1) table_id_index: lookups, and <= 4,096-byte [0x44][SHA-256:32] + tv1: TTL entries).
  5. §7 ExportTableToPointInTime (#5): Restored the note that ExportTableToPointInTime executes as a synchronous paged Scan of the live table with no point-in-time snapshot.
  6. Motivation #4 & #6, §3.A, and §5 (#6): Synced with #1154's fixes — evaluating StreamSpecification transitions/refusals ahead of companion fields (#963), pre-creating all 4 ShardMeta rows before publishing latest_stream_label (and deleting the clock-based None arm in write_record_ordered_at), draining committed transactions before closing shards, fencing writes, latest_sequence_for_shard, ensure_shard_past_record, get_stream_records, and first_sequence_number_at_or_after (AT_TIMESTAMP millisecond seeks via current_stream_clock / decode_stored_record) at ending_sequence_number, and closing the online GSI build visibility window (1 s metadata cache TTL + 250 ms slow-write self-repair + 1.35 s visibility fence in TableEngine::update_table and gsi_worker::recover_creating_gsi under lock:gsi_build:<table_id>:<index_name>).
  7. Testing Strategy (#7): Removed the out-of-tree model-checking claims and internal labels; Testing Strategy lists only the in-tree unit, cbtemulator (EXTENDDB_TEST_BIGTABLE_REQUIRED=1, session_data_conformance::run, AT_TIMESTAMP seeks/fencing/retention, U+10FFFF base/GSI/LSI queries, and devtools/check-bigtable-catalog-lock), and devtools/run-bigtable-tests wire suites.
  8. Tier, app profile, TTL backfill, and dev_mode:
    • Changed the tier in the Summary and §8 from "production-grade" to Experimental (evaluation tier per README.md, not for production use, targeting ExtendDB v1.1.0).
    • Fixed §2.E and Motivation #7: single-row transactions (CheckAndMutateRow) are available only on single-cluster routing with single-row transactions enabled (allow_transactional_writes = true), validated at startup via GetAppProfile.
    • Documented the ENABLING -> ENABLED base-table TTL backfill (create_ttl_index under lock:ttl_backfill:<table_id>), O(1) generation-fenced drop_ttl_index, preserving due index entries while TTL is Disabled/Enabling/Disabling, and lazy O(due) orphan retirement on deleted or recreated tables.
    • Deleted dev_auth.rs and dev_mode in #1154 (§6 notes no development auth bypass exists), and restored the canonical license footer.

…k/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.
…rough protocols

- 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`.
…sticsStore defaults, and U+10FFFF query coverage
Merge upstream main (ExtendDB v1.1.0) into rfc/bigtable-backend and
reverse-sync docs/rfcs/0000-bigtable-backend.md with the v1.1.0 trait
surface and conformance coverage:

- Update ExtendDB binary version literals to v1.1.0 (ExtendDB#1514).
- Document O(1) access-key-indexed AuthorizationStore::fetch_session_data
  (including expired sessions), symmetric 4 KiB key-length bounds, and
  session_data_conformance::run (ExtendDB#1523).
- Document escaped ClientRequestToken stored tokens (ExtendDB#1375), pre-companion
  StreamSpecification refusal in TableEngine::update_table (ExtendDB#963), default
  SettingsStore::get_setting_bounded (ExtendDB#1449), and write_bootstrap_rows admin
  environment-variable handling (ExtendDB#1349).

@LeeroyHannigan LeeroyHannigan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read this head (4c02b8e) against #1154 at 523548f. I checked each item of my last review in the RFC and in the code it describes, and I read every change since 1150651.

You fixed six of the seven items of my last review, and partly fixed the other one:

  1. Fixed. The §8 Bootstrapper row names only functions that exist. Each one is a method of BigtableBootstrapper in #1154.
  2. Fixed. §6 and §8 describe the renewed lease, wait_for_servers, the serving registration and the status check in serve, and #1154 has each of them. Two attributions on line 196 are wrong. My comment there gives them.
  3. Fixed. §6 gives migration 1 as Kind::Breaking, with the catalog body on instance_id and the data body on the data instance, as m0001_baseline.rs does.
  4. Fixed. §1.B describes up to four HASH attributes under a digest and up to four RANGE segments. §2.D no longer says that a shadow update never leaves a stale entry.
  5. Fixed. Line 208 describes ExportTableToPointInTime as a paged Scan with no point in time.
  6. Partly fixed. The Motivation now lists the problems instead of calling them solved. #1154 now refuses a record whose shard row is missing, where my last review found a clock-based sequence number. §3.A still says that each enable creates the shard rows before it publishes the label, and #1154 doesn't do that in every case yet. My comment on line 147 gives the detail. The GSI build fence in #1154 also has a gap. Its 1 s cache age starts when the catalog read returns. So a catalog read slower than about 100 ms reopens the window that §5 says the fence closes.
  7. Fixed. Testing Strategy no longer names TLC.

You fixed the three notes and the dev_mode text too. The Summary says Experimental. §2.E gives single-cluster routing as the only routing with single-row transactions. §4.A describes the ENABLING backfill, and §6 says that no development admin bypass exists. #1154 has none.

The inline comments hold the new items. Each one is in text that is new since my last review.

The process items are unchanged. The file says Status: Draft, with no final comment period and no number. No maintainer has approved it, and the accepted label is still on. RFC-0003 asks for devtools/run-tests --extenddb --all to pass in CI before acceptance, and no CI has run at the head of #1154 yet.

I found no other PR that adds a Bigtable RFC. #1184, #1396 and #142 are RFCs for other backends, and each one changes only its own file under docs/rfcs/.

* `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:<offset>`) 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: #1154 at 523548f doesn't do this yet. is_pre_execution_rejection in crates/storage-bigtable/src/data/client.rs treats every RESOURCE_EXHAUSTED as a rejection before execution, so check_and_mutate_row retries it. tonic 0.14.6 also gives RESOURCE_EXHAUSTED for an HTTP/2 error with the reason ENHANCE_YOUR_CALM, which is how the connection closes after a GOAWAY with that code. That close can come after Bigtable has applied the first attempt. The retry then answers OccMismatch, and the OCC loop applies the ADD a second time. In the emulator run of my first review, the server logged 23 of these closes, and 4 of them were on CheckAndMutateRow. This line can stay as it is once #1154 stops the retry when is_status_goaway_or_transport is true.

#### 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:<shard_id>` **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`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: two parts of this paragraph don't hold in #1154 at 523548f. First, when the CAS can't use the pre-created label, it falls back to a fresh label. The call inserts the shard rows of that label after the CAS publishes it, which is the order this paragraph rules out. Second, the label is a time in milliseconds. So two enables with the same view type in the same millisecond pre-create the same four shard ids. The second call's put_shard_if_absent calls return false, and nothing reads that result. Its CAS then fails, and its cleanup deletes the four rows that the published stream uses. After that, a write that captures a stream record can't finish its roll-forward, and later writes to the same item fail. RFC-0003 §10.3 asks that repeated UpdateTable calls don't corrupt state. Please describe the design that #1154 settles on. It needs a cleanup that deletes only the rows its own call created, and no label published before its rows exist.

```

* **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`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: in #1154 only the Bigtable config uses string_coerce::u64. The helpers that the five backends and crates/server share are the key generators and the self-service policy. Please say that here.


* **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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the catalog key setting is encryption_key. CATALOG_KEY_SETTING in crates/storage/src/secret_keys.rs is "encryption_key", and the bootstrapper in #1154 writes setting:encryption_key. This line and line 29 say catalog_encryption_key. Please use the name that the code writes in both places.

* **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`):**

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: ADR-0029 is the crates.io packaging decision. The migration rules are in ADR-0023. Line 10 also cites ADR-0029 for the baseline migrations. Please cite ADR-0023 in both places.

* **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`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this line credits two checks to code that doesn't run them. In #1154, both detect bodies in m0001_baseline.rs return an empty list. The NeedsAttention answer for a catalog table with rows and no ledger comes from resolve_status in migrations.rs. devtools/check-released-through compares RELEASED_THROUGH with the last migration id and reads no checksum. The crate's test migration_table_covers_all_ids_and_refuses_additive checks the Bigtable checksums through check_released. Please name the code that does each check.

@navareamol navareamol self-assigned this Dec 4, 2026

@navareamol navareamol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things in the Bigtable claims are not backed by the docs, and one test command does not exist on main.

Section 2.E requires a single-cluster profile with single-row transactions on, and checks that one profile at startup. Google's routing page says that if single-row transactions are enabled in profiles pointing at different clusters, the user must make sure conflicting check-and-mutate requests do not go to different clusters (https://docs.cloud.google.com/bigtable/docs/routing). The OCC and 2PC design depends on that atomicity. Does the backend require an instance with one cluster? What happens to the guarantees if someone adds a second cluster or another profile with transactions on? Single-cluster routing also has no automatic failover. Please state the supported deployment shape.

Motivation item 7 and section 2.E say multi-cluster profiles reject CheckAndMutateRow with FailedPrecondition. The routing and app profile pages say transactions cannot be enabled on multi-cluster routing, but I could not find the error a request gets. Has anyone sent the request to a multi-cluster profile on the real service? If not, I think the text should say what the docs say and leave out the error name.

Testing Strategy item 3 uses devtools/run-tests --extenddb --backend bigtable. On main that script accepts only postgres, sqlite, mongodb and cassandra, and devtools/run-bigtable-tests and devtools/check-bigtable-catalog-lock do not exist. Please mark them as arriving with the implementation PR.

I will approve once the replication constraint is written down, the FailedPrecondition sentence is sourced or reworded, and the test commands are marked as not yet on main, together with the open points Lee has on this head.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

accepted RFC Request for Comments, a proposal open for discussion before implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants