From cd66e050b67d0ebb46ed40abea4390f0c4811d59 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:42 +0000 Subject: [PATCH 01/30] fix(storage): store U+0000 in strings on PostgreSQL and MongoDB DynamoDB accepts the character U+0000 anywhere a string appears: keys, index keys, values, strings in lists, map keys, attribute names (measured against the service 2026-09-18; it sorts as the byte 0x00 and is a different key from the six-character text "\u0000"). PostgreSQL TEXT rejects the byte and jsonb rejects the escape, so the backend answered 500 for every such item and for a Query whose key value carried it. BSON field names are C strings, so MongoDB answered 500 when the character appeared in an attribute name or map key. Shared escape (crates/storage/src/util/control_chars.rs): U+0000 is stored as U+0001 U+0001, U+0001 as U+0001 U+0002, everything else unchanged. Exhaustive tests over every string up to length 4 on {U+0000, U+0001, U+0002, a} pin round trip, UTF-8 byte order, prefix preservation, and distinctness, so COLLATE "C" comparisons, BETWEEN, begins_with, and the row-comparison page cursors return the rows the raw text would. PostgreSQL: item documents go through item_to_json/json_to_item (every item_data write, stream records, gsi_pending rows and contexts, vector rows, and the rows the snapshot engine's cursor stream reads); key column text goes through data/key_text.rs wrappers at every producing site; the TTL index and sweep and the vector search filters address attributes by the escaped name. Migration 004_escape_control_chars re-encodes rows written by earlier releases that contain U+0001, one table per transaction with a per-table progress marker, only rows containing U+0001 touched, predicate independent of standard_conforming_strings. The server refuses to start on a data database that does not record the migration (rows this build writes are indistinguishable from legacy rows to the migration) and extenddb init records it on fresh deployments. Catalog 0.0.5 (migrations/004_control_chars_encoding.sql) changes no schema; it moves the version so that a binary from an earlier release, which reads escaped rows as literal data and reports nothing, refuses a migrated deployment through the version check it already performs. The two gates close both directions. extenddb migrate refuses to run 004 while any other session holds the data database or, when the catalog is a separate database, the catalog database (backup_items lives there). The check runs before the first write, so a refusal leaves the catalog version where it was, and again inside the migration. The command connects as the application role, for which pg_stat_activity hides backend_type on other roles' sessions; the filter counts any session with a role whose type is client backend or hidden, so an operator's psql or a server under another role is counted and autovacuum workers are not. The test-hooks entry point apply_all_migrations, which the live test harness runs on scratch databases it created and holds alone, runs 004 without that check; every path an operator runs keeps it. MongoDB: item_to_document and its inverse escape object keys only (BSON string values already hold the byte); conditions and native updates on names with these characters use the existing in-process fallback paths, as names with "." or "$" already do; the native $setOnInsert upsert writes key attributes as item_data. paths, so a table whose key attribute name holds either character takes the session path through the same is_plain_path_name check; field paths with no fallback use the escaped name. Legacy field names are read through the decoder without a migration; the decoder's documentation states the exposure (a name containing U+0001 followed by U+0001 or U+0002) and points at the upgrade manual. Tests: tests/test_nul_strings.py (14 wire cases passing against DynamoDB and on PostgreSQL, SQLite, MongoDB and Cassandra, plus a stream record case on ExtendDB servers); unit tests on the escape, the key wrappers, the MongoDB document conversion and predicates, the migration count and version; live migration tests for re-encoding, the second-run skip, the standard_conforming_strings setting, the startup gate, the connection guard on the data database, on a separate catalog database, and from a non-superuser pool against another role's session; a live snapshot test that streams an item with U+0000 in an attribute name and U+0001 in a value as it was written; tests/test_cli_vector_catalog_migration.py covers 0.0.2 to 0.0.5 and the gate in both directions. Docs: storage design, upgrade manual, version literals. Closes #364 --- crates/app/src/cmd_migrate.rs | 9 + crates/storage-mongodb/src/data/mod.rs | 148 +- crates/storage-mongodb/src/data_engine.rs | 38 +- .../src/data_engine_update_create.rs | 38 +- crates/storage-mongodb/src/metadata_engine.rs | 25 +- crates/storage-mongodb/src/pushdown.rs | 44 +- .../storage-mongodb/src/stream_record_docs.rs | 7 +- .../migrations/004_control_chars_encoding.sql | 23 + crates/storage-postgres/src/bootstrapper.rs | 17 + .../storage-postgres/src/data/delete_item.rs | 4 +- crates/storage-postgres/src/data/gsi_build.rs | 3 +- crates/storage-postgres/src/data/index.rs | 10 +- crates/storage-postgres/src/data/key_text.rs | 139 ++ crates/storage-postgres/src/data/mod.rs | 40 +- crates/storage-postgres/src/data/put_item.rs | 9 +- crates/storage-postgres/src/data/query.rs | 4 +- .../storage-postgres/src/data/query_scan.rs | 6 +- .../storage-postgres/src/data/tx_helpers.rs | 14 +- .../storage-postgres/src/data/update_item.rs | 8 +- .../storage-postgres/src/data/vector_index.rs | 11 +- crates/storage-postgres/src/gsi_queue.rs | 28 +- crates/storage-postgres/src/lib.rs | 53 +- .../storage-postgres/src/metadata_engine.rs | 8 +- crates/storage-postgres/src/migrations.rs | 1308 ++++++++++++++++- .../storage-postgres/src/snapshot_engine.rs | 41 +- crates/storage-postgres/src/stream_engine.rs | 7 +- crates/storage-postgres/src/vector_search.rs | 15 +- .../tests/catalog_converge.rs | 23 +- .../storage-postgres/tests/table_snapshot.rs | 45 + crates/storage/src/bootstrapper.rs | 11 + crates/storage/src/util/control_chars.rs | 332 +++++ crates/storage/src/util/key.rs | 9 +- crates/storage/src/util/mod.rs | 5 + docs/design/04-component-storage.md | 19 + docs/differences-from-dynamodb.md | 6 +- docs/getting-started.md | 6 +- docs/manuals/01-architecture-guide.md | 2 +- docs/manuals/04-quickstart-setup-guide.md | 4 +- docs/manuals/05-admin-guide.md | 2 +- docs/manuals/07-upgrade-manual.md | 96 +- docs/manuals/08-install-linux.md | 2 +- docs/manuals/09-install-macos.md | 2 +- tests/test_cli_vector_catalog_migration.py | 17 +- tests/test_nul_strings.py | 378 +++++ 44 files changed, 2870 insertions(+), 146 deletions(-) create mode 100644 crates/storage-postgres/migrations/004_control_chars_encoding.sql create mode 100644 crates/storage-postgres/src/data/key_text.rs create mode 100644 crates/storage/src/util/control_chars.rs create mode 100644 tests/test_nul_strings.py diff --git a/crates/app/src/cmd_migrate.rs b/crates/app/src/cmd_migrate.rs index 2c9ea1be3..507755bfb 100755 --- a/crates/app/src/cmd_migrate.rs +++ b/crates/app/src/cmd_migrate.rs @@ -302,6 +302,15 @@ async fn apply_migrations( return Ok(EXIT_PENDING); } + // A migration that rewrites rows in place needs every other session off + // the databases it touches. Check before the first write, so a refusal + // leaves the catalog version where it was and an older binary can still be + // restarted. + bootstrap + .check_exclusive_access_for_pending_migrations() + .await + .map_err(|e| anyhow::anyhow!("{e:?}"))?; + if catalog_pending { bootstrap.run_catalog_migrations().await.map_err(op_err)?; } diff --git a/crates/storage-mongodb/src/data/mod.rs b/crates/storage-mongodb/src/data/mod.rs index d1678862a..4ee910a3b 100644 --- a/crates/storage-mongodb/src/data/mod.rs +++ b/crates/storage-mongodb/src/data/mod.rs @@ -15,7 +15,9 @@ use extenddb_core::types::{ AttributeDefinition, AttributeValue, Item, KeySchemaElement, ScalarAttributeType, }; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{composite_pk_to_text, encode_netstring_composite, sk_info}; +use extenddb_storage::util::{ + composite_pk_to_text, encode_netstring_composite, escape_json_keys, sk_info, unescape_json_keys, +}; /// Returns the `MongoDB` collection name for a `DynamoDB` table. pub fn data_collection_name(table_id: &str) -> String { @@ -34,6 +36,53 @@ pub fn composite_id(pk_text: &str, sk_text: &str) -> String { encode_netstring_composite(&[pk_text.to_owned(), sk_text.to_owned()]) } +/// Convert an item (base item or projected index item) to the BSON stored +/// under `item_data`. +/// +/// BSON field names are C strings and cannot contain U+0000, while `DynamoDB` +/// accepts it in attribute names and map keys. Every object key in the item's +/// JSON form is run through the shared order-preserving escape (U+0000 and +/// U+0001 become two-character sequences, see +/// `extenddb_storage::util::escape_control`) before the BSON conversion, so +/// the stored document never carries a NUL field name. String values are left +/// alone; BSON strings are length-prefixed and hold U+0000 verbatim. +/// +/// Every conversion of an item to `item_data` BSON must go through this +/// function or [`json_to_item_data`]; a direct `bson::to_bson` on item JSON +/// fails in the driver at write time when a name contains U+0000. +/// [`item_data_to_json`] reverses the escape on read. +pub(crate) fn item_to_item_data(item: &Item) -> Result { + let item_json = + serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; + json_to_item_data(item_json) +} + +/// JSON-tree variant of [`item_to_item_data`], for payloads that carry items +/// nested inside another structure (stream records with key/image maps). +pub(crate) fn json_to_item_data(json: serde_json::Value) -> Result { + let escaped = escape_json_keys(json); + bson::to_bson(&escaped).map_err(|e| StorageError::Internal(e.to_string())) +} + +/// Reverse of [`json_to_item_data`]: BSON read from storage back to JSON with +/// the object-key escape undone. +/// +/// Documents written by a release before the escape hold their field names +/// raw, and there is no migration and no startup check for them: unlike +/// `PostgreSQL`, nothing here can fail to store (BSON strings already hold +/// U+0000, and a raw field name reads back through the driver), so the only +/// effect is on a legacy name that happens to contain U+0001 immediately +/// followed by U+0001 or U+0002, which this decoder reads as U+0000 or +/// U+0001. A lone U+0001 and every string value are unchanged. That exposure +/// was judged too narrow to make every `MongoDB` upgrade acknowledge a gate +/// with nothing to rewrite; the upgrade manual's "Data Migrations" section +/// states the limitation for operators. +pub(crate) fn item_data_to_json(value: &bson::Bson) -> Result { + let json: serde_json::Value = bson::from_bson(value.clone()) + .map_err(|e| StorageError::Internal(format!("BSON to JSON conversion error: {e}")))?; + Ok(unescape_json_keys(json)) +} + /// Convert a `DynamoDB` Item to a `MongoDB` BSON document for storage. /// /// Document structure: `{ _id, pk, sk_s/sk_n/sk_b, item_data }` @@ -44,10 +93,9 @@ pub fn item_to_document( ) -> Result { let pk_text = composite_pk_to_text(item, key_schema)?; - // Serialize the full item as item_data - let item_json = - serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; - let item_bson = bson::to_bson(&item_json).map_err(|e| StorageError::Internal(e.to_string()))?; + // Serialize the full item as item_data (object keys escaped, see + // item_to_item_data). + let item_bson = item_to_item_data(item)?; let mut doc = Document::new(); @@ -194,9 +242,7 @@ pub fn index_document( insert_typed_sk(&mut doc, &field, sk_type, sk_value)?; } - let item_json = - serde_json::to_value(projected).map_err(|e| StorageError::Internal(e.to_string()))?; - let item_bson = bson::to_bson(&item_json).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_bson = item_to_item_data(projected)?; doc.insert("item_data", item_bson); Ok(doc) @@ -256,8 +302,7 @@ pub fn document_to_item(doc: &Document) -> Result { .get("item_data") .ok_or_else(|| StorageError::Internal("Document missing item_data field".to_string()))?; - let json_value: serde_json::Value = bson::from_bson(item_data.clone()) - .map_err(|e| StorageError::Internal(format!("BSON to JSON conversion error: {e}")))?; + let json_value = item_data_to_json(item_data)?; let item: Item = serde_json::from_value(json_value) .map_err(|e| StorageError::Internal(format!("JSON to Item conversion error: {e}")))?; @@ -436,6 +481,89 @@ mod tests { assert!(matches!(err, StorageError::Validation(_))); } + /// Walk a BSON tree and assert no document field name contains U+0000. + fn assert_no_nul_field_names(value: &bson::Bson) { + match value { + bson::Bson::Document(doc) => { + for (k, v) in doc { + assert!(!k.contains('\u{0}'), "field name contains NUL: {k:?}"); + assert_no_nul_field_names(v); + } + } + bson::Bson::Array(items) => { + for item in items { + assert_no_nul_field_names(item); + } + } + _ => {} + } + } + + #[test] + fn item_document_round_trips_control_characters_in_names() { + use std::collections::BTreeMap; + + let (schema, attrs) = schema_pk_str_sk_num(); + + let mut inner = BTreeMap::new(); + inner.insert( + "deep\u{0}key".to_owned(), + AttributeValue::S("v\u{0}".to_owned()), + ); + let mut mid = BTreeMap::new(); + mid.insert("mid\u{1}key".to_owned(), AttributeValue::M(inner)); + let mut in_list = BTreeMap::new(); + in_list.insert( + "list\u{0}\u{1}key".to_owned(), + AttributeValue::S("w".to_owned()), + ); + + let mut item = Item::new(); + item.insert("pk".to_owned(), AttributeValue::S("p".to_owned())); + item.insert("sk".to_owned(), AttributeValue::N("1".to_owned())); + item.insert( + "top\u{0}\u{1}name".to_owned(), + AttributeValue::S("x".to_owned()), + ); + item.insert("map".to_owned(), AttributeValue::M(mid)); + item.insert( + "list".to_owned(), + AttributeValue::L(vec![AttributeValue::M(in_list)]), + ); + + let doc = item_to_document(&item, &schema, &attrs).unwrap(); + assert_no_nul_field_names(&bson::Bson::Document(doc.clone())); + + let back = document_to_item(&doc).unwrap(); + assert_eq!(back, item); + } + + #[test] + fn plain_item_document_stores_raw_field_names() { + use std::collections::BTreeMap; + + let (schema, attrs) = schema_pk_str_sk_num(); + + let mut inner = BTreeMap::new(); + inner.insert("k".to_owned(), AttributeValue::S("v".to_owned())); + let mut item = Item::new(); + item.insert("pk".to_owned(), AttributeValue::S("p".to_owned())); + item.insert("sk".to_owned(), AttributeValue::N("1".to_owned())); + item.insert("attr".to_owned(), AttributeValue::M(inner)); + + let doc = item_to_document(&item, &schema, &attrs).unwrap(); + let item_data = doc.get_document("item_data").unwrap(); + let names: Vec<&str> = item_data.keys().map(String::as_str).collect(); + assert_eq!(names, vec!["attr", "pk", "sk"]); + let attr_m = item_data + .get_document("attr") + .unwrap() + .get_document("M") + .unwrap(); + let map_keys: Vec<&str> = attr_m.keys().map(String::as_str).collect(); + assert_eq!(map_keys, vec!["k"]); + } + #[test] fn composite_id_disambiguates_delimiter_in_pk_or_sk() { // Two items whose naive "{pk}#{sk}" strings would collide must diff --git a/crates/storage-mongodb/src/data_engine.rs b/crates/storage-mongodb/src/data_engine.rs index ab297a544..c66ea152c 100644 --- a/crates/storage-mongodb/src/data_engine.rs +++ b/crates/storage-mongodb/src/data_engine.rs @@ -29,7 +29,7 @@ use crate::MongoEngine; use crate::condition::condition_to_filter; use crate::data::{ binary_sk_to_hex, composite_id, data_collection_name, document_to_item, index_document, - index_entry_filter, item_to_document, pk_filter, sk_field_name, sk_suffix, + index_entry_filter, item_to_document, json_to_item_data, pk_filter, sk_field_name, sk_suffix, }; use crate::pushdown::{Pushable, is_pushable}; @@ -37,8 +37,9 @@ use extenddb_core::types::{Projection, ProjectionType}; /// Resolve a single-component update path for the native MongoDB fast path. /// Literal attribute names containing dots or beginning with `$` cannot be -/// represented safely by MongoDB's ordinary update paths, so they must use -/// the Rust/session path. +/// represented safely by MongoDB's ordinary update paths, and names +/// containing U+0000 or U+0001 differ from the stored (escaped) field name, +/// so they must use the Rust/session path. fn native_attribute_name(path: &[PathElement], maps: &ExpressionMaps) -> Option { if path.len() != 1 { return None; @@ -802,8 +803,9 @@ impl MongoEngine { // common (no-GSI) case; when the cache is stale-or-unknown // we fall through to the slow path which is authoritative. Key // attribute names that are not plain path names (a dot, a leading - // `$`) also take the slow path, because the upsert writes the key - // attributes as `item_data.` (see `update_create`). + // `$`, U+0000 or U+0001) also take the slow path, because the + // upsert writes the key attributes as `item_data.` (see + // `update_create`). if condition.is_none() && !return_old && stream.is_none() @@ -1687,8 +1689,11 @@ impl MongoEngine { _ => return None, // complex expressions (if_not_exists, list_append, arithmetic) }; let field = format!("item_data.{attr_name}"); + // The value lands inside item_data, so its nested map + // keys must be in stored (escaped) form, matching what + // item_to_document writes. let val_json = serde_json::to_value(val).ok()?; - let val_bson = bson::to_bson(&val_json).ok()?; + let val_bson = json_to_item_data(val_json).ok()?; set_doc.insert(field, val_bson); } UpdateAction::Remove { path } => { @@ -2072,8 +2077,10 @@ impl MongoEngine { let record_json = serde_json::to_value(&record).map_err(|e| StorageError::Internal(e.to_string()))?; - let record_bson = - bson::to_bson(&record_json).map_err(|e| StorageError::Internal(e.to_string()))?; + // The record's key and image maps carry attribute names as object + // keys, which become BSON field names; convert through the same + // escaping helper as item_data. + let record_bson = json_to_item_data(record_json)?; // key_info already carries table_id — no need to re-read the catalog // just to resolve it, and re-reading inside the session against the @@ -4438,6 +4445,21 @@ transaction_read_concern = "majority""#, assert_eq!(native_attribute_name(&path, &maps), None); } + #[test] + fn native_update_rejects_control_character_literal_attribute_names() { + // Stored field names carry the escaped form of U+0000 and U+0001, + // so a native update path built from the raw name would target a + // different field; these names must use the Rust/session path. + for name in ["a\u{0}b", "a\u{1}b"] { + let mut names = std::collections::HashMap::new(); + names.insert("name".to_owned(), name.to_owned()); + let maps = ExpressionMaps::new(names, std::collections::HashMap::new()); + let path = vec![PathElement::Attribute("#name".to_owned())]; + + assert_eq!(native_attribute_name(&path, &maps), None, "{name:?}"); + } + } + #[test] fn native_update_keeps_simple_attribute_names_on_fast_path() { let maps = ExpressionMaps::new( diff --git a/crates/storage-mongodb/src/data_engine_update_create.rs b/crates/storage-mongodb/src/data_engine_update_create.rs index a7f4e7e01..f8ca78d86 100644 --- a/crates/storage-mongodb/src/data_engine_update_create.rs +++ b/crates/storage-mongodb/src/data_engine_update_create.rs @@ -29,13 +29,18 @@ //! step into a sub-document. A key attribute named `a.b` would be inserted as //! `item_data: { a: { b: ... } }`, where PutItem stores the field `"a.b"`, //! and the same path conflicts with an update of an attribute named `a`. -//! A table with a key attribute name that `key_names_are_plain_paths` -//! rejects therefore does not take the native upsert; it takes the session -//! path, which writes the document `item_to_document` builds. +//! A key attribute name containing U+0000 or U+0001 has the same problem in +//! another form: `item_to_document` stores it escaped +//! (`extenddb_storage::util::control_chars`), and the path would name the +//! raw text. A table with a key attribute name that +//! `key_names_are_plain_paths` rejects therefore does not take the native +//! upsert; it takes the session path, which writes the document +//! `item_to_document` builds. use bson::Document; use extenddb_core::types::{Item, KeySchemaElement, TableKeyInfo}; use extenddb_storage::error::StorageError; +use extenddb_storage::util::needs_escape; use mongodb::options::{FindOneAndUpdateOptions, ReturnDocument}; use super::{TRANSIENT_RETRY_ATTEMPTS, backoff_sleep}; @@ -44,9 +49,11 @@ use crate::data::key_fields::insert_only_key_fields; /// Whether `name` is usable as one field name in a MongoDB update path. A dot /// would split it into nested fields and a leading `$` would read as an -/// operator or positional path. +/// operator or positional path. A name containing U+0000 or U+0001 is stored +/// in escaped form, so a path built from the raw name would address a +/// different field (and BSON refuses U+0000 in a field name). pub(super) fn is_plain_path_name(name: &str) -> bool { - !name.contains('.') && !name.starts_with('$') + !name.contains('.') && !name.starts_with('$') && !needs_escape(name) } /// Whether every key attribute of `key_schema` is a plain path name, so that @@ -173,4 +180,25 @@ mod tests { ); } } + + #[test] + fn a_key_name_with_u0000_or_u0001_leaves_the_native_upsert() { + // item_to_document stores these names escaped, so the + // `item_data.` path of the upsert would name another field. + assert!(key_names_are_plain_paths(&schema(&[( + "a\u{2}b", + KeyType::Hash + )]))); + for name in ["a\u{0}b", "a\u{1}b", "\u{1}\u{2}"] { + assert!( + !key_names_are_plain_paths(&schema(&[(name, KeyType::Hash)])), + "hash key {name:?}" + ); + let keys = [("pk", KeyType::Hash), (name, KeyType::Range)]; + assert!( + !key_names_are_plain_paths(&schema(&keys)), + "range key {name:?}" + ); + } + } } diff --git a/crates/storage-mongodb/src/metadata_engine.rs b/crates/storage-mongodb/src/metadata_engine.rs index 7fe21f9c3..3dac4241b 100644 --- a/crates/storage-mongodb/src/metadata_engine.rs +++ b/crates/storage-mongodb/src/metadata_engine.rs @@ -18,6 +18,7 @@ use extenddb_storage::error::StorageError; use crate::MongoEngine; use crate::data::{data_collection_name, document_to_item}; +use extenddb_storage::util::escape_control; fn extract_id_fields(doc: &Document) -> (String, String) { let id = doc.get_document("_id").ok(); @@ -35,13 +36,15 @@ fn extract_id_fields(doc: &Document) -> (String, String) { /// Build the expression that reads a DynamoDB attribute from `item_data` as a /// literal field name. MongoDB normally interprets dots in a query field path /// as nested-document traversal, but DynamoDB permits dots in attribute names. +/// The stored field name is the escaped form of the attribute name (see +/// `extenddb_storage::util::escape_control`), so the lookup targets that form. fn literal_ttl_value_expression(ttl_attribute: &str) -> Document { doc! { "$getField": { "field": "N", "input": { "$getField": { - "field": ttl_attribute, + "field": escape_control(ttl_attribute).as_ref(), "input": "$item_data", } } @@ -69,7 +72,7 @@ fn literal_ttl_epoch_expression(ttl_attribute: &str) -> Document { /// also performs the expiry comparison in MongoDB, so non-expired low-`_id` /// documents cannot starve expired documents later in the collection. fn ttl_candidate_query(ttl_attribute: &str, now_epoch: i64) -> (Document, Document) { - let ttl_field = format!("item_data.{ttl_attribute}.N"); + let ttl_field = format!("item_data.{}.N", escape_control(ttl_attribute)); if ttl_attribute.contains('.') { let ttl_epoch = literal_ttl_epoch_expression(ttl_attribute); ( @@ -374,8 +377,12 @@ impl MetadataEngine for MongoEngine { let coll_name = data_collection_name(table_id); let data_coll = self.data_db.collection::(&coll_name); - let index_name = format!("idx_ttl_{ttl_attribute}"); - let index_key = format!("item_data.{ttl_attribute}.N"); + // The stored field name is the escaped attribute name, and the + // escape also keeps U+0000 out of the index name. Names without + // U+0000 or U+0001 escape to themselves, so existing index names + // do not change. + let index_name = format!("idx_ttl_{}", escape_control(&ttl_attribute)); + let index_key = format!("item_data.{}.N", escape_control(&ttl_attribute)); let index = IndexModel::builder() .keys(doc! { &index_key: 1 }) @@ -433,7 +440,9 @@ impl MetadataEngine for MongoEngine { .get_str("table_id") .map_err(|_| StorageError::Internal("missing table_id".to_string()))?; - let index_name = format!("idx_ttl_{ttl_attribute}"); + // Same escaped form as create_ttl_index so the drop targets the + // index that was created. + let index_name = format!("idx_ttl_{}", escape_control(&ttl_attribute)); let coll_name = data_collection_name(table_id); let data_coll = self.data_db.collection::(&coll_name); @@ -513,9 +522,11 @@ impl MetadataEngine for MongoEngine { if items.len() >= limit { break; } - // Parse the TTL value and check if expired + // Parse the TTL value and check if expired. The stored field + // name is the escaped attribute name. if let Ok(item_data) = doc.get_document("item_data") - && let Ok(ttl_obj) = item_data.get_document(&ttl_attribute) + && let Ok(ttl_obj) = + item_data.get_document(escape_control(&ttl_attribute).as_ref()) && let Ok(n_str) = ttl_obj.get_str("N") && let Ok(ttl_val) = n_str.parse::() && ttl_val >= 1 diff --git a/crates/storage-mongodb/src/pushdown.rs b/crates/storage-mongodb/src/pushdown.rs index 616ef7508..05f96dac9 100644 --- a/crates/storage-mongodb/src/pushdown.rs +++ b/crates/storage-mongodb/src/pushdown.rs @@ -44,6 +44,7 @@ use extenddb_core::expression::{CompareOp, Expr, ExpressionMaps, PathElement}; use extenddb_core::types::AttributeValue; +use extenddb_storage::util::needs_escape; /// Outcome of the pushdown analyzer. #[derive(Debug, Clone, PartialEq, Eq)] @@ -76,7 +77,10 @@ pub fn is_pushable(expr: &Expr, maps: &ExpressionMaps) -> Pushable { /// Return why an expression contains a literal DynamoDB attribute name that /// cannot safely be emitted as a MongoDB field path. A dot would mean nested /// document traversal in MongoDB, while a leading `$` would be interpreted as -/// an operator or otherwise have special meaning in a MongoDB path. +/// an operator or otherwise have special meaning in a MongoDB path. A name +/// containing U+0000 or U+0001 is stored under its escaped form (see +/// `extenddb_storage::util::escape_control`), so the raw name would not match +/// the stored field. fn unsafe_attribute_reason(expr: &Expr, maps: &ExpressionMaps) -> Option<&'static str> { match expr { Expr::Path(elements) => elements.iter().find_map(|element| match element { @@ -91,6 +95,9 @@ fn unsafe_attribute_reason(expr: &Expr, maps: &ExpressionMaps) -> Option<&'stati Some(name) if name.starts_with('$') => { Some("literal attribute name begins with '$'") } + Some(name) if needs_escape(name) => { + Some("literal attribute name contains U+0000 or U+0001") + } Some(_) => None, None => Some("attribute name alias is unresolved"), } @@ -393,6 +400,41 @@ mod tests { ); } + #[test] + fn nul_attribute_name_is_not_pushable() { + // The stored field name is the escaped form, so a raw path on a + // name containing U+0000 would never match; must fall back. + let expr = Expr::Compare { + left: Box::new(path("a\u{0}b")), + op: CompareOp::Eq, + right: Box::new(Expr::Placeholder(":value".into())), + }; + let maps = maps_with(&[(":value", AttributeValue::S("value".into()))]); + + assert_eq!( + is_pushable(&expr, &maps), + Pushable::No("literal attribute name contains U+0000 or U+0001") + ); + } + + #[test] + fn control_character_attribute_alias_is_not_pushable() { + for resolved in ["a\u{0}b", "a\u{1}b"] { + let expr = Expr::Compare { + left: Box::new(path("#name")), + op: CompareOp::Eq, + right: Box::new(Expr::Placeholder(":value".into())), + }; + let maps = aliased_maps(resolved, AttributeValue::S("value".into())); + + assert_eq!( + is_pushable(&expr, &maps), + Pushable::No("literal attribute name contains U+0000 or U+0001"), + "{resolved:?}" + ); + } + } + #[test] fn nested_document_path_without_literal_dot_remains_pushable() { let expr = Expr::Compare { diff --git a/crates/storage-mongodb/src/stream_record_docs.rs b/crates/storage-mongodb/src/stream_record_docs.rs index c84bbadf9..4fa57587c 100644 --- a/crates/storage-mongodb/src/stream_record_docs.rs +++ b/crates/storage-mongodb/src/stream_record_docs.rs @@ -12,7 +12,7 @@ use extenddb_core::types::StreamRecord; use extenddb_storage::error::StorageError; -use mongodb::bson::{self, Document}; +use mongodb::bson::Document; /// The records in `docs`, in order. A document whose `has_record` is false /// carries none. One whose `has_record` is true must carry `record_data`. @@ -23,8 +23,9 @@ pub(crate) fn records_from_docs(docs: Vec) -> Result let record_bson = d .remove("record_data") .ok_or_else(|| StorageError::Internal("Missing record_data".to_owned()))?; - let json_val: serde_json::Value = - bson::from_bson(record_bson).map_err(|e| StorageError::Internal(e.to_string()))?; + // Reverses the object-key escape applied when the record was + // written; see json_to_item_data. + let json_val = crate::data::item_data_to_json(&record_bson)?; serde_json::from_value(json_val).map_err(|e| StorageError::Internal(e.to_string())) }) .collect() diff --git a/crates/storage-postgres/migrations/004_control_chars_encoding.sql b/crates/storage-postgres/migrations/004_control_chars_encoding.sql new file mode 100644 index 000000000..215796932 --- /dev/null +++ b/crates/storage-postgres/migrations/004_control_chars_encoding.sql @@ -0,0 +1,23 @@ +-- Copyright 2026 ExtendDB contributors +-- SPDX-License-Identifier: Apache-2.0 +-- Migration 004: stored string encoding changed (catalog version 0.0.5). +-- +-- This migration changes no schema. It moves the catalog version because the +-- form of the stored data changed: from this release, strings in the data +-- database and in `backup_items` are written through an order-preserving +-- escape (U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002), and the data +-- migration `004_escape_control_chars` re-encodes rows written before it. +-- +-- A binary from an earlier release knows nothing about the escape and would +-- read an escaped row as literal data, silently. The catalog version check at +-- startup is the one check such a binary already performs, so moving the +-- version is what makes it refuse a migrated deployment instead of serving +-- wrong strings. The data migration itself is tracked in the data database's +-- `schema_history`; see `DATA_CODE_MIGRATIONS` in +-- `crates/storage-postgres/src/migrations.rs` and the upgrade manual. + +BEGIN; + +UPDATE settings SET value = '0.0.5' WHERE key = 'catalog_version'; + +COMMIT; diff --git a/crates/storage-postgres/src/bootstrapper.rs b/crates/storage-postgres/src/bootstrapper.rs index 5eea7b26d..b50c99aa0 100755 --- a/crates/storage-postgres/src/bootstrapper.rs +++ b/crates/storage-postgres/src/bootstrapper.rs @@ -110,6 +110,9 @@ impl PostgresBootstrapper { .username(&self.config.app_user) .password(&self.config.app_password) .database(database) + // Lets a migration tell its own connections apart from a server's + // in pg_stat_activity (see `migrations::MIGRATE_APPLICATION_NAME`). + .application_name(migrations::MIGRATE_APPLICATION_NAME) } /// Build the connection URL for the application user and a named database. @@ -446,6 +449,20 @@ impl Bootstrapper for PostgresBootstrapper { Ok(pending) } + /// `004_escape_control_chars` rewrites rows in the data database and in the + /// catalog's `backup_items`, so while it is pending the migrate command must + /// be the only client of both databases. The same check runs again inside + /// the migration; this one runs before the catalog migrations write the new + /// version, so a refusal changes nothing. + async fn check_exclusive_access_for_pending_migrations(&self) -> OpResult<()> { + let data_pool = self.app_pool(&self.config.data_db).await?; + if !migrations::needs_exclusive_access(&data_pool).await? { + return Ok(()); + } + let catalog_pool = self.app_pool(&self.config.catalog_db).await?; + migrations::refuse_if_other_clients_connected_anywhere(&catalog_pool, &data_pool).await + } + async fn record_data_connection(&self) -> OpResult<()> { let pool = self.app_pool(&self.config.catalog_db).await?; let data_conn = self.app_connection_url(&self.config.data_db); diff --git a/crates/storage-postgres/src/data/delete_item.rs b/crates/storage-postgres/src/data/delete_item.rs index 9a6dfda93..63a29e7b3 100755 --- a/crates/storage-postgres/src/data/delete_item.rs +++ b/crates/storage-postgres/src/data/delete_item.rs @@ -7,7 +7,9 @@ use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{SortKeyValue, parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{SortKeyValue, sk_column, sk_info}; + +use super::key_text::{parse_sk, pk_to_text}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; diff --git a/crates/storage-postgres/src/data/gsi_build.rs b/crates/storage-postgres/src/data/gsi_build.rs index 22ee5bf6f..2e84dd617 100644 --- a/crates/storage-postgres/src/data/gsi_build.rs +++ b/crates/storage-postgres/src/data/gsi_build.rs @@ -58,13 +58,14 @@ use extenddb_core::types::{ TableKeyInfo, }; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{composite_pk_to_text, parse_sk, sk_column_n}; +use extenddb_storage::util::sk_column_n; use sqlx::Row as _; use super::index::{ IndexMeta, db_error, delete_index_row_multi, fetch_indexes_for_table, insert_index_row_multi, project_item_for_index, }; +use super::key_text::{composite_pk_to_text, parse_sk}; use super::{all_sort_key_info, data_table_name, index_table_name, json_to_item}; use crate::gsi_queue::{GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending}; diff --git a/crates/storage-postgres/src/data/index.rs b/crates/storage-postgres/src/data/index.rs index 09c5627d7..c8d48595b 100644 --- a/crates/storage-postgres/src/data/index.rs +++ b/crates/storage-postgres/src/data/index.rs @@ -13,9 +13,11 @@ use extenddb_core::types::{ }; use extenddb_storage::error::StorageError; use extenddb_storage::util::SortKeyValue; -use extenddb_storage::util::{composite_pk_to_text, parse_sk, sk_column, sk_column_n}; +use extenddb_storage::util::{sk_column, sk_column_n}; -use super::{all_sort_key_info, index_table_name}; +use super::key_text::{composite_pk_to_text, parse_sk}; + +use super::{all_sort_key_info, index_table_name, item_to_json}; use crate::gsi_queue::{GsiApplyContext, GsiIndexDef, enqueue_gsi_pending}; /// Map a `sqlx` error to `StorageError`, preserving the SQLSTATE code in the @@ -571,9 +573,7 @@ pub(crate) async fn insert_index_rows_multi( for &(sk_name, sk_type) in base_sks { query = bind_index_sk(query, idx_table, item, sk_name, sk_type)?; } - query = query.bind( - serde_json::to_value(projected).map_err(|e| StorageError::Internal(e.to_string()))?, - ); + query = query.bind(item_to_json(projected)?); } query.execute(&mut **tx).await.map_err(db_error)?; diff --git a/crates/storage-postgres/src/data/key_text.rs b/crates/storage-postgres/src/data/key_text.rs new file mode 100644 index 000000000..a433907af --- /dev/null +++ b/crates/storage-postgres/src/data/key_text.rs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Key text for the `PostgreSQL` key columns. +//! +//! The shared helpers in `extenddb_storage::util` turn key attribute values into +//! the text the SQL backends bind against `pk`, `sk_s`, `base_pk`, and the other +//! string key columns. `PostgreSQL` `TEXT` cannot hold the byte 0x00, which +//! DynamoDB allows anywhere in a string key, so this module wraps those helpers +//! and passes every string component through the order-preserving escape from +//! `extenddb_storage::util::escape_control`. Numbers and base64 binaries contain +//! neither U+0000 nor U+0001 and are unchanged. The escape preserves byte order +//! and prefixes, so the `COLLATE "C"` comparisons, `BETWEEN`, `begins_with`, +//! and row-comparison cursors that run on these columns return the same rows +//! they would on the raw text. +//! +//! Every site in this crate that produces key column text imports these three +//! functions instead of the shared ones, so the write path, the read path, index +//! rows, cursors, and the propagation queue all agree on the stored form. + +use std::borrow::Cow; + +use extenddb_core::types::{AttributeValue, Item, KeySchemaElement, KeyType, ScalarAttributeType}; +use extenddb_storage::error::StorageError; +use extenddb_storage::util::{self, SortKeyValue, encode_netstring_composite, escape_control}; + +/// Partition key attribute value as escaped column text. +pub(crate) fn pk_to_text(value: &AttributeValue) -> Result, StorageError> { + Ok(match util::pk_to_text(value)? { + Cow::Borrowed(s) => escape_control(s), + Cow::Owned(s) => Cow::Owned(escape_control(&s).into_owned()), + }) +} + +/// Composite partition key as escaped column text. +/// +/// Mirrors `extenddb_storage::util::composite_pk_to_text`: a single HASH +/// attribute is its own text, several are netstring-joined. Each part is +/// escaped before joining, which is also what `query_scan` does when it builds +/// the same text from a key condition, so the two agree byte for byte. +pub(crate) fn composite_pk_to_text( + item: &Item, + key_schema: &[KeySchemaElement], +) -> Result { + let hash_elements: Vec<_> = key_schema + .iter() + .filter(|ks| ks.key_type == KeyType::Hash) + .collect(); + if hash_elements.len() == 1 { + let val = item + .get(&hash_elements[0].attribute_name) + .ok_or_else(|| StorageError::Internal("missing partition key".to_owned()))?; + return Ok(pk_to_text(val)?.into_owned()); + } + let mut parts = Vec::with_capacity(hash_elements.len()); + for ks in &hash_elements { + let val = item.get(&ks.attribute_name).ok_or_else(|| { + StorageError::Internal(format!( + "missing partition key attribute {}", + ks.attribute_name + )) + })?; + parts.push(pk_to_text(val)?.into_owned()); + } + Ok(encode_netstring_composite(&parts)) +} + +/// Sort key attribute value as a typed bind value, string keys escaped. +pub(crate) fn parse_sk( + value: &AttributeValue, + sk_type: ScalarAttributeType, +) -> Result { + Ok(match util::parse_sk(value, sk_type)? { + SortKeyValue::S(s) => SortKeyValue::S(escape_control(&s).into_owned()), + other => other, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ks(name: &str) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type: KeyType::Hash, + } + } + + #[test] + fn string_keys_are_escaped_and_other_types_are_not() { + assert_eq!( + pk_to_text(&AttributeValue::S("a\u{0}b".into())).unwrap(), + "a\u{1}\u{1}b" + ); + assert_eq!( + pk_to_text(&AttributeValue::S("plain".into())).unwrap(), + "plain" + ); + assert_eq!( + pk_to_text(&AttributeValue::N("12.5".into())).unwrap(), + "12.5" + ); + assert_eq!( + pk_to_text(&AttributeValue::B(vec![0, 1, 2])).unwrap(), + util::pk_to_text(&AttributeValue::B(vec![0, 1, 2])).unwrap() + ); + match parse_sk(&AttributeValue::S("\u{1}".into()), ScalarAttributeType::S).unwrap() { + SortKeyValue::S(s) => assert_eq!(s, "\u{1}\u{2}"), + _ => panic!("string sort key"), + } + match parse_sk(&AttributeValue::B(vec![0]), ScalarAttributeType::B).unwrap() { + SortKeyValue::B(b) => assert_eq!(b, vec![0]), + _ => panic!("binary sort key"), + } + } + + #[test] + fn composite_text_escapes_each_part_before_joining() { + let mut item = Item::new(); + item.insert("h1".to_owned(), AttributeValue::S("a\u{0}".into())); + item.insert("h2".to_owned(), AttributeValue::S("b".into())); + let text = composite_pk_to_text(&item, &[ks("h1"), ks("h2")]).unwrap(); + // The escaped part is three bytes, and the netstring length says so. + assert_eq!(text, "3:a\u{1}\u{1},1:b,"); + assert!(!text.contains('\u{0}')); + // Single hash attribute: the escaped value itself. + let text = composite_pk_to_text(&item, &[ks("h1")]).unwrap(); + assert_eq!(text, "a\u{1}\u{1}"); + } + + #[test] + fn stored_text_never_contains_nul() { + for raw in ["\u{0}", "a\u{0}b", "\u{0}\u{1}\u{2}", "x\u{1}\u{1}y"] { + let av = AttributeValue::S(raw.into()); + let text = pk_to_text(&av).unwrap(); + assert!(!text.contains('\u{0}'), "{raw:?} -> {text:?}"); + } + } +} diff --git a/crates/storage-postgres/src/data/mod.rs b/crates/storage-postgres/src/data/mod.rs index 7f37ea17d..d0d6a3aef 100755 --- a/crates/storage-postgres/src/data/mod.rs +++ b/crates/storage-postgres/src/data/mod.rs @@ -9,6 +9,7 @@ use extenddb_core::types::{AttributeDefinition, Item, KeySchemaElement, ScalarAttributeType}; use extenddb_storage::error::StorageError; +use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; /// SQL table name for a Virtual `DynamoDB` table. /// @@ -63,8 +64,44 @@ pub(crate) fn all_sort_key_info<'a>( } /// Deserialize an `item_data` JSONB value into an `Item`. +/// +/// Reverses [`item_to_json`]: every string in the stored tree is unescaped +/// before deserialization, so an item written with U+0000 anywhere in it comes +/// back byte-identical. pub(crate) fn json_to_item(v: serde_json::Value) -> Result { - serde_json::from_value(v).map_err(|e| StorageError::Internal(e.to_string())) + serde_json::from_value(unescape_json_strings(v)) + .map_err(|e| StorageError::Internal(e.to_string())) +} + +/// Serialize an `Item` for an `item_data` JSONB column. +/// +/// PostgreSQL `jsonb` rejects the `\u0000` escape, so every string in the tree +/// (attribute names, map keys, string values) goes through the order-preserving +/// escape from `extenddb_storage::util` before it reaches the column. Items +/// without U+0000 or U+0001 serialize to exactly what they did before. +pub(crate) fn item_to_json(item: &Item) -> Result { + serde_json::to_value(item) + .map(escape_json_strings) + .map_err(|e| StorageError::Internal(e.to_string())) +} + +/// Serialize any value for a JSONB column that may carry item strings (stream +/// records, queued index updates, index contexts). Same escape as +/// [`item_to_json`]; the inverse is [`stored_json_to`]. +pub(crate) fn to_stored_json( + value: &T, +) -> Result { + serde_json::to_value(value) + .map(escape_json_strings) + .map_err(|e| StorageError::Internal(e.to_string())) +} + +/// Deserialize a JSONB value written by [`to_stored_json`]. +pub(crate) fn stored_json_to( + v: serde_json::Value, +) -> Result { + serde_json::from_value(unescape_json_strings(v)) + .map_err(|e| StorageError::Internal(e.to_string())) } /// Bind a `SortKeyValue` to a positional parameter in a sqlx query and execute it. @@ -137,6 +174,7 @@ mod ddl; mod delete_item; pub(crate) mod gsi_build; pub(crate) mod index; +pub(crate) mod key_text; mod put_item; mod query; mod query_scan; diff --git a/crates/storage-postgres/src/data/put_item.rs b/crates/storage-postgres/src/data/put_item.rs index 2fbc3102b..1e06bfd72 100755 --- a/crates/storage-postgres/src/data/put_item.rs +++ b/crates/storage-postgres/src/data/put_item.rs @@ -7,13 +7,15 @@ use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{composite_pk_to_text, parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{sk_column, sk_info}; + +use super::key_text::{composite_pk_to_text, parse_sk, pk_to_text}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; use super::query::check_condition; use super::tx_helpers::write_stream_record_in_tx; -use super::{data_table_name, json_to_item}; +use super::{data_table_name, item_to_json, json_to_item}; use crate::PostgresEngine; impl PostgresEngine { @@ -31,8 +33,7 @@ impl PostgresEngine { let pk_text = composite_pk_to_text(&item, &key_info.key_schema)?; - let item_json = - serde_json::to_value(&item).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_json = item_to_json(&item)?; // Both index families in one catalog visit (D-4: sync + async split for the // secondary indexes). diff --git a/crates/storage-postgres/src/data/query.rs b/crates/storage-postgres/src/data/query.rs index a57b69bec..a9537deb9 100755 --- a/crates/storage-postgres/src/data/query.rs +++ b/crates/storage-postgres/src/data/query.rs @@ -12,7 +12,9 @@ use extenddb_core::types::{ }; use extenddb_storage::error::StorageError; use extenddb_storage::util::SortKeyValue; -use extenddb_storage::util::{parse_sk, pk_to_text, sk_info}; +use extenddb_storage::util::sk_info; + +use super::key_text::{parse_sk, pk_to_text}; /// Extra pagination bind values for index queries. /// diff --git a/crates/storage-postgres/src/data/query_scan.rs b/crates/storage-postgres/src/data/query_scan.rs index be6de8a6f..293718995 100644 --- a/crates/storage-postgres/src/data/query_scan.rs +++ b/crates/storage-postgres/src/data/query_scan.rs @@ -6,9 +6,9 @@ use extenddb_core::expression::{ExpressionMaps, KeyCondition}; use extenddb_core::types::{Item, ScalarAttributeType, TableKeyInfo}; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{ - encode_netstring_composite, parse_sk, pk_to_text, sk_column, sk_column_n, sk_info, -}; +use extenddb_storage::util::{encode_netstring_composite, sk_column, sk_column_n, sk_info}; + +use super::key_text::{parse_sk, pk_to_text}; use super::query::{ PaginationBinds, build_key, build_sk_sql, execute_query_sql, execute_scan_sql, diff --git a/crates/storage-postgres/src/data/tx_helpers.rs b/crates/storage-postgres/src/data/tx_helpers.rs index 6468f159b..b3f4c9820 100755 --- a/crates/storage-postgres/src/data/tx_helpers.rs +++ b/crates/storage-postgres/src/data/tx_helpers.rs @@ -12,10 +12,11 @@ use extenddb_core::types::{ }; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{SortKeyValue, parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{SortKeyValue, sk_column, sk_info}; use super::index::db_error; -use super::{data_table_name, json_to_item}; +use super::key_text::{parse_sk, pk_to_text}; +use super::{data_table_name, item_to_json, json_to_item, to_stored_json}; /// Fetch a single item within an existing transaction. pub(super) async fn fetch_item_in_tx( @@ -106,8 +107,7 @@ pub(super) async fn upsert_item_in_tx( .get(pk_name) .ok_or_else(|| StorageError::Internal("missing partition key".to_owned()))?; let pk_text = pk_to_text(pk_value)?; - let item_json = - serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_json = item_to_json(item)?; if let Some((sk_name, sk_type)) = sk_info(&key_info.key_schema, &key_info.attribute_definitions) { @@ -158,8 +158,7 @@ pub(super) async fn insert_item_if_absent_in_tx( .get(pk_name) .ok_or_else(|| StorageError::Internal("missing partition key".to_owned()))?; let pk_text = pk_to_text(pk_value)?; - let item_json = - serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_json = item_to_json(item)?; let rows_affected = if let Some((sk_name, sk_type)) = sk_info(&key_info.key_schema, &key_info.attribute_definitions) @@ -368,8 +367,7 @@ pub(super) async fn write_stream_record_in_tx( user_identity: capture.user_identity.clone(), }; - let record_json = - serde_json::to_value(&record).map_err(|e| StorageError::Internal(e.to_string()))?; + let record_json = to_stored_json(&record)?; sqlx::query( "INSERT INTO stream_records (sequence_number, shard_id, table_id, event_name, record_data) \ diff --git a/crates/storage-postgres/src/data/update_item.rs b/crates/storage-postgres/src/data/update_item.rs index 80ab9a515..75370f136 100755 --- a/crates/storage-postgres/src/data/update_item.rs +++ b/crates/storage-postgres/src/data/update_item.rs @@ -8,10 +8,13 @@ use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_core::validation; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{sk_column, sk_info}; + +use super::key_text::{parse_sk, pk_to_text}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; +use super::item_to_json; use super::query::check_condition; use super::tx_helpers::write_stream_record_in_tx; use super::{data_table_name, json_to_item}; @@ -213,8 +216,7 @@ impl PostgresEngine { let new_item = if return_new { Some(item.clone()) } else { None }; - let item_json = - serde_json::to_value(&item).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_json = item_to_json(&item)?; if old_json.is_some() { // Row existed and is locked by the read above, so update in place. diff --git a/crates/storage-postgres/src/data/vector_index.rs b/crates/storage-postgres/src/data/vector_index.rs index b48170e24..1a2f2bfa2 100644 --- a/crates/storage-postgres/src/data/vector_index.rs +++ b/crates/storage-postgres/src/data/vector_index.rs @@ -32,15 +32,15 @@ use extenddb_core::types::{AttributeDefinition, Item, KeySchemaElement, ScalarAttributeType}; use extenddb_core::validation::vector_item::{vector_components, vector_norm}; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{ - SortKeyValue, composite_pk_to_text, parse_sk, sk_column, sk_column_n, -}; +use extenddb_storage::util::{SortKeyValue, sk_column, sk_column_n}; + +use super::key_text::{composite_pk_to_text, parse_sk}; use extenddb_storage::vector_lifecycle::{ VectorApplyContext, VectorIndexMeta, item_is_indexable, item_partition, projected_payload, }; use pgvector::Vector; -use super::{all_sort_key_info, vector_table_name}; +use super::{all_sort_key_info, item_to_json, vector_table_name}; /// Read the vector index metadata for a table from the catalog. /// @@ -403,8 +403,7 @@ impl<'a> VectorInsertPlan<'a> { // vector attribute are the shared payload rules, so a live-written row and a // backfilled one cannot differ in shape. let projected = projected_payload(item, base_key_schema, meta); - let item_json = - serde_json::to_value(&projected).map_err(|e| StorageError::Internal(e.to_string()))?; + let item_json = item_to_json(&projected)?; // A plain INSERT, deliberately, where the GSI sibling upserts. Two callers reach // it and only one deletes first: the live write path through diff --git a/crates/storage-postgres/src/gsi_queue.rs b/crates/storage-postgres/src/gsi_queue.rs index f068089ed..44288f55d 100644 --- a/crates/storage-postgres/src/gsi_queue.rs +++ b/crates/storage-postgres/src/gsi_queue.rs @@ -26,11 +26,11 @@ use std::sync::Arc; +use crate::data::key_text::composite_pk_to_text; use extenddb_core::types::{ AttributeDefinition, AttributeValue, Item, KeySchemaElement, Projection, }; use extenddb_storage::error::StorageError; -use extenddb_storage::util::composite_pk_to_text; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use tokio::sync::Notify; @@ -322,16 +322,9 @@ pub(crate) async fn enqueue_gsi_pending( delay_ms: u64, context: &PendingApplyContext, ) -> Result<(), StorageError> { - let old_json = old_item - .map(serde_json::to_value) - .transpose() - .map_err(|e| StorageError::Internal(e.to_string()))?; - let new_json = new_item - .map(serde_json::to_value) - .transpose() - .map_err(|e| StorageError::Internal(e.to_string()))?; - let context_json = - serde_json::to_value(context).map_err(|e| StorageError::Internal(e.to_string()))?; + let old_json = old_item.map(crate::data::item_to_json).transpose()?; + let new_json = new_item.map(crate::data::item_to_json).transpose()?; + let context_json = crate::data::to_stored_json(context)?; // Route all updates for a given base item to one worker. // The base key is immutable over an item's lifetime; `new_item` carries it @@ -584,16 +577,9 @@ fn decode_row( new_json: Option, ctx_json: serde_json::Value, ) -> Result<(Option, Option, PendingApplyContext), StorageError> { - let old_item: Option = old_json - .map(serde_json::from_value) - .transpose() - .map_err(|e| StorageError::Internal(e.to_string()))?; - let new_item: Option = new_json - .map(serde_json::from_value) - .transpose() - .map_err(|e| StorageError::Internal(e.to_string()))?; - let context: PendingApplyContext = - serde_json::from_value(ctx_json).map_err(|e| StorageError::Internal(e.to_string()))?; + let old_item: Option = old_json.map(crate::data::json_to_item).transpose()?; + let new_item: Option = new_json.map(crate::data::json_to_item).transpose()?; + let context: PendingApplyContext = crate::data::stored_json_to(ctx_json)?; Ok((old_item, new_item, context)) } diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 9603d68ff..85db7204b 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -178,11 +178,16 @@ use extenddb_storage::error::StorageError; use sqlx::PgPool; use sqlx::postgres::PgPoolOptions; -/// Expected catalog version — compiled into the binary (REQ-CAT-006, D-9). +/// Expected catalog version, compiled into the binary (REQ-CAT-006, D-9). /// /// The tuple is the single source of truth. Use `CATALOG_VERSION.to_string()` /// wherever a string representation is needed. -pub const CATALOG_VERSION: CatalogVersion = CatalogVersion::new(0, 0, 4); +/// +/// 0.0.5 changed no schema: it marks the stored string encoding introduced with +/// data migration `004_escape_control_chars`, so that a binary from an earlier +/// release refuses a migrated deployment instead of reading escaped strings as +/// literal data. +pub const CATALOG_VERSION: CatalogVersion = CatalogVersion::new(0, 0, 5); /// Minimum number of connections allowed per pool. /// @@ -603,6 +608,38 @@ impl PostgresEngine { Ok(()) } + /// Refuse to serve a data database whose stored strings have not been + /// brought to this build's encoding. + /// + /// The escape in `extenddb_storage::util::escape_control` stores U+0001 as a + /// two-character sequence, and the migration that re-encodes rows written by + /// older builds (`004_escape_control_chars`) rewrites every row that contains + /// U+0001. It cannot tell a row this build wrote from a legacy one, so this + /// build must not write anything before the migration has run. `extenddb + /// init` records the migration on a fresh deployment; an upgrade runs + /// `extenddb migrate --yes` after stopping every older server and before + /// starting this one. + /// + /// # Errors + /// + /// Returns `StorageError::Internal` naming the migration and the command to + /// run when the data database's `schema_history` does not record it. + pub async fn check_data_migrations_applied(&self) -> Result<(), StorageError> { + let missing = migrations::unapplied_required_data_migrations(&self.data_pool) + .await + .map_err(|e| StorageError::Connection(format!("{e:?}")))?; + if missing.is_empty() { + return Ok(()); + } + Err(StorageError::Internal(format!( + "Data migration not applied: {}. This build stores strings in a different \ + encoding from earlier builds, so it must not serve until the existing rows \ + have been re-encoded. Stop every older ExtendDB server that uses this data \ + database, run 'extenddb migrate --yes', then start this server.", + missing.join(", ") + ))) + } + /// Everything `serve` checks and changes in the catalog before serving, /// in order; returns the shape steps applied. /// @@ -921,6 +958,18 @@ fn server_components_factory( tracing::warn!("converged the catalog shape at startup: {step}"); } + // This build stores strings through the control-character escape, and the + // re-encoding migration cannot tell a row this build wrote from a row an + // older build wrote (both can hold U+0001). Serving before the migration + // has run would let the migration later rewrite this build's own rows, so + // refuse to start until it is recorded. `extenddb init` records it on a + // fresh deployment; an upgraded deployment runs `extenddb migrate --yes` + // with every older server stopped. + engine + .check_data_migrations_applied() + .await + .map_err(|e| BackendError::InitializationFailed(e.to_string()))?; + // Rebuild any vector index a crash left CREATING, before serving: an index // in that state is not searchable, and nothing else will repair it. match crate::data::vector_index::reconcile_incomplete_vector_indexes(&engine).await { diff --git a/crates/storage-postgres/src/metadata_engine.rs b/crates/storage-postgres/src/metadata_engine.rs index b2f958b3b..6ef499c04 100755 --- a/crates/storage-postgres/src/metadata_engine.rs +++ b/crates/storage-postgres/src/metadata_engine.rs @@ -292,7 +292,9 @@ impl MetadataEngine for PostgresEngine { ) -> BoxFuture<'_, Result<(), StorageError>> { let account_id = account_id.to_string(); let table_name = table_name.to_string(); - let ttl_attribute = ttl_attribute.to_string(); + // Stored attribute names carry the same escape as the rest of item_data, + // so the name SQL addresses must be the stored form. + let ttl_attribute = extenddb_storage::util::escape_control(ttl_attribute).into_owned(); Box::pin(async move { Self::validate_account_id(&account_id)?; let (table_id,): (String,) = sqlx::query_as( @@ -408,7 +410,9 @@ impl MetadataEngine for PostgresEngine { ) -> BoxFuture<'_, Result, StorageError>> { let account_id = account_id.to_string(); let table_name = table_name.to_string(); - let ttl_attribute = ttl_attribute.to_string(); + // Stored attribute names carry the same escape as the rest of item_data, + // so the name SQL addresses must be the stored form. + let ttl_attribute = extenddb_storage::util::escape_control(ttl_attribute).into_owned(); Box::pin(async move { Self::validate_account_id(&account_id)?; let (table_id,): (String,) = sqlx::query_as( diff --git a/crates/storage-postgres/src/migrations.rs b/crates/storage-postgres/src/migrations.rs index 952f7920a..29502042d 100755 --- a/crates/storage-postgres/src/migrations.rs +++ b/crates/storage-postgres/src/migrations.rs @@ -20,6 +20,10 @@ pub(crate) const CATALOG_MIGRATIONS: &[(&str, &str)] = &[ "003_backup_definitions.sql", include_str!("../../storage-postgres/migrations/003_backup_definitions.sql"), ), + ( + "004_control_chars_encoding.sql", + include_str!("../../storage-postgres/migrations/004_control_chars_encoding.sql"), + ), ]; /// The runner's convergence write, executed after the walk over @@ -333,7 +337,154 @@ pub(crate) async fn run_data_migrations(pool: &PgPool) -> OpResult<()> { /// outside a transaction (they use `CREATE INDEX CONCURRENTLY`), so they cannot /// be expressed as SQL in [`DATA_MIGRATIONS`]. Applied by `extenddb migrate` /// after the SQL migrations, so the operator controls when the change happens. -pub(crate) const DATA_CODE_MIGRATIONS: &[&str] = &["003_gsi_base_key_index"]; +pub(crate) const DATA_CODE_MIGRATIONS: &[&str] = + &["003_gsi_base_key_index", "004_escape_control_chars"]; + +/// Code migrations a server must see recorded before it serves. `003` only adds +/// an index and a server runs correctly without it; `004` changes the stored +/// form of strings, and a server that wrote through the new escape before the +/// migration ran would have its own rows rewritten by it (see +/// [`escape_legacy_control_chars`]). `PostgresEngine::check_data_migrations_applied` +/// refuses to start on a data database missing any of these. +pub(crate) const REQUIRED_DATA_CODE_MIGRATIONS: &[&str] = &["004_escape_control_chars"]; + +/// `application_name` the init and migrate commands set on their connections, +/// so [`refuse_if_other_clients_connected`] can leave them out of its count. +pub(crate) const MIGRATE_APPLICATION_NAME: &str = "extenddb-migrate"; + +/// Environment variable that skips [`refuse_if_other_clients_connected`], for a +/// data database whose only other connections are known to be idle (a +/// connection pooler holding server-side connections open, for example). +pub(crate) const IGNORE_CONNECTIONS_ENV: &str = "EXTENDDB_MIGRATE_IGNORE_CONNECTIONS"; + +/// Refuse to run a data-rewriting migration while anything else is connected +/// to the database `pool` reaches. `which` names that database in the refusal +/// (`"data"` or `"catalog"`). +/// +/// `004_escape_control_chars` rewrites rows in place and cannot tell a row a +/// running server writes from a legacy row: an older server still writing +/// leaves unescaped rows behind, and a server of this release writing before +/// the migration finishes gets its rows double-escaped. The upgrade manual +/// requires every server to be stopped first; this check catches the case +/// where one was not. Connections carrying [`MIGRATE_APPLICATION_NAME`] are +/// this process's own and are ignored; every other session on the database +/// counts. Managed environments where a pooler keeps idle connections open +/// can set [`IGNORE_CONNECTIONS_ENV`] to skip the check. +/// +/// The migrate command connects as the application role, which is not a +/// superuser. For sessions of other roles, `PostgreSQL` then shows `datname`, +/// `usename`, and `application_name` but hides `backend_type` and +/// `client_addr`, so a filter on `backend_type` alone misses an operator's +/// `psql` or a server running under another role. A session is counted when it +/// has a role (`usename`), which background workers such as autovacuum never +/// have, and its type is either `client backend` or hidden. +pub(crate) async fn refuse_if_other_clients_connected(pool: &PgPool, which: &str) -> OpResult<()> { + let others: Vec<(String, Option, Option)> = sqlx::query_as( + "SELECT usename::text, application_name, client_addr::text \ + FROM pg_stat_activity \ + WHERE datname = current_database() \ + AND usename IS NOT NULL \ + AND coalesce(backend_type, 'client backend') = 'client backend' \ + AND pid <> pg_backend_pid() \ + AND coalesce(application_name, '') <> $1", + ) + .bind(MIGRATE_APPLICATION_NAME) + .fetch_all(pool) + .await + .map_err(|e| OpError::Internal(format!("Check for other connections: {e}")))?; + if others.is_empty() { + return Ok(()); + } + let mut described: Vec = others + .iter() + .map(|(user, app, addr)| { + format!( + "{user} from {} ({})", + addr.as_deref().unwrap_or("no client address shown"), + match app.as_deref() { + Some("") | None => "no application name", + Some(a) => a, + } + ) + }) + .collect(); + described.sort(); + described.dedup(); + Err(OpError::Internal(format!( + "{} other connection(s) hold the {which} database: {}. This migration rewrites \ + stored rows and must run with every ExtendDB server stopped and every other \ + session closed. Stop them and run 'extenddb migrate --yes' again. If the only \ + other connections are idle ones held by a connection pooler, set \ + {IGNORE_CONNECTIONS_ENV}=1 to skip this check.", + others.len(), + described.join("; ") + ))) +} + +/// The server address, port, and database name a pool is connected to. +/// +/// Two pools with the same identity reach the same database, so a connection +/// check on one covers the other. The address is `None` over a Unix socket on +/// both sides of a same-host comparison, which still compares equal. +async fn database_identity(pool: &PgPool) -> OpResult<(Option, Option, String)> { + sqlx::query_as("SELECT inet_server_addr()::text, inet_server_port(), current_database()::text") + .fetch_one(pool) + .await + .map_err(|e| OpError::Internal(format!("Identify the database: {e}"))) +} + +/// [`refuse_if_other_clients_connected`] on every database +/// `004_escape_control_chars` rewrites: the data database, and the catalog +/// database when it is a different one, because `backup_items` lives there. +/// A deployment whose catalog and data share one database is checked once. +pub(crate) async fn refuse_if_other_clients_connected_anywhere( + catalog_pool: &PgPool, + data_pool: &PgPool, +) -> OpResult<()> { + refuse_if_other_clients_connected(data_pool, "data").await?; + if database_identity(catalog_pool).await? != database_identity(data_pool).await? { + refuse_if_other_clients_connected(catalog_pool, "catalog").await?; + } + Ok(()) +} + +/// True when `004_escape_control_chars` still has to run on this data database +/// and the operator has not set [`IGNORE_CONNECTIONS_ENV`], so the migrate +/// command must hold the databases alone before it writes anything. +pub(crate) async fn needs_exclusive_access(data_pool: &PgPool) -> OpResult { + if std::env::var_os(IGNORE_CONNECTIONS_ENV).is_some() { + return Ok(false); + } + Ok(!is_migration_applied(data_pool, "004_escape_control_chars").await?) +} + +/// Names in [`REQUIRED_DATA_CODE_MIGRATIONS`] not recorded in this data +/// database's `schema_history`. +pub(crate) async fn unapplied_required_data_migrations(pool: &PgPool) -> OpResult> { + let mut missing = Vec::new(); + for name in REQUIRED_DATA_CODE_MIGRATIONS { + if !is_migration_applied(pool, name).await? { + missing.push((*name).to_owned()); + } + } + Ok(missing) +} + +/// How `004_escape_control_chars` treats other sessions on the databases it +/// rewrites. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum OtherSessions { + /// Refuse to write while any other session holds either database (see + /// [`refuse_if_other_clients_connected`]), unless the operator set + /// [`IGNORE_CONNECTIONS_ENV`]. Every path an operator runs. + Refuse, + /// Write regardless. For [`apply_all_migrations`] on scratch databases a + /// test harness created and holds alone: its own unnamed pools are the only + /// sessions, and a fresh database has no legacy row for a server to miss. + /// Compiled only with `test-hooks`, as that function is. + #[cfg(feature = "test-hooks")] + Allow, +} /// Run programmatic data migrations, skipping already-applied ones. /// @@ -344,6 +495,16 @@ pub(crate) const DATA_CODE_MIGRATIONS: &[&str] = &["003_gsi_base_key_index"]; pub(crate) async fn run_data_code_migrations( catalog_pool: &PgPool, data_pool: &PgPool, +) -> OpResult<()> { + run_data_code_migrations_with(catalog_pool, data_pool, OtherSessions::Refuse).await +} + +/// [`run_data_code_migrations`] with `004_escape_control_chars`'s session +/// check chosen by the caller. +async fn run_data_code_migrations_with( + catalog_pool: &PgPool, + data_pool: &PgPool, + other_sessions: OtherSessions, ) -> OpResult<()> { for name in DATA_CODE_MIGRATIONS { if is_migration_applied(data_pool, name).await? { @@ -355,6 +516,19 @@ pub(crate) async fn run_data_code_migrations( "003_gsi_base_key_index" => { ensure_gsi_base_key_indexes(catalog_pool, data_pool).await?; } + "004_escape_control_chars" => { + // Rows written by a server that is still running would be missed + // (an older release) or double-escaped (this release); see + // `refuse_if_other_clients_connected`. `extenddb migrate` runs + // the same check before its first write; this one covers any + // other caller. + if other_sessions == OtherSessions::Refuse + && std::env::var_os(IGNORE_CONNECTIONS_ENV).is_none() + { + refuse_if_other_clients_connected_anywhere(catalog_pool, data_pool).await?; + } + escape_legacy_control_chars(catalog_pool, data_pool).await?; + } other => { return Err(OpError::Internal(format!( "Unknown data code migration: {other}" @@ -373,6 +547,11 @@ pub(crate) async fn run_data_code_migrations( /// in this crate's own `tests/` directory, which otherwise copy the file /// lists and go stale when a migration is added here. /// +/// The harness's own pools are the only sessions on its scratch databases, +/// so `004_escape_control_chars` runs without the check for other sessions +/// that `extenddb migrate` makes; the migrate command's pools carry +/// [`MIGRATE_APPLICATION_NAME`] for the same reason. +/// /// # Errors /// /// Returns the first migration's error, formatted. @@ -385,7 +564,7 @@ pub async fn apply_all_migrations(catalog: &PgPool, data: &PgPool) -> Result<(), run_data_migrations(data) .await .map_err(|e| format!("{e:?}"))?; - run_data_code_migrations(catalog, data) + run_data_code_migrations_with(catalog, data, OtherSessions::Allow) .await .map_err(|e| format!("{e:?}")) } @@ -447,6 +626,355 @@ async fn ensure_gsi_base_key_indexes(catalog_pool: &PgPool, data_pool: &PgPool) Ok(()) } +/// Progress ledger for multi-table data code migrations: one row per +/// (migration, table) pair, committed in the same transaction as that table's +/// rewrite, so a re-run after a crash knows exactly which tables are done. +const CODE_MIGRATION_PROGRESS_TABLE: &str = "data_code_migration_progress"; + +/// Create the progress ledger if this database does not have one yet. +async fn ensure_progress_table(pool: &PgPool) -> OpResult<()> { + sqlx::query(&format!( + "CREATE TABLE IF NOT EXISTS {CODE_MIGRATION_PROGRESS_TABLE} (\ + migration_name TEXT NOT NULL, \ + table_name TEXT NOT NULL, \ + completed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), \ + PRIMARY KEY (migration_name, table_name)\ + )" + )) + .execute(pool) + .await + .map_err(|e| OpError::Internal(format!("Create migration progress table: {e}")))?; + Ok(()) +} + +/// Whether the progress ledger says `table` is already done for `migration`. +async fn is_table_marked(pool: &PgPool, migration: &str, table: &str) -> OpResult { + let marked: bool = sqlx::query_scalar(&format!( + "SELECT EXISTS(SELECT 1 FROM {CODE_MIGRATION_PROGRESS_TABLE} \ + WHERE migration_name = $1 AND table_name = $2)" + )) + .bind(migration) + .bind(table) + .fetch_one(pool) + .await + .map_err(|e| OpError::Internal(format!("Check migration progress: {e}")))?; + Ok(marked) +} + +/// One physical table's rewrite work for `004_escape_control_chars`: the text +/// key columns that get the single-statement SQL replace, and the jsonb +/// columns whose rows are re-encoded one by one. +struct EscapeWork { + /// Bare (unquoted) table name, e.g. `_ddb_` or `gsi_pending`. + table: String, + text_columns: Vec, + jsonb_columns: Vec, +} + +/// Rewrite work for a dynamically named `_ddb_*` table, read from +/// `information_schema.columns` so that exactly the sort key columns this +/// table has (`sk_s`, `sk_s`, `base_sk_s`, ...) are covered. Returns +/// `None` when the physical table does not exist (a catalog row mid-create or +/// mid-delete): such a table has no legacy rows to re-encode. +async fn dynamic_table_work(pool: &PgPool, table: String) -> OpResult> { + let text_columns: Vec = sqlx::query_scalar( + "SELECT column_name::text FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'text' \ + AND (column_name IN ('pk', 'base_pk') OR column_name::text ~ '^(base_)?sk[0-9]*_s$') \ + ORDER BY ordinal_position", + ) + .bind(&table) + .fetch_all(pool) + .await + .map_err(|e| OpError::Internal(format!("List text key columns of {table}: {e}")))?; + + let jsonb_columns: Vec = sqlx::query_scalar( + "SELECT column_name::text FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'jsonb' \ + AND column_name = 'item_data'", + ) + .bind(&table) + .fetch_all(pool) + .await + .map_err(|e| OpError::Internal(format!("List jsonb columns of {table}: {e}")))?; + + if text_columns.is_empty() && jsonb_columns.is_empty() { + return Ok(None); + } + Ok(Some(EscapeWork { + table, + text_columns, + jsonb_columns, + })) +} + +/// Rewrite work for a fixed-name table, with the candidate columns filtered +/// through `information_schema.columns` so a column absent on this deployment +/// is skipped. Returns `None` when the table itself is absent. +async fn fixed_table_work( + pool: &PgPool, + table: &str, + text_candidates: &[&str], + jsonb_candidates: &[&str], +) -> OpResult> { + if !table_exists(pool, table).await? { + return Ok(None); + } + let text_candidates: Vec = text_candidates.iter().map(|c| (*c).to_owned()).collect(); + let jsonb_candidates: Vec = jsonb_candidates.iter().map(|c| (*c).to_owned()).collect(); + let text_columns: Vec = sqlx::query_scalar( + "SELECT column_name::text FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'text' \ + AND column_name::text = ANY($2) \ + ORDER BY ordinal_position", + ) + .bind(table) + .bind(&text_candidates) + .fetch_all(pool) + .await + .map_err(|e| OpError::Internal(format!("List text columns of {table}: {e}")))?; + let jsonb_columns: Vec = sqlx::query_scalar( + "SELECT column_name::text FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'jsonb' \ + AND column_name::text = ANY($2) \ + ORDER BY ordinal_position", + ) + .bind(table) + .bind(&jsonb_candidates) + .fetch_all(pool) + .await + .map_err(|e| OpError::Internal(format!("List jsonb columns of {table}: {e}")))?; + Ok(Some(EscapeWork { + table: table.to_owned(), + text_columns, + jsonb_columns, + })) +} + +/// The re-encoded form of a stored jsonb value, or `None` when re-encoding +/// does not change it. `escape_json_strings` only changes strings and object +/// keys containing U+0000 or U+0001, so a plain document and a document whose +/// strings merely contain the literal six-character text backslash-u-0001 both +/// come back equal and are skipped. +fn reencoded_json(value: &serde_json::Value) -> Option { + let escaped = extenddb_storage::util::escape_json_strings(value.clone()); + (escaped != *value).then_some(escaped) +} + +/// Re-encode the rows of one jsonb column whose stored document contains +/// U+0001. Runs inside the caller's per-table transaction. +/// +/// The candidate ctids are snapshotted once, before any row of this column is +/// touched, so no row is ever visited twice; the updates relocate rows (a ctid +/// names a physical row version), but always after that row's value was read. +/// A parameterized `DECLARE CURSOR` cannot be issued through the extended +/// protocol, so the locked-snapshot form of a streamed fetch is used instead, +/// and the values are then fetched in batches of 500 by ctid so a large table +/// never loads into memory. The matching set is tiny in practice; the table +/// scan, not the writes, is the cost. +async fn escape_jsonb_rows( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + quoted_table: &str, + col: &str, +) -> OpResult { + // '\u0001' (six characters) is how jsonb::text renders a raw U+0001 inside + // a string or key. It also matches a stored string whose content is a + // literal backslash followed by u0001 (rendered '\\u0001'), which is + // harmless: that row re-encodes to itself and is skipped below. jsonb text + // rendering is why SQL-level replace() is not used here: it would corrupt + // exactly that literal-backslash case. The backslash is spelled chr(92) so + // the predicate reads the same under either value of + // standard_conforming_strings; a plain '\u0001' literal would become the + // single byte 0x01 with the setting off and match nothing. + let select_ctids = format!( + "SELECT ctid::text FROM {quoted_table} \ + WHERE position((chr(92) || 'u0001') IN \"{col}\"::text) > 0 FOR UPDATE" + ); + let ctids: Vec = sqlx::query_scalar(&select_ctids) + .fetch_all(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Find rows to re-encode in {quoted_table}: {e}")))?; + + let fetch_batch = + format!("SELECT ctid::text, \"{col}\" FROM {quoted_table} WHERE ctid = ANY($1::tid[])"); + let update_row = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); + let mut changed: u64 = 0; + for batch in ctids.chunks(500) { + let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&fetch_batch) + .bind(batch.to_vec()) + .fetch_all(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Fetch rows from {quoted_table}: {e}")))?; + for (ctid, value) in rows { + if let Some(escaped) = reencoded_json(&value) { + sqlx::query(&update_row) + .bind(escaped) + .bind(&ctid) + .execute(&mut **tx) + .await + .map_err(|e| { + OpError::Internal(format!("Re-encode a row of {quoted_table}: {e}")) + })?; + changed += 1; + } + } + } + Ok(changed) +} + +/// Rewrite one table in one transaction and mark it done in the progress +/// ledger before committing, so the rewrite and the marker are atomic. +async fn escape_rows_in_table(pool: &PgPool, work: &EscapeWork) -> OpResult { + let mut tx = pool + .begin() + .await + .map_err(|e| OpError::Internal(format!("Begin transaction for {}: {e}", work.table)))?; + let quoted = format!("\"{}\"", work.table); + let mut rewritten: u64 = 0; + + // Key text columns: TEXT has no escaping layer, so a single SQL statement + // per column is exact. NULL columns never match (position() is NULL). + for col in &work.text_columns { + let sql = format!( + "UPDATE {quoted} SET \"{col}\" = replace(\"{col}\", chr(1), chr(1) || chr(2)) \ + WHERE position(chr(1) IN \"{col}\") > 0" + ); + let done = sqlx::query(&sql) + .execute(&mut *tx) + .await + .map_err(|e| OpError::Internal(format!("Re-encode {}.{col}: {e}", work.table)))?; + rewritten += done.rows_affected(); + } + + for col in &work.jsonb_columns { + rewritten += escape_jsonb_rows(&mut tx, "ed, col).await?; + } + + sqlx::query(&format!( + "INSERT INTO {CODE_MIGRATION_PROGRESS_TABLE} (migration_name, table_name) \ + VALUES ($1, $2) ON CONFLICT DO NOTHING" + )) + .bind("004_escape_control_chars") + .bind(&work.table) + .execute(&mut *tx) + .await + .map_err(|e| OpError::Internal(format!("Mark {} as re-encoded: {e}", work.table)))?; + + tx.commit() + .await + .map_err(|e| OpError::Internal(format!("Commit re-encode of {}: {e}", work.table)))?; + Ok(rewritten) +} + +/// Re-encode legacy rows that contain a raw U+0001 (`004_escape_control_chars`). +/// +/// Strings are stored through the order-preserving escape in +/// `extenddb_storage::util::escape_control` (U+0000 becomes U+0001 U+0001, +/// U+0001 becomes U+0001 U+0002). Rows written before the escape existed hold +/// their strings raw. The decoder keeps a stray U+0001 literal, so the only +/// legacy rows it can misread are those where a raw U+0001 is immediately +/// followed by U+0001 or U+0002; rewriting every row containing U+0001 removes +/// that case. Legacy rows never contain U+0000 (PostgreSQL refused it), so for +/// legacy data applying the escape to the raw stored value is exactly the +/// re-encode, and rows without U+0001 encode to themselves and are left alone. +/// +/// Crash safety. This migration is NOT idempotent at the row level: escaped +/// data also contains U+0001 (the first character of every escape pair), and a +/// legacy U+0001 U+0002 is indistinguishable from an escaped U+0001, so +/// applying the escape to an already-escaped row would double-escape it. A +/// partially rewritten table must therefore never be rescanned. Each table is +/// processed in one transaction: its matching rows are rewritten, a marker row +/// (migration_name, table_name) is inserted into the small progress table +/// created at the start of this migration, and the transaction commits. A +/// re-run after a crash skips tables that carry a marker and resumes with the +/// rest; when every table is marked, the caller records the migration in +/// `schema_history` exactly as `003` does, and the usual +/// `is_migration_applied` guard makes later runs no-ops. Marker rows are kept +/// forever: deleting them before the `schema_history` row is durable would +/// reopen the rescan window. +/// +/// Rows written by THIS build are indistinguishable from legacy rows for the +/// same reason (an escaped U+0001 is stored as U+0001 U+0002), so the server +/// refuses to start on a data database that does not record this migration +/// (`PostgresEngine::check_data_migrations_applied`). The migration therefore +/// only ever sees rows written by older builds, provided every older server +/// is stopped before it runs; `extenddb init` records it on a fresh deployment. `backup_items` lives in the catalog database +/// while every other table lives in the data database, and a transaction +/// cannot span two databases, so each database gets its own progress table and +/// each marker commits with the table it marks. +async fn escape_legacy_control_chars(catalog_pool: &PgPool, data_pool: &PgPool) -> OpResult<()> { + const NAME: &str = "004_escape_control_chars"; + ensure_progress_table(data_pool).await?; + ensure_progress_table(catalog_pool).await?; + + let mut work: Vec<(&PgPool, EscapeWork)> = Vec::new(); + + // Every data table, index table, and vector index table, enumerated from + // the catalog. Their text key columns are read from information_schema so + // single-sort-key, multi-sort-key, and base_* layouts are all covered. + let table_ids: Vec = + sqlx::query_scalar("SELECT table_id FROM tables ORDER BY table_id") + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate tables: {e}")))?; + for id in table_ids { + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}")).await? { + work.push((data_pool, w)); + } + } + let index_ids: Vec = + sqlx::query_scalar("SELECT index_id FROM indexes ORDER BY index_id") + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate indexes: {e}")))?; + for id in index_ids { + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}")).await? { + work.push((data_pool, w)); + } + } + let vector_ids: Vec = + sqlx::query_scalar("SELECT index_id FROM vector_indexes ORDER BY index_id") + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate vector indexes: {e}")))?; + for id in vector_ids { + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_vec_{id}")).await? { + work.push((data_pool, w)); + } + } + + // Fixed tables holding item documents. gsi_pending and stream_records live + // in the data database; backup_items lives in the catalog database. + if let Some(w) = fixed_table_work( + data_pool, + "gsi_pending", + &[], + &["old_item", "new_item", "index_context"], + ) + .await? + { + work.push((data_pool, w)); + } + if let Some(w) = fixed_table_work(data_pool, "stream_records", &[], &["record_data"]).await? { + work.push((data_pool, w)); + } + if let Some(w) = + fixed_table_work(catalog_pool, "backup_items", &["pk", "sk"], &["item_data"]).await? + { + work.push((catalog_pool, w)); + } + + for (pool, w) in &work { + if is_table_marked(pool, NAME, &w.table).await? { + println!(" {}: already re-encoded, skipping.", w.table); + continue; + } + let rewritten = escape_rows_in_table(pool, w).await?; + println!(" {}: {rewritten} row update(s)", w.table); + } + Ok(()) +} + /// Check if a table exists in the public schema. pub(crate) async fn table_exists(pool: &PgPool, name: &str) -> OpResult { let exists: bool = sqlx::query_scalar( @@ -527,6 +1055,30 @@ mod tests { use super::CATALOG_MIGRATIONS; use crate::CATALOG_VERSION; + /// `reencoded_json` is what decides whether a stored jsonb row is + /// rewritten by `004_escape_control_chars`, so it must change exactly the + /// rows holding a raw control character and nothing else. + #[test] + fn reencoded_json_changes_exactly_the_rows_holding_raw_control_chars() { + use serde_json::json; + + // Raw U+0001 in a string value and in an object key: rewritten, with + // each U+0001 becoming U+0001 U+0002 wherever it appears. + let raw = json!({"k\u{1}": {"S": "v\u{1}"}, "plain": {"N": "1"}}); + let expected = json!({"k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}, "plain": {"N": "1"}}); + assert_eq!(super::reencoded_json(&raw), Some(expected)); + + // A string whose content is the literal six-character text + // backslash-u-0001: the SQL candidate filter over-matches it, and this + // check is what keeps it byte-identical. + let literal = json!({"note": {"S": "x\\u0001y"}}); + assert_eq!(super::reencoded_json(&literal), None); + + // A plain document: untouched. + let plain = json!({"pk": {"S": "p"}, "m": {"M": {"k": {"S": "v"}}}}); + assert_eq!(super::reencoded_json(&plain), None); + } + /// The catalog version and the migration list must move together. /// /// A migration that creates its schema without moving the version leaves a @@ -539,10 +1091,10 @@ mod tests { fn the_migration_count_and_the_catalog_version_agree() { assert_eq!( CATALOG_MIGRATIONS.len(), - 3, + 4, "a catalog migration was added or removed; update CATALOG_VERSION and this count" ); - assert_eq!(CATALOG_VERSION.to_string(), "0.0.4"); + assert_eq!(CATALOG_VERSION.to_string(), "0.0.5"); } /// The version the binary expects must be the version the schema writes. @@ -684,3 +1236,751 @@ mod tests { assert!(absent, "an absent version proceeds"); } } + +#[cfg(test)] +mod live_reencode { + //! Live checks for `004_escape_control_chars` against a scratch database. + //! + //! Follows the convention of `tests/key_collation.rs`: each test needs + //! `EXTENDDB_TEST_PG_CONNECTION_STRING` (a base URL with no database name, + //! for example `postgresql://postgres:postgres@127.0.0.1:5432`), builds a + //! throwaway database, and drops it when it passes. Without the variable + //! every test here reports a skip and passes. One database serves as both + //! catalog and data, as the storage-level tests do. + + use serde_json::json; + use sqlx::PgPool; + use sqlx::postgres::PgPoolOptions; + + use super::{ + CATALOG_MIGRATIONS, DATA_MIGRATIONS, IGNORE_CONNECTIONS_ENV, MIGRATE_APPLICATION_NAME, + needs_exclusive_access, pending_data_migrations, refuse_if_other_clients_connected, + refuse_if_other_clients_connected_anywhere, run_data_code_migrations, + unapplied_required_data_migrations, + }; + + struct Scratch { + db: PgPool, + admin: PgPool, + db_name: String, + } + + impl Scratch { + async fn cleanup(self) { + let Scratch { db, admin, db_name } = self; + db.close().await; + sqlx::query(&format!( + "DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)" + )) + .execute(&admin) + .await + .expect("drop the scratch database"); + admin.close().await; + } + } + + fn base_conn() -> Option { + let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").ok()?; + (!conn.trim().is_empty()).then(|| conn.trim_end_matches('/').to_owned()) + } + + fn skip(test: &str) { + eprintln!( + "SKIP {test}: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is no \ + PostgreSQL to build a scratch database in." + ); + } + + async fn scratch() -> Scratch { + let base = base_conn().expect("caller checks base_conn() first"); + let db_name = format!("eddb_esc_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); + let admin = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/postgres")) + .await + .expect("connect to the postgres maintenance database"); + sqlx::query(&format!("CREATE DATABASE \"{db_name}\"")) + .execute(&admin) + .await + .expect("create the scratch database"); + // Named like the migrate command, so the connection guard on 004 treats + // this pool as the migration's own. + let db = PgPoolOptions::new() + .max_connections(2) + .connect_with( + format!("{base}/{db_name}") + .parse::() + .expect("scratch connection string") + .application_name(MIGRATE_APPLICATION_NAME), + ) + .await + .expect("connect to the scratch database"); + for (_, sql) in CATALOG_MIGRATIONS.iter().chain(DATA_MIGRATIONS) { + sqlx::raw_sql(sql) + .execute(&db) + .await + .expect("apply a shipped migration"); + } + // 003 creates its indexes from parsed catalog key schemas and is not + // what these tests exercise, so record it as already applied. + sqlx::query("INSERT INTO schema_history (filename) VALUES ('003_gsi_base_key_index')") + .execute(&db) + .await + .expect("record 003 as applied"); + Scratch { db, admin, db_name } + } + + /// Seed a data table, an index table, `gsi_pending`, `stream_records`, and + /// `backup_items` with three row kinds: raw U+0001 in key columns and + /// inside jsonb strings and object keys, the literal six-character text + /// backslash-u-0001 inside a jsonb string, and plain rows. + async fn seed(db: &PgPool) { + let ks = json!([ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let ad = json!([ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"} + ]); + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES ($1, $2)") + .bind("111122223333") + .bind("esc-check") + .execute(db) + .await + .expect("seed the account row"); + sqlx::query( + "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ + table_status, table_arn, table_id) \ + VALUES ($1, 't', $2, $3, 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/t', 't1')", + ) + .bind("111122223333") + .bind(&ks) + .bind(&ad) + .execute(db) + .await + .expect("seed the tables row"); + sqlx::query( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ + projection) VALUES ('t1', 'i1', 'gsi1', 'GSI', $1, $2)", + ) + .bind(json!([{"AttributeName": "gpk", "KeyType": "HASH"}])) + .bind(json!({"ProjectionType": "ALL"})) + .execute(db) + .await + .expect("seed the indexes row"); + + sqlx::raw_sql( + r#"CREATE TABLE "_ddb_t1" ( + pk TEXT COLLATE "C" NOT NULL, + sk_s TEXT COLLATE "C", + sk_n NUMERIC, + sk_b BYTEA, + item_data JSONB NOT NULL, + PRIMARY KEY (pk, sk_s) + ); + CREATE TABLE "_ddb_i1" ( + pk TEXT COLLATE "C" NOT NULL, + sk_s TEXT COLLATE "C", + sk_n NUMERIC, + sk_b BYTEA, + base_pk TEXT COLLATE "C" NOT NULL, + base_sk_s TEXT COLLATE "C", + base_sk_n NUMERIC, + base_sk_b BYTEA, + item_data JSONB NOT NULL, + PRIMARY KEY (pk, base_pk, base_sk_s) + );"#, + ) + .execute(db) + .await + .expect("create the physical data and index tables"); + + for (pk, sk, item) in [ + ( + "a\u{1}b", + "s\u{1}", + json!({"pk": {"S": "a\u{1}b"}, "k\u{1}": {"S": "v\u{1}"}}), + ), + ("lit", "s", json!({"note": {"S": "x\\u0001y"}})), + ("plain", "s", json!({"pk": {"S": "plain"}})), + ] { + sqlx::query("INSERT INTO \"_ddb_t1\" (pk, sk_s, item_data) VALUES ($1, $2, $3)") + .bind(pk) + .bind(sk) + .bind(item) + .execute(db) + .await + .expect("seed a data table row"); + } + for (pk, sk, base_pk, base_sk, item) in [ + ( + "g\u{1}", + "gs\u{1}", + "a\u{1}b", + "s\u{1}", + json!({"gpk": {"S": "g\u{1}"}}), + ), + ("zz", "zs", "plain", "s", json!({"gpk": {"S": "zz"}})), + ] { + sqlx::query( + "INSERT INTO \"_ddb_i1\" (pk, sk_s, base_pk, base_sk_s, item_data) \ + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(pk) + .bind(sk) + .bind(base_pk) + .bind(base_sk) + .bind(item) + .execute(db) + .await + .expect("seed an index table row"); + } + + for (new_item, context) in [ + (json!({"pk": {"S": "a\u{1}b"}}), json!({"k\u{1}": 1})), + (json!({"pk": {"S": "p"}}), json!({"k": 1})), + ] { + sqlx::query( + "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ + index_context) VALUES ('t1', 0, NULL, $1, $2)", + ) + .bind(new_item) + .bind(context) + .execute(db) + .await + .expect("seed a gsi_pending row"); + } + + sqlx::query( + "INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \ + VALUES ('shard-1', 't1', '1')", + ) + .execute(db) + .await + .expect("seed the stream shard"); + for (seq, record) in [ + ("1", json!({"Keys": {"pk": {"S": "a\u{1}b"}}})), + ("2", json!({"Keys": {"pk": {"S": "p"}}})), + ] { + sqlx::query( + "INSERT INTO stream_records (shard_id, sequence_number, table_id, event_name, \ + record_data) VALUES ('shard-1', $1, 't1', 'INSERT', $2)", + ) + .bind(seq) + .bind(record) + .execute(db) + .await + .expect("seed a stream record"); + } + + sqlx::query( + "INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, \ + key_schema, attribute_definitions) \ + VALUES ('arn:aws:dynamodb:us-east-1:111122223333:table/t/backup/b1', 'b1', 't1', \ + 't', '111122223333', $1, $2)", + ) + .bind(&ks) + .bind(&ad) + .execute(db) + .await + .expect("seed the backups row"); + for (pk, sk, item) in [ + ("p\u{1}", Some("s\u{1}"), json!({"pk": {"S": "p\u{1}"}})), + ("plain", None, json!({"pk": {"S": "plain"}})), + ] { + sqlx::query( + "INSERT INTO backup_items (backup_arn, pk, sk, item_data) \ + VALUES ('arn:aws:dynamodb:us-east-1:111122223333:table/t/backup/b1', $1, $2, $3)", + ) + .bind(pk) + .bind(sk) + .bind(item) + .execute(db) + .await + .expect("seed a backup item"); + } + } + + #[tokio::test] + async fn reencodes_legacy_rows_once_and_records_itself() { + if base_conn().is_none() { + skip("reencodes_legacy_rows_once_and_records_itself"); + return; + } + let s = scratch().await; + seed(&s.db).await; + + let pending = pending_data_migrations(&s.db).await.expect("pending list"); + assert!( + pending.iter().any(|p| p == "004_escape_control_chars"), + "004 must be pending before the run: {pending:?}" + ); + + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run the data code migrations"); + + // Data table: raw U+0001 became U+0001 U+0002 in the key columns and + // inside every jsonb string and object key; the literal-backslash row + // and the plain row are byte-identical. + let rows: Vec<(String, String, serde_json::Value)> = + sqlx::query_as("SELECT pk, sk_s, item_data FROM \"_ddb_t1\" ORDER BY pk") + .fetch_all(&s.db) + .await + .expect("read the data table"); + assert_eq!( + rows, + vec![ + ( + "a\u{1}\u{2}b".to_owned(), + "s\u{1}\u{2}".to_owned(), + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), + ), + ( + "lit".to_owned(), + "s".to_owned(), + json!({"note": {"S": "x\\u0001y"}}), + ), + ( + "plain".to_owned(), + "s".to_owned(), + json!({"pk": {"S": "plain"}}), + ), + ] + ); + + // Index table: pk, sk_s, base_pk, base_sk_s and item_data all re-encoded. + let rows: Vec<(String, String, String, String, serde_json::Value)> = sqlx::query_as( + "SELECT pk, sk_s, base_pk, base_sk_s, item_data FROM \"_ddb_i1\" ORDER BY pk", + ) + .fetch_all(&s.db) + .await + .expect("read the index table"); + assert_eq!( + rows, + vec![ + ( + "g\u{1}\u{2}".to_owned(), + "gs\u{1}\u{2}".to_owned(), + "a\u{1}\u{2}b".to_owned(), + "s\u{1}\u{2}".to_owned(), + json!({"gpk": {"S": "g\u{1}\u{2}"}}), + ), + ( + "zz".to_owned(), + "zs".to_owned(), + "plain".to_owned(), + "s".to_owned(), + json!({"gpk": {"S": "zz"}}), + ), + ] + ); + + // gsi_pending: NULL old_item stays NULL, the raw row is re-encoded in + // both jsonb columns, the plain row is untouched. + let rows: Vec<( + Option, + serde_json::Value, + serde_json::Value, + )> = + sqlx::query_as("SELECT old_item, new_item, index_context FROM gsi_pending ORDER BY id") + .fetch_all(&s.db) + .await + .expect("read gsi_pending"); + assert_eq!( + rows, + vec![ + ( + None, + json!({"pk": {"S": "a\u{1}\u{2}b"}}), + json!({"k\u{1}\u{2}": 1}), + ), + (None, json!({"pk": {"S": "p"}}), json!({"k": 1})), + ] + ); + + // stream_records. + let rows: Vec<(serde_json::Value,)> = + sqlx::query_as("SELECT record_data FROM stream_records ORDER BY sequence_number") + .fetch_all(&s.db) + .await + .expect("read stream_records"); + assert_eq!( + rows, + vec![ + (json!({"Keys": {"pk": {"S": "a\u{1}\u{2}b"}}}),), + (json!({"Keys": {"pk": {"S": "p"}}}),), + ] + ); + + // backup_items, including the NULL sk row. + let rows: Vec<(String, Option, serde_json::Value)> = + sqlx::query_as("SELECT pk, sk, item_data FROM backup_items ORDER BY pk") + .fetch_all(&s.db) + .await + .expect("read backup_items"); + assert_eq!( + rows, + vec![ + ( + "p\u{1}\u{2}".to_owned(), + Some("s\u{1}\u{2}".to_owned()), + json!({"pk": {"S": "p\u{1}\u{2}"}}), + ), + ("plain".to_owned(), None, json!({"pk": {"S": "plain"}}),), + ] + ); + + // Recorded in schema_history, one progress marker per table, and no + // longer pending. + let recorded: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM schema_history \ + WHERE filename = '004_escape_control_chars')", + ) + .fetch_one(&s.db) + .await + .expect("read schema_history"); + assert!(recorded, "schema_history must record the migration"); + let markers: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM data_code_migration_progress \ + WHERE migration_name = '004_escape_control_chars'", + ) + .fetch_one(&s.db) + .await + .expect("count progress markers"); + assert_eq!(markers, 5, "one marker per processed table"); + let pending = pending_data_migrations(&s.db).await.expect("pending list"); + assert!( + !pending.iter().any(|p| p == "004_escape_control_chars"), + "004 must not be pending after the run: {pending:?}" + ); + + // A second run is skipped by the is_migration_applied guard and does + // not double-escape anything. + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run the data code migrations again"); + let (pk, item): (String, serde_json::Value) = + sqlx::query_as("SELECT pk, item_data FROM \"_ddb_t1\" WHERE sk_s = $1") + .bind("s\u{1}\u{2}") + .fetch_one(&s.db) + .await + .expect("re-read the re-encoded row"); + assert_eq!(pk, "a\u{1}\u{2}b"); + assert_eq!( + item, + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}) + ); + + s.cleanup().await; + } + + /// The jsonb candidate predicate must not depend on the session's + /// standard_conforming_strings: with it off, a plain '\u0001' literal is a + /// single 0x01 byte that never appears in jsonb text and matches nothing, + /// so every jsonb row would be skipped while the migration recorded itself. + #[tokio::test] + async fn reencodes_jsonb_rows_with_standard_conforming_strings_off() { + if base_conn().is_none() { + skip("reencodes_jsonb_rows_with_standard_conforming_strings_off"); + return; + } + let s = scratch().await; + seed(&s.db).await; + + let base = base_conn().unwrap(); + let scs_off = PgPoolOptions::new() + .max_connections(2) + .after_connect(|conn, _| { + Box::pin(async move { + sqlx::Executor::execute(&mut *conn, "SET standard_conforming_strings = off") + .await?; + Ok(()) + }) + }) + .connect_with( + format!("{base}/{}", s.db_name) + .parse::() + .unwrap() + .application_name(MIGRATE_APPLICATION_NAME), + ) + .await + .expect("connect with standard_conforming_strings off"); + + run_data_code_migrations(&scs_off, &scs_off) + .await + .expect("run 004"); + + let (pk, sk, item): (String, String, serde_json::Value) = + sqlx::query_as("SELECT pk, sk_s, item_data FROM \"_ddb_t1\" WHERE pk LIKE 'a%'") + .fetch_one(&s.db) + .await + .unwrap(); + assert_eq!(pk, "a\u{1}\u{2}b"); + assert_eq!(sk, "s\u{1}\u{2}"); + assert_eq!( + item, + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), + "jsonb rows must be re-encoded whatever the session setting" + ); + scs_off.close().await; + s.cleanup().await; + } + + /// The server must not serve a data database that has not been through + /// 004: rows it wrote through the escape would be rewritten by the + /// migration later. The required list is empty only once 004 is recorded. + #[tokio::test] + async fn required_migrations_are_reported_until_004_is_recorded() { + if base_conn().is_none() { + skip("required_migrations_are_reported_until_004_is_recorded"); + return; + } + let s = scratch().await; + seed(&s.db).await; + + let missing = unapplied_required_data_migrations(&s.db).await.unwrap(); + assert_eq!(missing, vec!["004_escape_control_chars".to_owned()]); + + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run 004"); + + let missing = unapplied_required_data_migrations(&s.db).await.unwrap(); + assert!(missing.is_empty(), "{missing:?}"); + s.cleanup().await; + } + + /// A server (or any other session) still connected to the data database + /// blocks 004; the migrate command's own connections do not. + #[tokio::test] + async fn refuses_004_while_another_client_is_connected() { + if base_conn().is_none() { + skip("refuses_004_while_another_client_is_connected"); + return; + } + let s = scratch().await; + seed(&s.db).await; + let base = base_conn().unwrap(); + + // An unnamed pool stands in for a running server. + let server_pool = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/{}", s.db_name)) + .await + .expect("connect as a server would"); + sqlx::query("SELECT 1").execute(&server_pool).await.unwrap(); + + let err = refuse_if_other_clients_connected(&s.db, "data") + .await + .expect_err("an unnamed connection must block the migration"); + let text = format!("{err:?}"); + assert!( + text.contains("other connection(s) hold the data database"), + "{text}" + ); + assert!(text.contains(IGNORE_CONNECTIONS_ENV), "{text}"); + let err = run_data_code_migrations(&s.db, &s.db) + .await + .expect_err("004 must not run while the server is connected"); + assert!(format!("{err:?}").contains("other connection(s)")); + assert!( + unapplied_required_data_migrations(&s.db) + .await + .unwrap() + .len() + == 1, + "nothing may be recorded when the guard refuses" + ); + + // Server stopped: only the migrate command's own connections remain. + server_pool.close().await; + after_close(|| refuse_if_other_clients_connected(&s.db, "data")) + .await + .expect("no foreign connection left"); + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run 004"); + s.cleanup().await; + } + + /// `PgPool::close` returns before PostgreSQL removes the closed session + /// from `pg_stat_activity`, so a session check right after a close can + /// still count it. Repeat `check` until it passes, for at most five + /// seconds, and return its last answer. + async fn after_close(check: F) -> Result<(), E> + where + F: Fn() -> Fut, + Fut: std::future::Future>, + { + let mut answer = check().await; + for _ in 0..50 { + if answer.is_ok() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + answer = check().await; + } + answer + } + + /// With the catalog in its own database, a session holding only that + /// database blocks 004 as well: the migration rewrites `backup_items` + /// there. The refusal names the catalog database, and the check is + /// skipped once the migration is recorded. + #[tokio::test] + async fn refuses_004_while_another_client_holds_a_separate_catalog() { + if base_conn().is_none() { + skip("refuses_004_while_another_client_holds_a_separate_catalog"); + return; + } + let data = scratch().await; + let catalog = scratch().await; + seed(&data.db).await; + let base = base_conn().unwrap(); + + // Nothing but the migrate command's own connections on either side. + refuse_if_other_clients_connected_anywhere(&catalog.db, &data.db) + .await + .expect("both databases are free"); + assert!( + needs_exclusive_access(&data.db).await.unwrap(), + "004 is pending, so exclusive access is required" + ); + + // A session on the catalog database alone. + let catalog_client = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/{}", catalog.db_name)) + .await + .expect("connect to the catalog as a server would"); + sqlx::query("SELECT 1") + .execute(&catalog_client) + .await + .unwrap(); + + refuse_if_other_clients_connected(&data.db, "data") + .await + .expect("the data database is still free"); + let err = refuse_if_other_clients_connected_anywhere(&catalog.db, &data.db) + .await + .expect_err("a catalog-only session must block the migration"); + let text = format!("{err:?}"); + assert!( + text.contains("other connection(s) hold the catalog database"), + "{text}" + ); + let err = run_data_code_migrations(&catalog.db, &data.db) + .await + .expect_err("004 must not run while the catalog is held"); + assert!(format!("{err:?}").contains("hold the catalog database")); + assert_eq!( + unapplied_required_data_migrations(&data.db) + .await + .unwrap() + .len(), + 1, + "nothing may be recorded when the guard refuses" + ); + + catalog_client.close().await; + after_close(|| refuse_if_other_clients_connected_anywhere(&catalog.db, &data.db)) + .await + .expect("the catalog session is gone"); + run_data_code_migrations(&catalog.db, &data.db) + .await + .expect("run 004 once the catalog is free"); + assert!( + !needs_exclusive_access(&data.db).await.unwrap(), + "a recorded 004 needs no exclusive access" + ); + + data.cleanup().await; + catalog.cleanup().await; + } + + /// The migrate command runs the guard as the application role, which is + /// not a superuser, and `pg_stat_activity` hides `backend_type` for other + /// roles' sessions from it. A session held by another role (an operator's + /// `psql`, a server under a different role) must still count. + #[tokio::test] + async fn guard_counts_other_roles_sessions_from_a_non_superuser_pool() { + if base_conn().is_none() { + skip("guard_counts_other_roles_sessions_from_a_non_superuser_pool"); + return; + } + let s = scratch().await; + let base = base_conn().unwrap(); + let role = format!( + "eddb_guard_{}", + &uuid::Uuid::new_v4().simple().to_string()[..12] + ); + sqlx::query(&format!( + "CREATE ROLE \"{role}\" LOGIN PASSWORD 'guard-test' NOSUPERUSER" + )) + .execute(&s.admin) + .await + .expect("create a plain login role"); + + // The migrate command's view: the plain role, named as the migration. + let opts = format!("{base}/{}", s.db_name) + .parse::() + .expect("scratch connection string") + .username(&role) + .password("guard-test") + .application_name(MIGRATE_APPLICATION_NAME); + let migrate_pool = PgPoolOptions::new() + .max_connections(1) + .connect_with(opts) + .await + .expect("connect as the plain role"); + + // Only the superuser scratch pool is connected, and it is named as the + // migration too, so nothing counts. + refuse_if_other_clients_connected(&migrate_pool, "data") + .await + .expect("no foreign session yet"); + + // A superuser session with no application name, as an operator's psql + // would be. The plain role sees its datname and usename but not its + // backend_type. + let holder = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/{}", s.db_name)) + .await + .expect("connect as another role would"); + sqlx::query("SELECT 1").execute(&holder).await.unwrap(); + let hidden: Option = sqlx::query_scalar( + "SELECT backend_type FROM pg_stat_activity \ + WHERE datname = current_database() AND usename <> current_user LIMIT 1", + ) + .fetch_one(&migrate_pool) + .await + .expect("read another role's row"); + assert!( + hidden.is_none(), + "this test needs a role that cannot see other sessions' backend_type" + ); + + let err = refuse_if_other_clients_connected(&migrate_pool, "data") + .await + .expect_err("another role's session must count"); + let text = format!("{err:?}"); + assert!(text.contains("hold the data database"), "{text}"); + assert!(text.contains("no client address shown"), "{text}"); + + holder.close().await; + after_close(|| refuse_if_other_clients_connected(&migrate_pool, "data")) + .await + .expect("the other role's session is gone"); + + migrate_pool.close().await; + sqlx::query(&format!("DROP ROLE \"{role}\"")) + .execute(&s.admin) + .await + .expect("drop the test role"); + s.cleanup().await; + } +} diff --git a/crates/storage-postgres/src/snapshot_engine.rs b/crates/storage-postgres/src/snapshot_engine.rs index abb066cf3..35644bbf4 100644 --- a/crates/storage-postgres/src/snapshot_engine.rs +++ b/crates/storage-postgres/src/snapshot_engine.rs @@ -643,14 +643,11 @@ fn cursor_stream( } let mut items = Vec::with_capacity(rows.len()); for (data,) in rows { - match serde_json::from_str::(&data) { + match decode_row(&data) { Ok(item) => items.push(item), Err(e) => { state.abandon(); - return Some(( - Err(StorageError::Internal(format!("Parse item: {e}"))), - state, - )); + return Some((Err(e), state)); } } } @@ -660,6 +657,16 @@ fn cursor_stream( )) } +/// One cursor row, `item_data::text`, as the item it stores. `item_data` holds +/// every string through the escape of U+0000 and U+0001 (`data::item_to_json`), +/// so the row is decoded by `data::json_to_item`, as every other reader of the +/// column decodes it. +fn decode_row(data: &str) -> Result { + let value: serde_json::Value = serde_json::from_str(data) + .map_err(|e| StorageError::Internal(format!("Parse item: {e}")))?; + crate::data::json_to_item(value) +} + /// Two SQLSTATEs mean the server discarded the snapshot's rows before the /// stream drained them: 40001 (`serialization_failure`), which on a /// `REPEATABLE READ READ ONLY` transaction can only come from a hot standby @@ -679,3 +686,27 @@ pub fn map_fetch_error(e: &sqlx::Error) -> StorageError { } db_err(e) } + +#[cfg(test)] +mod tests { + use extenddb_core::types::{AttributeValue, Item}; + + use super::decode_row; + + #[test] + fn a_row_decodes_to_the_item_it_stores() { + let mut map = std::collections::BTreeMap::new(); + map.insert( + "m\u{1}".to_owned(), + AttributeValue::S("\u{1}\u{2}".to_owned()), + ); + let mut item = Item::new(); + item.insert("pk".to_owned(), AttributeValue::S("a\u{0}b".to_owned())); + item.insert("k\u{0}".to_owned(), AttributeValue::M(map)); + let stored = crate::data::item_to_json(&item) + .expect("stored form") + .to_string(); + assert!(!stored.contains("\\u0000"), "{stored}"); + assert_eq!(decode_row(&stored).expect("decode"), item); + } +} diff --git a/crates/storage-postgres/src/stream_engine.rs b/crates/storage-postgres/src/stream_engine.rs index 970a81755..733c7a297 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -165,8 +165,7 @@ impl StreamEngine for PostgresEngine { let shard_id = shard_id.to_string(); let table_name = table_name.to_string(); Box::pin(async move { - let record_json = - serde_json::to_value(&record).map_err(|e| StorageError::Internal(e.to_string()))?; + let record_json = crate::data::to_stored_json(&record)?; let table_id: String = sqlx::query_scalar( "SELECT table_id FROM tables WHERE account_id = $1 AND table_name = $2", @@ -267,9 +266,7 @@ impl StreamEngine for PostgresEngine { let records: Vec = rows .into_iter() .filter_map(|(_, data)| data) - .map(|data| { - serde_json::from_value(data).map_err(|e| StorageError::Internal(e.to_string())) - }) + .map(crate::data::stored_json_to) .collect::, _>>()?; let last_seq = records.last().map(|r| r.dynamodb.sequence_number.clone()); diff --git a/crates/storage-postgres/src/vector_search.rs b/crates/storage-postgres/src/vector_search.rs index 5b278d467..5f4106acf 100644 --- a/crates/storage-postgres/src/vector_search.rs +++ b/crates/storage-postgres/src/vector_search.rs @@ -277,10 +277,17 @@ impl VectorSearchEngine for PostgresEngine { .bind(partition.into_bytes()) .bind(top_k) .bind(query_norm); + // The stored item carries the same escape as every other item_data + // column, so the filter's attribute name and value must be compared + // in stored form. for (name, value) in &filters { - let value_json = serde_json::to_string(value) - .map_err(|e| StorageError::Internal(format!("filter value: {e}")))?; - query = query.bind(name).bind(value_json); + let value_json = serde_json::to_value(value) + .map(extenddb_storage::util::escape_json_strings) + .map_err(|e| StorageError::Internal(format!("filter value: {e}")))? + .to_string(); + query = query + .bind(extenddb_storage::util::escape_control(name).into_owned()) + .bind(value_json); } let rows = query.fetch_all(&self.data_pool).await.map_err(|e| { @@ -298,7 +305,7 @@ impl VectorSearchEngine for PostgresEngine { let mut hits = Vec::with_capacity(rows.len()); for (ordered, embedding, item_json) in rows { - let mut item: extenddb_core::types::Item = serde_json::from_value(item_json) + let mut item: extenddb_core::types::Item = crate::data::json_to_item(item_json) .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; // Reinstated from the stored f32s rather than from a second copy in // the payload, so what comes back is the narrowed value that was diff --git a/crates/storage-postgres/tests/catalog_converge.rs b/crates/storage-postgres/tests/catalog_converge.rs index feb761aef..0c49aafea 100644 --- a/crates/storage-postgres/tests/catalog_converge.rs +++ b/crates/storage-postgres/tests/catalog_converge.rs @@ -8,9 +8,9 @@ //! (`PostgresEngine::prepare_catalog_for_serve`), waiting at most a few //! seconds for the table lock, and keeps the default; `extenddb migrate` //! reports and applies both steps. -//! - A catalog stamped 0.0.4 by a different `003_*` file: `serve` refuses it -//! naming this binary's 003; `extenddb migrate` reports that file as -//! pending and applies it. +//! - A catalog stamped with the current version by a different `003_*` file: +//! `serve` refuses it naming this binary's 003; `extenddb migrate` reports +//! that file as pending and applies it. //! //! Requires `EXTENDDB_TEST_PG_CONNECTION_STRING` (a base URL //! `postgres://user:pass@host:port`, no database); without it every test @@ -108,8 +108,9 @@ impl Drop for DbGuard { impl Scratch { /// A catalog with 001 and 002 applied and recorded, then `third` - /// applied and recorded under `third_name`; and a data database with - /// every data migration applied and recorded. + /// applied and recorded under `third_name`, then 004 applied and + /// recorded (so the stored version is the current one); and a data + /// database with every data migration applied and recorded. async fn new(third_name: &str, third: &str) -> Self { let base = base_conn().expect("caller checks base_conn() first"); let stem = format!("eddb_conv_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); @@ -144,6 +145,10 @@ impl Scratch { include_str!("../migrations/002_vector_indexes.sql"), ), (third_name, third), + ( + "004_control_chars_encoding.sql", + include_str!("../migrations/004_control_chars_encoding.sql"), + ), ] { sqlx::raw_sql(sql).execute(&catalog).await.expect(file); sqlx::query("INSERT INTO schema_history (filename) VALUES ($1)") @@ -191,6 +196,7 @@ impl Scratch { include_str!("../data_migrations/004_vector_index_state.sql"), ), ("003_gsi_base_key_index", ""), + ("004_escape_control_chars", ""), ] { if !sql.is_empty() { sqlx::raw_sql(sql).execute(&data).await.expect(file); @@ -305,7 +311,7 @@ async fn an_earlier_0_0_4_catalog_converges_at_serve_and_describe_table_works() return; } let s = Scratch::new("003_backup_definitions.sql", EARLIER_003).await; - assert_eq!(s.catalog_version().await, "0.0.4"); + assert_eq!(s.catalog_version().await, "0.0.5"); assert_eq!(s.column_default("source_table_arn").await, None); assert!( matches!(s.column_default("restore_date_time").await, Some(Some(_))), @@ -510,7 +516,8 @@ async fn migrate_converges_an_earlier_0_0_4_catalog() { } /// A catalog stamped 0.0.4 by another branch's `003_*` (recorded under its -/// own filename). The version matches, but this binary's 003 is unrecorded: +/// own filename) and then brought to 0.0.5 by 004. The version matches, but +/// this binary's 003 is unrecorded: /// `serve` refuses to start, naming the file and `extenddb migrate --yes`, /// and changes nothing; `migrate` reports it and applies it; afterwards /// nothing is pending, serve starts, and DescribeTable works. @@ -525,7 +532,7 @@ async fn an_unrecorded_catalog_migration_is_pending_even_at_the_current_version( "UPDATE settings SET value = '0.0.4' WHERE key = 'catalog_version';", ) .await; - assert_eq!(s.catalog_version().await, "0.0.4"); + assert_eq!(s.catalog_version().await, "0.0.5"); let b = s.bootstrapper(); assert_eq!( b.read_catalog_version().await.expect("version").as_deref(), diff --git a/crates/storage-postgres/tests/table_snapshot.rs b/crates/storage-postgres/tests/table_snapshot.rs index adfad63b2..ffa54152f 100644 --- a/crates/storage-postgres/tests/table_snapshot.rs +++ b/crates/storage-postgres/tests/table_snapshot.rs @@ -516,6 +516,51 @@ async fn legacy_collation_table_streams_unordered_and_complete(shared: bool) { } on_both_layouts!(legacy_collation_table_streams_unordered_and_complete); +/// An item with U+0000 in an attribute name and U+0001 in a value is stored +/// through the escape (`data::item_to_json`), and the stream yields it as it +/// was written, not in its stored form. +#[tokio::test] +async fn an_item_with_control_characters_streams_as_written() { + use extenddb_core::expression::ExpressionMaps; + use extenddb_core::types::{AttributeValue, Item}; + use extenddb_storage::DataEngine; + use futures::StreamExt; + if base_conn().is_none() { + eprintln!("SKIP an_item_with_control_characters_streams_as_written: no PostgreSQL"); + return; + } + let s = scratch().await; + create_active(&s, plain_input("control")).await; + let item: Item = [ + ("pk".to_owned(), AttributeValue::S("p".to_owned())), + ( + "a\u{0}b".to_owned(), + AttributeValue::S("v\u{1}w".to_owned()), + ), + ] + .into_iter() + .collect(); + let ki = key_info(&s, "control").await; + s.engine + .put_item( + &ki, + item.clone(), + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put"); + let snapshot = s + .engine + .open_table_snapshot(ACCOUNT, "control") + .await + .expect("open"); + let streamed: Vec = snapshot.items.map(|r| r.expect("item")).collect().await; + assert_eq!(streamed, vec![item]); +} + /// The snapshot bound is half the pool, with a separate data database or one /// shared pool: five snapshots holding their data connections on a /// ten-connection pool, the sixth open refused at once with `LimitExceeded`, diff --git a/crates/storage/src/bootstrapper.rs b/crates/storage/src/bootstrapper.rs index 5e3ca8dd2..87279e1c3 100755 --- a/crates/storage/src/bootstrapper.rs +++ b/crates/storage/src/bootstrapper.rs @@ -135,6 +135,17 @@ pub trait Bootstrapper: Send + Sync { /// decide whether confirmation is required — without running anything. async fn pending_data_migrations(&self) -> OpResult>; + /// Refuse when a pending migration needs the databases to itself and + /// another session holds one of them. + /// + /// `migrate` calls this after confirmation and before its first write, so + /// a refusal leaves the deployment exactly as it found it (the catalog + /// version in particular). Defaults to a no-op; a backend whose pending + /// migrations never rewrite rows in place has nothing to check. + async fn check_exclusive_access_for_pending_migrations(&self) -> OpResult<()> { + Ok(()) + } + /// Record the data database connection string in the catalog. async fn record_data_connection(&self) -> OpResult<()>; diff --git a/crates/storage/src/util/control_chars.rs b/crates/storage/src/util/control_chars.rs new file mode 100644 index 000000000..07db91310 --- /dev/null +++ b/crates/storage/src/util/control_chars.rs @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Order-preserving escape for the two characters a storage engine may not be +//! able to hold verbatim. +//! +//! DynamoDB accepts the character U+0000 anywhere a string appears: partition +//! and sort keys, index keys, attribute values, map keys, attribute names. Two +//! of the storage engines cannot store it as is. PostgreSQL `TEXT` rejects the +//! byte (`invalid byte sequence for encoding "UTF8": 0x00`) and `jsonb` rejects +//! the `\u0000` escape. BSON field names are C strings and end at the first NUL. +//! +//! The escape maps each affected character to a two-character sequence that +//! contains no NUL: +//! +//! | input | output | +//! |--------|---------------| +//! | U+0000 | U+0001 U+0001 | +//! | U+0001 | U+0001 U+0002 | +//! +//! Every other character passes through unchanged, so a string without either +//! character encodes to itself and the stored form of ordinary data does not +//! change. The mapping is applied per character and the two output sequences +//! share the prefix U+0001, so three properties hold, each pinned by a test +//! below: +//! +//! - **Round trip.** `unescape(escape(s)) == s` for every `s`. +//! - **Byte order.** `escape(a) < escape(b)` exactly when `a < b` under UTF-8 +//! byte comparison. PostgreSQL compares key columns under `COLLATE "C"`, so +//! Query ordering, `BETWEEN`, and cursor comparisons on escaped keys give the +//! same answers as on the originals. +//! - **Prefix.** `escape(p)` is a prefix of `escape(s)` exactly when `p` is a +//! prefix of `s`, so `begins_with` on escaped values is exact. +//! +//! Decoding is lenient about a U+0001 that is not followed by U+0001 or U+0002: +//! it is returned as a literal U+0001. Rows written before this escape existed +//! can hold such a character, and a lenient decoder reads them unchanged. A +//! legacy string that contained U+0001 immediately followed by U+0001 or U+0002 +//! would decode differently; the operator migration `004_escape_control_chars` +//! re-encodes such rows so that case cannot arise after it has run. + +use std::borrow::Cow; + +const ESC: char = '\u{1}'; +const NUL_TAIL: char = '\u{1}'; +const ESC_TAIL: char = '\u{2}'; + +/// Whether `s` contains a character the escape changes. +#[must_use] +pub fn needs_escape(s: &str) -> bool { + s.bytes().any(|b| b == 0 || b == 1) +} + +/// Escape U+0000 and U+0001 in `s`. Borrows when there is nothing to change. +#[must_use] +pub fn escape_control(s: &str) -> Cow<'_, str> { + if !needs_escape(s) { + return Cow::Borrowed(s); + } + let mut out = String::with_capacity(s.len() + 8); + for ch in s.chars() { + match ch { + '\u{0}' => { + out.push(ESC); + out.push(NUL_TAIL); + } + '\u{1}' => { + out.push(ESC); + out.push(ESC_TAIL); + } + other => out.push(other), + } + } + Cow::Owned(out) +} + +/// Reverse [`escape_control`]. Borrows when there is nothing to change. A +/// U+0001 not followed by U+0001 or U+0002 is kept as a literal U+0001 (see +/// the module documentation for why). +#[must_use] +pub fn unescape_control(s: &str) -> Cow<'_, str> { + if !s.bytes().any(|b| b == 1) { + return Cow::Borrowed(s); + } + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == ESC { + match chars.peek() { + Some(&NUL_TAIL) => { + chars.next(); + out.push('\u{0}'); + } + Some(&ESC_TAIL) => { + chars.next(); + out.push('\u{1}'); + } + _ => out.push('\u{1}'), + } + } else { + out.push(ch); + } + } + Cow::Owned(out) +} + +/// Apply [`escape_control`] to every string in a JSON tree: object keys and +/// string values, at every depth. Used where the whole document lands in a +/// store that rejects U+0000 in any string (PostgreSQL `jsonb`). +#[must_use] +pub fn escape_json_strings(v: serde_json::Value) -> serde_json::Value { + map_json(v, true, &|s| escape_control(s).into_owned()) +} + +/// Reverse [`escape_json_strings`]. +#[must_use] +pub fn unescape_json_strings(v: serde_json::Value) -> serde_json::Value { + map_json(v, true, &|s| unescape_control(s).into_owned()) +} + +/// Apply [`escape_control`] to every object key in a JSON tree, leaving string +/// values alone. Used where only field names are restricted (BSON). +#[must_use] +pub fn escape_json_keys(v: serde_json::Value) -> serde_json::Value { + map_json(v, false, &|s| escape_control(s).into_owned()) +} + +/// Reverse [`escape_json_keys`]. +#[must_use] +pub fn unescape_json_keys(v: serde_json::Value) -> serde_json::Value { + map_json(v, false, &|s| unescape_control(s).into_owned()) +} + +fn map_json( + v: serde_json::Value, + values_too: bool, + f: &dyn Fn(&str) -> String, +) -> serde_json::Value { + use serde_json::Value; + match v { + Value::String(s) if values_too => { + if needs_escape(&s) { + Value::String(f(&s)) + } else { + Value::String(s) + } + } + Value::Array(items) => Value::Array( + items + .into_iter() + .map(|item| map_json(item, values_too, f)) + .collect(), + ), + Value::Object(map) => { + let mut out = serde_json::Map::with_capacity(map.len()); + for (k, val) in map { + let key = if k.bytes().any(|b| b == 0 || b == 1) { + f(&k) + } else { + k + }; + out.insert(key, map_json(val, values_too, f)); + } + Value::Object(out) + } + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// Every string over the alphabet {NUL, U+0001, U+0002, 'a'} up to the + /// given length. Small alphabet, exhaustive: the escape only looks at + /// these three code points and everything else is identity. + fn corpus(max_len: usize) -> Vec { + let alphabet = ['\u{0}', '\u{1}', '\u{2}', 'a']; + let mut out = vec![String::new()]; + let mut frontier = vec![String::new()]; + for _ in 0..max_len { + let mut next = Vec::new(); + for s in &frontier { + for ch in alphabet { + let mut t = s.clone(); + t.push(ch); + next.push(t); + } + } + out.extend(next.iter().cloned()); + frontier = next; + } + out + } + + #[test] + fn plain_strings_are_borrowed_unchanged() { + for s in ["", "a", "hello", "\u{2}\u{3}", "\u{e9}\u{4e2d}", "a\tb\nc"] { + assert!(matches!(escape_control(s), Cow::Borrowed(_)), "{s:?}"); + assert!(matches!(unescape_control(s), Cow::Borrowed(_)), "{s:?}"); + assert_eq!(escape_control(s), s); + assert_eq!(unescape_control(s), s); + } + } + + #[test] + fn table_of_the_two_mappings() { + assert_eq!(escape_control("\u{0}"), "\u{1}\u{1}"); + assert_eq!(escape_control("\u{1}"), "\u{1}\u{2}"); + assert_eq!(escape_control("a\u{0}b"), "a\u{1}\u{1}b"); + assert_eq!(escape_control("\u{0}\u{1}"), "\u{1}\u{1}\u{1}\u{2}"); + assert_eq!(unescape_control("\u{1}\u{1}"), "\u{0}"); + assert_eq!(unescape_control("\u{1}\u{2}"), "\u{1}"); + } + + #[test] + fn escaped_output_never_contains_nul() { + for s in corpus(5) { + assert!(!escape_control(&s).contains('\u{0}'), "{s:?}"); + } + } + + #[test] + fn round_trips_every_string_in_the_corpus() { + for s in corpus(5) { + assert_eq!(unescape_control(&escape_control(&s)), s, "{s:?}"); + } + for s in [ + "caf\u{e9}\u{0}\u{4e2d}", + "\u{0}\u{0}\u{0}", + "\u{1}\u{1}\u{1}", + "x\u{1}\u{0}\u{2}y", + ] { + assert_eq!(unescape_control(&escape_control(s)), s, "{s:?}"); + } + } + + #[test] + fn escape_preserves_utf8_byte_order() { + // The whole point: PostgreSQL compares the escaped column under + // COLLATE "C", and every ordering answer must equal the answer on + // the originals. + let corpus = corpus(4); + for a in &corpus { + for b in &corpus { + let want = a.as_bytes().cmp(b.as_bytes()); + let got = escape_control(a) + .as_bytes() + .cmp(escape_control(b).as_bytes()); + assert_eq!(want, got, "a={a:?} b={b:?}"); + } + } + } + + #[test] + fn escape_preserves_prefixes() { + // begins_with on escaped values must be exact in both directions. + let corpus = corpus(4); + for p in &corpus { + for s in &corpus { + let want = s.as_bytes().starts_with(p.as_bytes()); + let got = escape_control(s) + .as_bytes() + .starts_with(escape_control(p).as_bytes()); + assert_eq!(want, got, "p={p:?} s={s:?}"); + } + } + } + + #[test] + fn escaped_forms_are_distinct_for_distinct_inputs() { + let corpus = corpus(4); + let mut seen = std::collections::HashMap::new(); + for s in &corpus { + let e = escape_control(s).into_owned(); + if let Some(prev) = seen.insert(e.clone(), s.clone()) { + panic!("collision: {prev:?} and {s:?} both escape to {e:?}"); + } + } + } + + #[test] + fn lenient_decode_keeps_a_stray_escape_character_literal() { + // A row written before the escape existed can carry a raw U+0001 + // followed by anything other than U+0001 or U+0002. + assert_eq!(unescape_control("a\u{1}b"), "a\u{1}b"); + assert_eq!(unescape_control("\u{1}"), "\u{1}"); + assert_eq!(unescape_control("\u{1}\u{3}"), "\u{1}\u{3}"); + assert_eq!(unescape_control("x\u{1}"), "x\u{1}"); + } + + #[test] + fn json_strings_variant_touches_keys_and_values_at_every_depth() { + let item = json!({ + "a\u{0}b": {"S": "v\u{0}"}, + "m": {"M": {"k\u{1}": {"S": "\u{0}"}, "plain": {"N": "1"}}}, + "l": {"L": [{"S": "\u{0}x"}, {"SS": ["\u{0}", "y"]}]}, + "b": {"B": "AAEC"} + }); + let escaped = escape_json_strings(item.clone()); + assert!(!escaped.to_string().contains("\\u0000"), "{escaped}"); + assert_eq!(escaped["a\u{1}\u{1}b"]["S"], json!("v\u{1}\u{1}")); + assert_eq!(escaped["m"]["M"]["k\u{1}\u{2}"]["S"], json!("\u{1}\u{1}")); + assert_eq!(escaped["l"]["L"][1]["SS"][0], json!("\u{1}\u{1}")); + assert_eq!(escaped["b"]["B"], json!("AAEC")); + assert_eq!(unescape_json_strings(escaped), item); + } + + #[test] + fn json_keys_variant_leaves_values_alone() { + let item = json!({ + "a\u{0}b": {"S": "v\u{0}"}, + "m": {"M": {"k\u{0}": {"L": [{"S": "\u{0}"}]}}} + }); + let escaped = escape_json_keys(item.clone()); + assert_eq!(escaped["a\u{1}\u{1}b"]["S"], json!("v\u{0}")); + assert_eq!( + escaped["m"]["M"]["k\u{1}\u{1}"]["L"][0]["S"], + json!("\u{0}") + ); + assert_eq!(unescape_json_keys(escaped), item); + } + + #[test] + fn json_without_control_characters_is_unchanged() { + let item = json!({"pk": {"S": "p"}, "n": {"N": "1"}, "m": {"M": {"k": {"S": "v"}}}}); + assert_eq!(escape_json_strings(item.clone()), item); + assert_eq!(escape_json_keys(item.clone()), item); + assert_eq!(unescape_json_strings(item.clone()), item); + assert_eq!(unescape_json_keys(item.clone()), item); + } +} diff --git a/crates/storage/src/util/key.rs b/crates/storage/src/util/key.rs index 8177f6e50..b72d1f202 100755 --- a/crates/storage/src/util/key.rs +++ b/crates/storage/src/util/key.rs @@ -21,9 +21,10 @@ pub enum SortKeyValue { /// /// For single-attribute keys, returns the value directly (no encoding). /// For multi-attribute keys, uses netstring encoding: each part is encoded as -/// `:,` and concatenated. This is provably collision-free -/// regardless of value content, and compatible with `PostgreSQL` TEXT columns -/// (no null bytes). +/// `:,` and concatenated. This is collision-free +/// regardless of value content. The parts are the raw attribute strings; a +/// backend whose columns cannot hold every character (PostgreSQL, see +/// `escape_control`) escapes its key text in its own wrapper. pub fn composite_pk_to_text( item: &Item, key_schema: &[KeySchemaElement], @@ -341,7 +342,7 @@ pub fn recover_sort_key_definitions( /// Encode multiple string parts into a single netstring-encoded composite key. /// /// Format: `:,:,...` — e.g., `"abc"` + `"de"` → `"3:abc,2:de,"`. -/// This encoding is unambiguous for arbitrary byte content and contains no null bytes. +/// This encoding is unambiguous for arbitrary part content; the parts are copied as given. #[must_use] pub fn encode_netstring_composite(parts: &[String]) -> String { let mut out = String::new(); diff --git a/crates/storage/src/util/mod.rs b/crates/storage/src/util/mod.rs index bb79c2103..11414e696 100755 --- a/crates/storage/src/util/mod.rs +++ b/crates/storage/src/util/mod.rs @@ -9,6 +9,7 @@ mod arn; mod backup_id; mod catalog_version; +mod control_chars; mod key; mod shard_stream; @@ -23,6 +24,10 @@ pub use backup_id::{ is_backup_resource_arn, new_backup_id, parse_backup_arn, }; pub use catalog_version::check_stored_catalog_version; +pub use control_chars::{ + escape_control, escape_json_keys, escape_json_strings, needs_escape, unescape_control, + unescape_json_keys, unescape_json_strings, +}; pub use key::SortKeyValue; pub use key::{ composite_pk_to_text, effective_attribute_definitions, encode_netstring_composite, diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index dcfda3a3d..4889ee0d2 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -406,6 +406,25 @@ The PostgreSQL backend uses two categories of tables: attributes, matching the DynamoDB model where key attributes are part of the item. +- **U+0000 in strings**: DynamoDB accepts the character U+0000 anywhere a + string appears (measured 2026-09-18: partition and sort keys, index keys, + values, strings in lists, map keys, attribute names; it sorts as the byte + 0x00 and is a different key from the six-character text `\u0000`). + PostgreSQL `TEXT` rejects the byte and `jsonb` rejects the `\u0000` escape, + so every string that reaches a key column or an `item_data`, `gsi_pending`, + `stream_records`, or `backup_items` document goes through the escape in + `extenddb_storage::util::escape_control`: U+0000 is stored as U+0001 U+0001 + and U+0001 as U+0001 U+0002; every other character is unchanged, so ordinary + data is stored exactly as before. The mapping preserves UTF-8 byte order and + prefixes, so `COLLATE "C"` comparisons, `BETWEEN`, `begins_with`, and + row-comparison cursors on escaped columns return the rows the raw text + would. SQL that addresses an attribute by name inside `item_data` (the TTL + index and sweep, vector search filters) uses the escaped name. The MongoDB + backend applies the same escape to BSON field names only, since BSON string + values are length-prefixed and hold the byte as is. Rows written before the + escape existed are re-encoded once by the operator migration + `004_escape_control_chars` (see the upgrade manual). + - **GSI tables**: GSI tables include base table primary key columns (`base_pk`, `base_sk_*`) as actual SQL columns (not just inside `item_data` JSONB). This is required because: (1) GSI keys are not unique — two base table items can diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 6bd1a1607..11206f673 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -87,7 +87,7 @@ adaptation when switching between ExtendDB and the real service. | Vector index update propagation | Eventually consistent, the same model as a GSI | Matches DynamoDB. Maintenance is queued on the same propagation queue as async GSIs, so a search immediately after a write may not see it. Governed by the same `index_propagation_delay_ms` setting; unlike a GSI there is no per-index override. A value of 0 applies maintenance inline in the write's own transaction, which is stricter than the service and exists so a test can assert steady state without waiting. Inline additionally requires the table's propagation queue to be empty: while rows queued during an index build are still draining, a new write queues behind them instead of overtaking them, so a brief search-after-write window exists even at 0 until the queue drains. That window is ordering, not data loss; the write is applied, in order, by the queue worker. That zero behaves differently while an index is still building, and the two backends differ: **PostgreSQL** applies inline only to an index that is already `ACTIVE`, and defers a write to a building index whatever the delay says, because the write must not reach the index ahead of the backfill's older snapshot of the same item; **SQLite** does not check the status on this path, so with a zero delay a write during a backfill is applied inline and bypasses the hold that keeps the two ordered. The SQLite behaviour is tracked as a defect (F-20), not intended, and it is reachable only with the zero delay, which is a test setting. | | `SearchVectors` score at extreme magnitudes (PostgreSQL backend only) | Returns the true distance as a number for any vector of finite components | The score is bounded to a finite value instead, and the bound is not a measured service answer. pgvector accumulates distances in single precision, so magnitudes far below `f32::MAX` overflow inside the extension: Euclidean above about 9.2e18, dot product above about 1.8e19, and cosine at both ends, above about 1.8e19 and below about 3.7e-23, which is where a component's single-precision square rounds to zero. A non-finite score cannot be serialised as JSON at all, so the result is bounded in SQL: `1e308` for an overflowed distance, `-1e308` for an overflowed negated inner product, which the score contract negates so a client sees `1e308` in `Score`, and 1.0 for a cosine that comes back NaN. Ranking is unaffected at the overflow end, because each bound sits at the end its metric overflows towards, so the farthest row stays farthest and the most similar stays most similar; two rows that both overflow tie, and the tie breaks on the base key. At the underflow end cosine loses resolution rather than being bounded, and which side is tiny decides how much. For a tiny **query** vector, its norm underflows while the inner product usually does not, so the quotient is an infinity that pgvector clamps and the reported distance collapses to one of 0, 1 or 2 following the sign of the inner product, with the 1.0 substitute firing only when the vectors are exactly orthogonal and the quotient is therefore 0/0 (measured). For a tiny **stored** vector it is worse: the stored norm is computed in single precision and reaches zero, so the zero-vector guard fires and that row reports 1.0 at every angle, parallel included. A corpus of tiny embeddings therefore loses ranking altogether rather than losing resolution. For a tiny query vector, by contrast, ranking still separates nearer-than-orthogonal from farther and loses resolution only within each half. The SQLite backend owns its own arithmetic, computes in double precision, and reports the true value, which is why this row is scoped to PostgreSQL. | | Vector index deletion window | `UpdateTable` Delete leaves the index in `DELETING` long enough to observe, then removes it | No observable `DELETING` window on either backend: the catalog row is removed inside the `UpdateTable` transaction, so a `DescribeTable` immediately afterwards already omits the index. The index's data table is dropped after that commit, in a separate transaction, and the two backends handle a failure there differently. **PostgreSQL** treats it as best effort, because the data table lives in a different database entirely: a failure is logged and skipped rather than failing the request. **SQLite** propagates it, so a failed drop returns an error from an `UpdateTable` whose catalog change has already committed, which is the more surprising outcome of the two: the index is gone from the catalog and the caller saw a failure. So an operator debugging a leftover `_ddb_vec_*` table should look for that warning rather than assume the delete was incomplete. | -| Backing up and restoring a table that has vector indexes | Restores the table with its vector indexes intact: the configuration survives, items keep their vector attributes, and `SearchVectors` works as soon as the table is `ACTIVE` (measured) | Not supported. On PostgreSQL and SQLite, the two backends with vector indexes, `CreateBackup` of such a table is refused with `ValidationException` "table has vector index(es); restoring a table with vector indexes is not supported by this storage backend", and no backup is created, because a restore cannot carry the index data across. A backup of a vector table taken before catalog 0.0.4 is refused at restore on PostgreSQL with the same message naming the backup; on SQLite such a backup restores without its vector indexes. A backup of a table with no vector indexes restores normally. | +| Backing up and restoring a table that has vector indexes | Restores the table with its vector indexes intact: the configuration survives, items keep their vector attributes, and `SearchVectors` works as soon as the table is `ACTIVE` (measured) | Not supported. On PostgreSQL and SQLite, the two backends with vector indexes, `CreateBackup` of such a table is refused with `ValidationException` "table has vector index(es); restoring a table with vector indexes is not supported by this storage backend", and no backup is created, because a restore cannot carry the index data across. A backup of a vector table taken before catalog 0.0.4 is refused at restore on PostgreSQL with the same message naming the backup; on SQLite such a backup restores without its vector indexes. A backup of a table with no vector indexes restores normally. | | `SearchVectors` endpoint | Served only on `search-dynamodb..amazonaws.com`. The standard `dynamodb..amazonaws.com` endpoint answers the same request with HTTP 400 `UnknownOperationException` ("This operation is not supported by this endpoint"); every control-plane and item operation stays on the standard endpoint. Signing is unchanged either way (service name `dynamodb`, target prefix `DynamoDB_20120810`) | Served on the same endpoint as every other operation, so a client is pointed at one ExtendDB endpoint for all of them. Two consequences worth knowing: an SDK that resolves a separate search hostname from its endpoint ruleset needs its endpoint overridden to reach ExtendDB, and ExtendDB does **not** reproduce the service's refusal, so a test asserting `UnknownOperationException` for vector search on the base endpoint passes against Amazon DynamoDB and fails here. | | `SearchVectors` result order for equal distances | Measured unstable: three identical searches returned tied rows in three different orders, and a top-k that truncates a tie group keeps an arbitrary subset of it | Deterministic on both backends, by different means. **PostgreSQL** sorts explicitly on the base table's full primary key after the score, so the order is a property of the query. **SQLite** issues no `ORDER BY` and resolves ties by scan order through a stable top-k, so its order is a property of the plan rather than something the query guarantees. Either way a client re-issuing an identical search sees the same order, which is stricter than the service rather than divergent in outcome. Do not rely on the two backends agreeing on which subset of a truncated tie group they keep. | | Vector indexes on the MongoDB backend | Vector indexes and `SearchVectors` are available | Not supported at all. That backend provides no vector search implementation, so the engine's capability gate refuses `CreateTable` and `UpdateTable` carrying `VectorIndexes` and every `SearchVectors` request, with the same capability message a PostgreSQL deployment without pgvector returns. Every other vector row in this document describes the PostgreSQL and SQLite backends. | @@ -102,7 +102,7 @@ Behaviour stated as measured, and every number below, was observed with release | Area | DynamoDB | ExtendDB | |------|----------|------| -| What a restore carries across | Key schema, attribute definitions, items, secondary indexes, billing mode and provisioned throughput, on-demand throughput (table and GSI level), SSE settings. Table class is not carried: a restore is `STANDARD` whatever the source's class (measured). Stream settings, TTL, tags, auto scaling, IAM policies, and CloudWatch settings must be reapplied by hand | The same set on all four backends, with one gap: the table's on-demand throughput is carried, a GSI's is not (ExtendDB records no per-index on-demand maximum, and `OnDemandThroughput` is not a member of its GSI definition). Table class is not restored: a `STANDARD_INFREQUENT_ACCESS` source restores as `STANDARD`, as on the service. Streams, TTL, tags, and deletion protection are not restored. A backup written before catalog 0.0.4 (PostgreSQL, SQLite, Cassandra) has no recorded table definition and restores with its keys, items, and billing mode but no secondary indexes. A provisioned one restores with 5/5 throughput on PostgreSQL and SQLite and with its recorded throughput on Cassandra | +| What a restore carries across | Key schema, attribute definitions, items, secondary indexes, billing mode and provisioned throughput, on-demand throughput (table and GSI level), SSE settings. Table class is not carried: a restore is `STANDARD` whatever the source's class (measured). Stream settings, TTL, tags, auto scaling, IAM policies, and CloudWatch settings must be reapplied by hand | The same set on all four backends, with one gap: the table's on-demand throughput is carried, a GSI's is not (ExtendDB records no per-index on-demand maximum, and `OnDemandThroughput` is not a member of its GSI definition). Table class is not restored: a `STANDARD_INFREQUENT_ACCESS` source restores as `STANDARD`, as on the service. Streams, TTL, tags, and deletion protection are not restored. A backup written before catalog 0.0.4 (PostgreSQL, SQLite, Cassandra) has no recorded table definition and restores with its keys, items, and billing mode but no secondary indexes. A provisioned one restores with 5/5 throughput on PostgreSQL and SQLite and with its recorded throughput on Cassandra | | How `RestoreTableFromBackup` runs | Returns at once with the target `CREATING`; the service copies in the background | The same on all four backends: the response carries the target `CREATING`, and the items are copied by a background task in the server, so a client that times out or disconnects does not stop it. Once the request has been authenticated and authorized, the rest of it, from reading the backup to registering the restore, runs in a task of its own, so a client that disconnects after that does not cancel it either: the restore runs and the client finds the target with `DescribeTable`. A client that disconnects while the request is still being authenticated or authorized cancels it, and nothing is created *(from the code)*. Measured with a client whose 1 ms read timeout closed its connection before any response arrived: on all four backends the restore was registered and finished. Measured with a 60,000-item backup of a table with no secondary indexes: response in 0.032 s (PostgreSQL), 0.012 s (SQLite), 0.053 s (MongoDB), 0.151 s (Cassandra); `ACTIVE` after 1.5 s, 2.1 s, 3.6 s, and 11.2 s. On Cassandra the response waits for the target table's schema to be created: 0.75 to 1.3 s with five restores running at once *(earlier build)*, which is longer than a client read timeout of 1 s. A restore runs inside the server process; if the process stops, see the abandoned-restore row | | `RestoreSummary` | The restore response and `DescribeTable` while `CREATING` report `SourceBackupArn`, `SourceTableArn`, `RestoreDateTime` (the backup's `BackupCreationDateTime`, not the time the restore ran), and `RestoreInProgress=true`. Once the table is `ACTIVE`, `DescribeTable` omits `RestoreSummary` | The same on all four backends. No response that describes a table (`CreateTable`, `UpdateTable`, `DeleteTable`, `DescribeTable`, `RestoreTableFromBackup`) carries `RestoreSummary` unless the table is `CREATING`; what the service's `UpdateTable` returns for a restored table was not measured | | Reads on a restore target | A `GetItem` or `Scan` on the target while `CREATING` is `ResourceNotFoundException`; the first read after `DescribeTable` reports `ACTIVE` succeeds (measured) | The same on all four backends. The server's key-info cache stores a negative entry (5 s TTL by default) for a name the catalog does not have, and does not store one for a name the catalog has in a state other than `ACTIVE`: on a not-found answer it asks the catalog once more with `DescribeTable`, and authorization records the name as missing in the key-info snapshot it hands the engine, so the engine does not look it up again. A `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, or `Scan` on the target while it is `CREATING` therefore costs exactly one `table_key_info` and one `describe_table` catalog load, uncached, per request (on SQLite five SQL statements: one for the key info, four for `DescribeTable`; on PostgreSQL `describe_table` is two queries), plus one `describe_table` on the first such request for the throttle registry; the first read after `ACTIVE` loads once more and is then cached. Measured on SQLite with a `GetItem` loop on a `CREATING` restore target of 100,000 items: 40 requests refused, 40 key-info and 41 `DescribeTable` loads in the server's statement log; with the hand-off to the engine removed, 80 and 81. In an earlier run of the fidelity test the first `GetItem` after `ACTIVE` answered in 3 ms after 72 refused reads. | @@ -117,7 +117,7 @@ Behaviour stated as measured, and every number below, was observed with release | Multi-part base table keys (preview) | Not supported | A backup of a table created with `enable_multipart_keys` is refused at restore with `ValidationException`; the item paths address such tables by their first HASH and RANGE attribute only *(from the code and storage-level tests; not checked on a running server)* | | `DeleteBackup` and `DeleteTable` during a restore | `DeleteTable` on the `CREATING` target is `ResourceInUseException`. `DeleteBackup` during a restore was not measured | While the target is `CREATING`, `DeleteTable` on it is `ResourceInUseException` on all four backends, as on the service. `DeleteBackup` on its source backup is `BackupInUseException` on all four: that refusal is ExtendDB's contract, not measured against the service. Both succeed once the target is `ACTIVE`. How the restore and `DeleteBackup` are ordered differs *(from the code)*. PostgreSQL and SQLite register the restore in the transaction that creates the target, holding the backup row, so a concurrent `DeleteBackup` is ordered strictly before (the restore then finds no backup) or after (it finds the restore). MongoDB has no cross-collection transaction: a restore claims the backup document, inserts the target's catalog document, and releases the claim; `DeleteBackup` claims the backup the same way. Cassandra uses two lightweight transactions on different partitions: the target's row is inserted first (`IF NOT EXISTS`, which reserves the name), then the restore is registered on the backup's row (`IF backup_status = 'AVAILABLE'`), which `DeleteBackup` claims on the same partition; a concurrent `DescribeTable` can therefore see a `CREATING` target for a restore that then fails with `BackupNotFoundException`, after which the target is removed. On MongoDB, if `DeleteBackup` returns an internal error or its request is cancelled after the backup's data drop started, the backup stays `AVAILABLE` and in use (`DeleteBackup` and `RestoreTableFromBackup` return `BackupInUseException`) until the heartbeat sweep finishes the delete, about 45 to 80 s later; it is not left restorable without its data. A `DeleteBackup` that stopped while a restore from the same backup is `CREATING` is finished by the sweep after that restore becomes `ACTIVE`. So a `DeleteBackup` that returned an error can still take effect later: besides the case above, one that failed after claiming the backup (for example because it found a restore from it `CREATING`) and whose claim could not then be released, neither in the request nor by the claim guard's release on drop, is finished by the sweep (once no restore from the backup is `CREATING`), although the client was told it failed (not reproduced) *(all from the code and storage-level tests)*. MongoDB reads the catalog from the primary with read concern `local` regardless of the connection string, which the claims rely on; the connection string must use `readPreference=primary` (any other read preference is refused at startup). The write concern follows the connection string and must be `majority` (the server default): a connection string with `w=1` is refused at startup, because a claim acknowledged under `w=1` just before a primary failover can be rolled back | | Concurrent restores of one backup | A second `RestoreTableFromBackup` of a backup while a restore from it is still `CREATING` is `BackupInUseException` (measured) | The same on all four backends: the second restore is refused with `BackupInUseException` and creates nothing; the check runs inside the transaction that registers the restore (PostgreSQL, with the backup row locked `FOR UPDATE`; SQLite), inside the claim on the backup document followed by a check for a `CREATING` target of the backup (MongoDB), or inside the lightweight transaction on the backup row (Cassandra), so two simultaneous requests cannot both pass. Once the first target is `ACTIVE` the backup restores again. A restore of a backup whose `DeleteBackup` is in progress answers differently by backend (the service's answer was not measured): `BackupInUseException` "Backup is being deleted" on MongoDB, where the backup stays `AVAILABLE` under a delete claim until its data is dropped; `BackupNotFoundException` on Cassandra, where the delete marks it `DELETING` first; and on PostgreSQL and SQLite the restore waits for the delete's transaction and then finds no backup (`BackupNotFoundException`). Earlier builds accepted concurrent restores of one backup on PostgreSQL, SQLite, and Cassandra, and on MongoDB after a 2 s retry | -| Restore interrupted by the server stopping | Managed by the service | The copy runs in the server process, so a stopped process leaves its target `CREATING`. Each backend removes such a target without operator action, logs the removal with the table name (at warn; at info on Cassandra), and then lets `DeleteBackup` and a new restore into the name succeed. Measured after `SIGKILL` mid-copy and an immediate restart *(earlier build)*: **PostgreSQL** removes it on a control-plane pass once the target is older than 60 s and its restore lock is free (removed 60 s after the kill). **SQLite** removes it when the next server starts (0.1 s after the restart). **MongoDB** and **Cassandra** remove it once its owner's heartbeat is more than 60 s old, by a sweep that runs at startup and every 15 s, so about 45 to 80 s after the owner stopped (the heartbeat's last refresh can be up to one 15 s interval before the stop; measured: 60 s on MongoDB, 62 s on Cassandra). Until then `DeleteTable` and `DeleteBackup` are refused as during a running restore. Not covered *(from the code)*: on MongoDB, a target whose base copy had finished is not swept but is finished by the index backfill worker after a restart; if that backfill fails on every attempt, the worker retries it every 5 s with a warning and never gives up, so the target stays `CREATING` (and `DeleteTable` and `DeleteBackup` stay refused) until the cause is fixed or the target's catalog document is removed by hand (no failing case was found to reproduce this). On Cassandra, a target left `CREATING` by a build before catalog 0.0.4 carries no heartbeat and is not swept. The MongoDB and Cassandra heartbeats compare wall clocks across servers (MongoDB uses the database server's clock for refreshes), so a server whose clock is far behind can have a live restore swept | +| Restore interrupted by the server stopping | Managed by the service | The copy runs in the server process, so a stopped process leaves its target `CREATING`. Each backend removes such a target without operator action, logs the removal with the table name (at warn; at info on Cassandra), and then lets `DeleteBackup` and a new restore into the name succeed. Measured after `SIGKILL` mid-copy and an immediate restart *(earlier build)*: **PostgreSQL** removes it on a control-plane pass once the target is older than 60 s and its restore lock is free (removed 60 s after the kill). **SQLite** removes it when the next server starts (0.1 s after the restart). **MongoDB** and **Cassandra** remove it once its owner's heartbeat is more than 60 s old, by a sweep that runs at startup and every 15 s, so about 45 to 80 s after the owner stopped (the heartbeat's last refresh can be up to one 15 s interval before the stop; measured: 60 s on MongoDB, 62 s on Cassandra). Until then `DeleteTable` and `DeleteBackup` are refused as during a running restore. Not covered *(from the code)*: on MongoDB, a target whose base copy had finished is not swept but is finished by the index backfill worker after a restart; if that backfill fails on every attempt, the worker retries it every 5 s with a warning and never gives up, so the target stays `CREATING` (and `DeleteTable` and `DeleteBackup` stay refused) until the cause is fixed or the target's catalog document is removed by hand (no failing case was found to reproduce this). On Cassandra, a target left `CREATING` by a build before catalog 0.0.4 carries no heartbeat and is not swept. The MongoDB and Cassandra heartbeats compare wall clocks across servers (MongoDB uses the database server's clock for refreshes), so a server whose clock is far behind can have a live restore swept | | Point-in-time recovery | 35-day window | Not supported. `RestoreTableToPointInTime` is refused with `ValidationException` ("Point-in-time recovery restore is not yet supported"). `UpdateContinuousBackups` is not refused: enabling point-in-time recovery succeeds, and `DescribeContinuousBackups` then reports it `ENABLED` with an `EarliestRestorableDateTime` 35 days back, although nothing is recorded and no restore to any of those times is possible. Same on all four backends | | Where backups live | Managed storage, independent of the table | Inside the database the server already uses, so a lost database loses its backups too: on PostgreSQL in the catalog database (`backups`, `backup_items`, `backup_definitions`, `table_restores`), on SQLite in the one database file, on MongoDB as a `backups` metadata collection in the catalog database and one data collection per backup in the data database, on Cassandra as backup metadata in the catalog keyspace and item payloads in the account's keyspace. Take database-level backups for off-host copies until the backup store program ships | | Backup creation | `CreateBackup` returns while the backup is `CREATING`; `ListBackups` and `DescribeBackup` expose that state until it becomes `AVAILABLE`. `BackupName` and `TableName` are checked as the model says: length 3 to 255 and `[a-zA-Z0-9_.-]+`, with "1 validation error detected: Value '' at 'backupName' failed to satisfy constraint: " texts, joined under "2 validation errors detected:" when both fail (measured). `TableName` may be the table's ARN (measured). A table that does not exist or is still `CREATING` is `TableNotFoundException` "Table not found: " (measured) | `CreateBackup` copies the items before it returns and returns the backup `AVAILABLE` on all four backends. On PostgreSQL, MongoDB, and Cassandra a concurrent `ListBackups` never saw it `CREATING` *(earlier build)*; on SQLite the backup row is visible as `CREATING` to other requests while the copy runs. Measured *(earlier build)*: 1.3 s for 60,000 items on PostgreSQL, 1.9 s for 60,000 on SQLite, 0.2 s for 20,000 on MongoDB, 5.1 s for 20,000 on Cassandra. MongoDB reports `BackupSizeBytes` 0. The name checks are the service's, with its texts (the length clause before the pattern clause when both fail; the service's order was not captured), counting characters, with `TableName` taking the deployment's table-name limits; before them a 200 KB name was stored and returned in every `ListBackups` page (a 500 on Cassandra) and a NUL byte was a 500 on PostgreSQL. `TableName` as an ARN (`arn:aws:dynamodb:::table/`) is accepted on all four backends: another region's resolves, another account's is `AccessDeniedException` (neither measured on the service); an SDK built from the model refuses the ARN form client-side, so only a hand-built request sends it. `TableNotFoundException` "Table not found: " for a missing or `CREATING` table on all four backends, built from the request's name (the backends' own payloads differ) | diff --git a/docs/getting-started.md b/docs/getting-started.md index 8632ad33d..fc513aea1 100755 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -268,7 +268,7 @@ You should see all checks pass: --- Checking catalog connection... OK: Connected to catalog. --- Checking catalog version... - OK: Catalog version 0.0.4 + OK: Catalog version 0.0.5 --- Checking data database... OK: Connected to data database 'extenddb_catalog_data'. --- Enumerating tables... @@ -284,7 +284,7 @@ extenddb runs as a daemon (background process) and logs to syslog. On startup it ```bash ./target/release/extenddb serve --config extenddb.toml -# extenddb 0.1.14 (catalog 0.0.4) starting on 127.0.0.1:18443 +# extenddb 0.1.14 (catalog 0.0.5) starting on 127.0.0.1:18443 # storage: postgres (postgresql://extenddb:***@localhost:5432/extenddb_catalog) ``` @@ -1363,7 +1363,7 @@ Each runner requires its tools to be installed. The runner checks prerequisites ```bash ./target/release/extenddb version # extenddb 0.1.14 -# catalog 0.0.4 (postgres) +# catalog 0.0.5 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z ``` diff --git a/docs/manuals/01-architecture-guide.md b/docs/manuals/01-architecture-guide.md index bd05b6552..58ffdfc04 100755 --- a/docs/manuals/01-architecture-guide.md +++ b/docs/manuals/01-architecture-guide.md @@ -205,7 +205,7 @@ extenddb uses a dual-database architecture: - **Catalog database** (e.g., `extenddb_catalog`): Stores table metadata, account/user/group/role/policy definitions, access keys, settings, stream metadata, and metrics. Shared across all accounts. - **Data database** (e.g., `extenddb_catalog_data`): Stores user items, GSI/LSI data, and stream records. Each table gets its own PostgreSQL table. -The catalog version is 0.0.4 on PostgreSQL, SQLite, and Cassandra. PostgreSQL and SQLite store it in the `settings` table under the key `catalog_version` and check it at startup; Cassandra has no startup check (see the Upgrade Manual). +The catalog version is 0.0.5 on PostgreSQL and 0.0.4 on SQLite and Cassandra. PostgreSQL and SQLite store it in the `settings` table under the key `catalog_version` and check it at startup; Cassandra has no startup check (see the Upgrade Manual). The MongoDB backend tracks its own catalog version, 0.0.2. A mismatch between the compiled-in version and the stored one prevents a PostgreSQL or SQLite server from starting; run `extenddb migrate` to upgrade. diff --git a/docs/manuals/04-quickstart-setup-guide.md b/docs/manuals/04-quickstart-setup-guide.md index 0f57420d8..2bed0dc6a 100755 --- a/docs/manuals/04-quickstart-setup-guide.md +++ b/docs/manuals/04-quickstart-setup-guide.md @@ -130,7 +130,7 @@ Check the version: ```bash ./target/release/extenddb version # extenddb 0.1.14 -# catalog 0.0.4 (postgres) +# catalog 0.0.5 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z ``` @@ -171,7 +171,7 @@ Expected output: --- Checking catalog connection... OK: Connected to catalog. --- Checking catalog version... - OK: Catalog version 0.0.4 + OK: Catalog version 0.0.5 --- Checking data database... OK: Connected to data database 'extenddb_catalog_data'. --- Enumerating tables... diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index a0cf56e7e..ca61b1a9a 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -927,7 +927,7 @@ Check that PostgreSQL is running and the connection string in `extenddb.toml` is ``` -Error: catalog version mismatch: found 1.0.0, expected 0.0.4 +Error: catalog version mismatch: found 1.0.0, expected 0.0.5 ``` Run `extenddb migrate --config extenddb.toml` to upgrade the catalog schema. The check is exact equality in both directions, so this also appears when a binary meets a catalog a newer build already migrated; in that case upgrade the binary rather than the catalog. `extenddb migrate` refuses a catalog newer than the binary (`catalog version X is newer than this binary's Y`) instead of stamping the older version onto it. See the Upgrade Manual for the version history and the stop / migrate / start sequence. diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index f4451a0f5..4cb7ffd12 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -4,9 +4,9 @@ ## Current Status -Catalog 0.0.4 is current. **Every existing PostgreSQL, SQLite, and Cassandra deployment must run `extenddb migrate`** to reach it. PostgreSQL and SQLite servers refuse to start against a catalog version they were not built for; a Cassandra server starts anyway and serves tables and items, but CreateBackup, RestoreTableFromBackup, and DeleteBackup are refused with a `ValidationException` naming `extenddb migrate --yes` until the catalog is migrated (see [Cassandra](#cassandra)). MongoDB's catalog version does not change in this release. +Catalog 0.0.5 is current on PostgreSQL; catalog 0.0.4 is current on SQLite and Cassandra. **Every existing PostgreSQL, SQLite, and Cassandra deployment must run `extenddb migrate`** to reach it. PostgreSQL and SQLite servers refuse to start against a catalog version they were not built for; a Cassandra server starts anyway and serves tables and items, but CreateBackup, RestoreTableFromBackup, and DeleteBackup are refused with a `ValidationException` naming `extenddb migrate --yes` until the catalog is migrated (see [Cassandra](#cassandra)). MongoDB's catalog version does not change in this release. -See [Catalog 0.0.4](#catalog-004-current) below for what changes and the exact sequence. +On PostgreSQL the 0.0.5 upgrade changes no schema; it accompanies the data migration `004_escape_control_chars`, which changes how strings are stored, and it has an ordering requirement the earlier upgrades did not have: every server must be stopped before `extenddb migrate --yes` runs. See [Catalog 0.0.5](#catalog-005-current) and [004_escape_control_chars](#004_escape_control_chars) below for what changes and the exact sequence, and [Catalog 0.0.4](#catalog-004) for the backup definition tables. ## How Catalog Upgrades Work @@ -15,9 +15,10 @@ See [Catalog 0.0.4](#catalog-004-current) below for what changes and the exact s Migrations are SQL files in `crates/storage-postgres/migrations/`, applied in filename order: ``` -001_schema.sql ← the complete initial schema -002_vector_indexes.sql ← vector index metadata, catalog 0.0.3 -003_backup_definitions.sql ← backup table definitions, catalog 0.0.4 +001_schema.sql ← the complete initial schema +002_vector_indexes.sql ← vector index metadata, catalog 0.0.3 +003_backup_definitions.sql ← backup table definitions, catalog 0.0.4 +004_control_chars_encoding.sql ← stored string encoding marker, catalog 0.0.5 ``` The `schema_history` table tracks which files have been applied. When `extenddb migrate` runs, it: @@ -202,7 +203,25 @@ To discard data written after the upgrade as well, restore `` from its ## Version History -### Catalog 0.0.4 (Current) +### Catalog 0.0.5 (Current) + +PostgreSQL only; SQLite, Cassandra, and MongoDB keep their versions. Changes no schema. The version moves because the stored form of strings changed: from this release, every string in the data database and in the catalog's `backup_items` is written through an order-preserving escape (U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002), so that U+0000, which DynamoDB accepts anywhere in a string, can be stored. The data migration [004_escape_control_chars](#004_escape_control_chars) re-encodes rows written before the escape existed. + +A binary from an earlier release reads escaped rows as literal data and reports nothing wrong. The catalog version check at startup is the one check such a binary performs, so moving the version is what makes it refuse a migrated deployment. The two checks together close both directions: a 0.0.4 binary refuses a 0.0.5 catalog, and a 0.0.5 binary refuses a data database that does not record `004_escape_control_chars`. + +Upgrade sequence (the order matters; see the data migration section for why): + +```bash +extenddb stop --config extenddb.toml # every server that uses this data database +extenddb migrate --yes --config extenddb.toml +extenddb serve --config extenddb.toml +``` + +Run `extenddb migrate` without `--yes` first to see what is pending; it reports `catalog 0.0.4 -> 0.0.5` and `data migrations [004_escape_control_chars]` and changes nothing. With `--yes`, the command first checks that no other session holds the catalog or the data database and refuses before writing anything if one does, so the catalog version stays at 0.0.4 and the stopped servers can be restarted on the old binary while the operator sorts it out. + +Rolling back after the upgrade means restoring both databases from the backups taken before it. A 0.0.4 binary refuses the migrated catalog; pointing it at a migrated data database with a restored 0.0.4 catalog would serve escaped strings as data. + +### Catalog 0.0.4 Adds the table definition a backup records and the registration of a running restore: @@ -313,6 +332,71 @@ The first release, so all 0.0.2 deployments were fresh installs. --- +## Data Migrations + +Some changes rewrite rows in the data database rather than the catalog schema. These are +implemented in Rust (`DATA_CODE_MIGRATIONS` in `crates/storage-postgres/src/migrations.rs`), +tracked in the data database's own `schema_history` table, and applied once by +`extenddb migrate --yes`. Running `extenddb migrate` without `--yes` lists them as pending +and changes nothing. + +### 004_escape_control_chars + +Strings are stored through an order-preserving escape so that U+0000, which DynamoDB +accepts anywhere a string appears, can be held in PostgreSQL `TEXT` and `jsonb` columns: +U+0000 is stored as U+0001 U+0001, and U+0001 as U+0001 U+0002. Rows written before the +escape existed hold their strings raw, and a raw U+0001 in such a row could be misread by +the decoder. This migration re-encodes those rows. + +What it rewrites: every data table and index table (the text key columns and the +`item_data` document), vector index tables, `gsi_pending`, `stream_records`, and +`backup_items`. Only rows that contain U+0001 are touched; a database with none is left as +it is, apart from the `schema_history` row. + +The migration scans every data and index table once (each row's `jsonb` document is +rendered to text to find candidates), so on a large deployment it takes time proportional +to the size of the data. It processes one table per transaction and keeps a per-table +progress marker in `data_code_migration_progress`, so an interrupted run resumes with the +tables that are not yet done and never rewrites a table twice. + +Order of operations. A server built with the escape refuses to start on a data database +that does not record this migration, with a message naming it, because rows the new build +writes are indistinguishable from legacy rows to the migration (both can contain U+0001) and +would be rewritten by it. Upgrade a PostgreSQL deployment in this order: + +1. Stop every ExtendDB server that uses the data database. A server from an earlier release + still writing during the migration would leave unescaped rows behind. +2. Run `extenddb migrate --yes` with the new binary. +3. Start the new servers. + +A fresh `extenddb init` records the migration, so new deployments start without this step. +A rolling deployment that mixes the two releases against one data database is not +supported for this release: the new server will not start until the migration has run, +and the old server must be stopped before it runs. + +`extenddb migrate --yes` refuses to run this migration while any other session is connected +to the data database or, when the catalog is a separate database, to the catalog database +(`backup_items` lives there), and lists them, because a server still writing during the +rewrite would leave rows in the wrong encoding. The check runs before the command writes +anything, so a refusal leaves the catalog version at 0.0.4. If the only other connections +are idle ones held by a connection pooler, set `EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1` to +skip that check. + +A server from an earlier release refuses to start against a migrated deployment because +the migration moves the catalog version to 0.0.5 (see [Catalog 0.0.5](#catalog-005-current)). +Do not downgrade past this release without restoring both databases from backups taken +before the migration: a 0.0.4 binary given a restored 0.0.4 catalog and a migrated data +database would read escaped rows as literal data. + +MongoDB. The MongoDB backend applies the same escape to BSON field names (attribute +names and map keys) and has no migration and no startup check. Field names written by +an earlier release are stored raw. A name containing a lone U+0001 reads back unchanged, +as do all string values and all key strings; a name containing U+0001 immediately +followed by U+0001 or U+0002 reads back with that pair decoded as U+0000 or U+0001. +Deployments whose attribute names never contain U+0001 are unaffected. + +--- + ## Behavior Changes by Release Catalog upgrades change the schema; behavior changes alter how the running server diff --git a/docs/manuals/08-install-linux.md b/docs/manuals/08-install-linux.md index 7414ab006..cff9a63cd 100755 --- a/docs/manuals/08-install-linux.md +++ b/docs/manuals/08-install-linux.md @@ -118,7 +118,7 @@ Expected: ``` === extenddb verify === ... - OK: Catalog version 0.0.4 + OK: Catalog version 0.0.5 ... === HEALTHY: All checks passed === ``` diff --git a/docs/manuals/09-install-macos.md b/docs/manuals/09-install-macos.md index feec0a409..aae4b95c9 100755 --- a/docs/manuals/09-install-macos.md +++ b/docs/manuals/09-install-macos.md @@ -96,7 +96,7 @@ Expected: ``` === extenddb verify === ... - OK: Catalog version 0.0.4 + OK: Catalog version 0.0.5 ... === HEALTHY: All checks passed === ``` diff --git a/tests/test_cli_vector_catalog_migration.py b/tests/test_cli_vector_catalog_migration.py index e50f9f175..452d30776 100644 --- a/tests/test_cli_vector_catalog_migration.py +++ b/tests/test_cli_vector_catalog_migration.py @@ -3,8 +3,9 @@ """Catalog migration tests against a live PostgreSQL deployment. -The vector index schema (catalog 0.0.3) and the backup table definitions -(catalog 0.0.4) are exercised through an upgrade from the pre-vector shape. +The vector index schema (catalog 0.0.3), the backup table definitions +(catalog 0.0.4) and the stored string encoding marker (catalog 0.0.5) are +exercised through an upgrade from the pre-vector shape. These exercise the migration against a live deployment rather than asserting the SQL text: init one, roll its catalog back to the pre-vector shape, and check that @@ -33,13 +34,16 @@ VECTOR_MIGRATION = "002_vector_indexes.sql" BACKUP_DEFINITIONS_MIGRATION = "003_backup_definitions.sql" +# Moves the version for the stored string encoding; changes no schema. A 0.0.2 +# deployment has none of these three recorded. +ENCODING_MIGRATION = "004_control_chars_encoding.sql" # The version the binary expects, written by the last catalog migration. Every # current-version assertion reads it from here so the next bump is one edit. -CURRENT_CATALOG_VERSION = "0.0.4" +CURRENT_CATALOG_VERSION = "0.0.5" # A version no release has reached, for the symmetric version-gate test. -FUTURE_CATALOG_VERSION = "0.0.5" +FUTURE_CATALOG_VERSION = "0.0.6" def _catalog_conn(cli_env): @@ -108,8 +112,8 @@ def _roll_catalog_back_to_pre_vector(cli_env): cur.execute("DROP TABLE IF EXISTS vector_indexes") cur.execute("ALTER TABLE backups DROP COLUMN IF EXISTS vector_indexes") cur.execute( - "DELETE FROM schema_history WHERE filename IN (%s, %s)", - (VECTOR_MIGRATION, BACKUP_DEFINITIONS_MIGRATION), + "DELETE FROM schema_history WHERE filename IN (%s, %s, %s)", + (VECTOR_MIGRATION, BACKUP_DEFINITIONS_MIGRATION, ENCODING_MIGRATION), ) cur.execute("UPDATE settings SET value = '0.0.2' WHERE key = 'catalog_version'") finally: @@ -145,6 +149,7 @@ def test_init_creates_the_catalog_at_the_current_version(self, cli_env): # so a replay after a crash between applying and recording is harmless. assert VECTOR_MIGRATION in tracked, tracked assert BACKUP_DEFINITIONS_MIGRATION in tracked, tracked + assert ENCODING_MIGRATION in tracked, tracked def test_migrate_upgrades_a_pre_vector_deployment(self, cli_env): """A 0.0.2 deployment is refused, upgraded by migrate, and then serves.""" diff --git a/tests/test_nul_strings.py b/tests/test_nul_strings.py new file mode 100644 index 000000000..0e1d8c511 --- /dev/null +++ b/tests/test_nul_strings.py @@ -0,0 +1,378 @@ +# SPDX-License-Identifier: Apache-2.0 +"""U+0000 and U+0001 inside strings: keys, index keys, values, and names. + +DynamoDB places no character restriction on strings. Measured 2026-09-18 +against the service on a scratch table: PutItem accepts the NUL character +inside a partition key, a sort key, a GSI key, a non-key value, a string in a +list, a map key, and a top-level attribute name, and GetItem returns every one +byte-identical. NUL sorts as the byte 0x00, before every other character; it is +a different character from the six-character text ``\\u0000``; range and prefix +conditions treat it as an ordinary byte; the GSI holds the item; DeleteItem on +the key removes it. These tests pin exactly that, so every backend has to store +the character rather than its escape text and has to keep it out of the way of +its own storage encoding. + +U+0001 is included because a storage encoding that handles NUL has to leave the +next code point alone as well. +""" + +from __future__ import annotations + +import time + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table, wait_for_gsi_items + +NUL = "\u0000" +SOH = "\u0001" +ESCAPE_TEXT = "\\u0000" # backslash, u, 0, 0, 0, 0: six characters, not a NUL + +PK = f"a{NUL}b" +PK_WITHOUT_NUL = "ab" +PK_SOH = f"a{SOH}b" + +# One partition, five sort keys whose byte order is: NUL, U+0001, space, the +# escape text (starts with 0x5c), then "a" (0x61). +SORT_KEYS = [NUL, SOH, " ", ESCAPE_TEXT, "a"] + +# The item under the NUL sort key carries the character in every kind of +# position the item model has. +RICH_ITEM = { + "pk": {"S": PK}, + "sk": {"S": NUL}, + "g": {"S": f"g{NUL}"}, + "v": {"S": f"v{NUL}"}, + f"n{NUL}n": {"S": "x"}, + "m": {"M": {f"k{NUL}": {"S": f"{NUL}"}, f"k{SOH}{SOH}": {"N": "1"}}}, + "l": {"L": [{"S": NUL}, {"S": f"{SOH}{NUL}{SOH}"}]}, + "ss": {"SS": [NUL, "a"]}, +} + + +def _query(client, table, **kwargs): + return client.query( + TableName=table, + KeyConditionExpression=kwargs.pop("cond", "pk = :p"), + ExpressionAttributeValues={":p": {"S": PK}, **kwargs.pop("values", {})}, + **kwargs, + ) + + +def _sks(resp): + return [i["sk"]["S"] for i in resp["Items"]] + + +@pytest.fixture(scope="class") +def nul_table(dynamodb_client): + """(S, S) table with GSI gsi1 on g; the partition PK holds SORT_KEYS, plus + a control item in the partition without the NUL and one in a partition + keyed with U+0001.""" + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + GlobalSecondaryIndexes=[ + { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + ], + ) as name: + dynamodb_client.put_item(TableName=name, Item=RICH_ITEM) + for sk in SORT_KEYS[1:]: + dynamodb_client.put_item( + TableName=name, Item={"pk": {"S": PK}, "sk": {"S": sk}, "g": {"S": "plain"}} + ) + dynamodb_client.put_item( + TableName=name, Item={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": "x"}, "g": {"S": "plain"}} + ) + dynamodb_client.put_item( + TableName=name, + Item={"pk": {"S": PK_SOH}, "sk": {"S": SOH}, "g": {"S": f"g{SOH}"}, "v": {"S": SOH}}, + ) + yield name + + +class TestNulInStrings: + def test_item_with_nul_everywhere_round_trips(self, dynamodb_client, nul_table): + resp = dynamodb_client.get_item( + TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + ) + assert resp["Item"] == RICH_ITEM + + def test_soh_item_round_trips(self, dynamodb_client, nul_table): + resp = dynamodb_client.get_item( + TableName=nul_table, Key={"pk": {"S": PK_SOH}, "sk": {"S": SOH}}, ConsistentRead=True + ) + assert resp["Item"] == { + "pk": {"S": PK_SOH}, + "sk": {"S": SOH}, + "g": {"S": f"g{SOH}"}, + "v": {"S": SOH}, + } + + def test_partition_order_is_byte_order_with_nul_first(self, dynamodb_client, nul_table): + assert _sks(_query(dynamodb_client, nul_table, ConsistentRead=True)) == SORT_KEYS + assert ( + _sks(_query(dynamodb_client, nul_table, ScanIndexForward=False, ConsistentRead=True)) + == SORT_KEYS[::-1] + ) + + def test_nul_and_its_escape_text_are_different_keys(self, dynamodb_client, nul_table): + by_nul = dynamodb_client.get_item( + TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + )["Item"] + by_text = dynamodb_client.get_item( + TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": ESCAPE_TEXT}}, ConsistentRead=True + )["Item"] + assert by_nul["sk"]["S"] == NUL and len(by_nul["sk"]["S"]) == 1 + assert by_text["sk"]["S"] == ESCAPE_TEXT and len(by_text["sk"]["S"]) == 6 + + def test_partition_key_with_nul_is_distinct_from_the_key_without_it( + self, dynamodb_client, nul_table + ): + resp = dynamodb_client.get_item( + TableName=nul_table, Key={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": NUL}}, ConsistentRead=True + ) + assert "Item" not in resp + resp = _query(dynamodb_client, nul_table, values={":p": {"S": PK_WITHOUT_NUL}}, ConsistentRead=True) + assert _sks(resp) == ["x"] + + def test_range_conditions_treat_nul_as_a_byte(self, dynamodb_client, nul_table): + below_space = _query( + dynamodb_client, nul_table, cond="pk = :p AND sk < :s", values={":s": {"S": " "}}, + ConsistentRead=True, + ) + assert _sks(below_space) == [NUL, SOH] + between = _query( + dynamodb_client, nul_table, cond="pk = :p AND sk BETWEEN :lo AND :hi", + values={":lo": {"S": NUL}, ":hi": {"S": SOH}}, ConsistentRead=True, + ) + assert _sks(between) == [NUL, SOH] + prefix = _query( + dynamodb_client, nul_table, cond="pk = :p AND begins_with(sk, :pre)", + values={":pre": {"S": NUL}}, ConsistentRead=True, + ) + assert _sks(prefix) == [NUL] + text_prefix = _query( + dynamodb_client, nul_table, cond="pk = :p AND begins_with(sk, :pre)", + values={":pre": {"S": "\\"}}, ConsistentRead=True, + ) + assert _sks(text_prefix) == [ESCAPE_TEXT] + + def test_pages_of_one_visit_every_key_once(self, dynamodb_client, nul_table): + """The cursor for a NUL key travels through LastEvaluatedKey and back + through ExclusiveStartKey; the walk must neither skip nor repeat.""" + seen: list[str] = [] + kwargs: dict = {"Limit": 1, "ConsistentRead": True} + while True: + resp = _query(dynamodb_client, nul_table, **kwargs) + seen += _sks(resp) + if "LastEvaluatedKey" not in resp: + break + kwargs["ExclusiveStartKey"] = resp["LastEvaluatedKey"] + assert seen == SORT_KEYS + + def test_gsi_holds_the_item_with_a_nul_key(self, dynamodb_client, nul_table): + def walk(): + return dynamodb_client.query( + TableName=nul_table, + IndexName="gsi1", + KeyConditionExpression="g = :g", + ExpressionAttributeValues={":g": {"S": f"g{NUL}"}}, + )["Items"] + + items = wait_for_gsi_items(walk, 1) + assert items == [RICH_ITEM] + + def test_filter_on_a_nul_named_attribute(self, dynamodb_client, nul_table): + resp = dynamodb_client.scan( + TableName=nul_table, + FilterExpression="#n = :x", + ExpressionAttributeNames={"#n": f"n{NUL}n"}, + ExpressionAttributeValues={":x": {"S": "x"}}, + ConsistentRead=True, + ) + assert resp["Items"] == [RICH_ITEM] + resp = _query( + dynamodb_client, nul_table, FilterExpression="v = :v", + values={":v": {"S": f"v{NUL}"}}, ConsistentRead=True, + ) + assert resp["Items"] == [RICH_ITEM] + + def test_condition_expression_sees_the_nul_named_attribute(self, dynamodb_client, nul_table): + # Exists on the rich item: the conditional write goes through. + dynamodb_client.update_item( + TableName=nul_table, + Key={"pk": {"S": PK}, "sk": {"S": NUL}}, + UpdateExpression="SET touched = :t", + ConditionExpression="attribute_exists(#n)", + ExpressionAttributeNames={"#n": f"n{NUL}n"}, + ExpressionAttributeValues={":t": {"BOOL": True}}, + ) + with pytest.raises(ClientError) as exc: + dynamodb_client.update_item( + TableName=nul_table, + Key={"pk": {"S": PK}, "sk": {"S": "a"}}, + UpdateExpression="SET touched = :t", + ConditionExpression="attribute_exists(#n)", + ExpressionAttributeNames={"#n": f"n{NUL}n"}, + ExpressionAttributeValues={":t": {"BOOL": True}}, + ) + assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException" + dynamodb_client.update_item( + TableName=nul_table, + Key={"pk": {"S": PK}, "sk": {"S": NUL}}, + UpdateExpression="REMOVE touched", + ) + + def test_update_item_sets_nul_named_attribute_and_nul_value(self, dynamodb_client, nul_table): + key = {"pk": {"S": PK}, "sk": {"S": " "}} + resp = dynamodb_client.update_item( + TableName=nul_table, + Key=key, + UpdateExpression="SET #a = :v, m2 = :m", + ExpressionAttributeNames={"#a": f"u{NUL}"}, + ExpressionAttributeValues={ + ":v": {"S": f"{NUL}z"}, + ":m": {"M": {f"{NUL}": {"L": [{"S": SOH}]}}}, + }, + ReturnValues="ALL_NEW", + ) + assert resp["Attributes"][f"u{NUL}"] == {"S": f"{NUL}z"} + assert resp["Attributes"]["m2"] == {"M": {f"{NUL}": {"L": [{"S": SOH}]}}} + got = dynamodb_client.get_item(TableName=nul_table, Key=key, ConsistentRead=True)["Item"] + assert got[f"u{NUL}"] == {"S": f"{NUL}z"} + assert got["m2"] == {"M": {f"{NUL}": {"L": [{"S": SOH}]}}} + resp = dynamodb_client.update_item( + TableName=nul_table, + Key=key, + UpdateExpression="REMOVE #a, m2", + ExpressionAttributeNames={"#a": f"u{NUL}"}, + ReturnValues="ALL_NEW", + ) + assert f"u{NUL}" not in resp["Attributes"] and "m2" not in resp["Attributes"] + + def test_batch_and_transact_writes_and_reads(self, dynamodb_client, nul_table): + b1 = {"pk": {"S": f"batch{NUL}"}, "sk": {"S": NUL}, "g": {"S": "plain"}, f"{NUL}": {"S": NUL}} + t1 = {"pk": {"S": f"tx{NUL}"}, "sk": {"S": f"{NUL}{NUL}"}, "g": {"S": "plain"}} + dynamodb_client.batch_write_item(RequestItems={nul_table: [{"PutRequest": {"Item": b1}}]}) + dynamodb_client.transact_write_items( + TransactItems=[{"Put": {"TableName": nul_table, "Item": t1}}] + ) + got = dynamodb_client.batch_get_item( + RequestItems={ + nul_table: { + "Keys": [{"pk": b1["pk"], "sk": b1["sk"]}, {"pk": t1["pk"], "sk": t1["sk"]}], + "ConsistentRead": True, + } + } + )["Responses"][nul_table] + assert sorted(got, key=lambda i: i["pk"]["S"]) == sorted([b1, t1], key=lambda i: i["pk"]["S"]) + tg = dynamodb_client.transact_get_items( + TransactItems=[ + {"Get": {"TableName": nul_table, "Key": {"pk": b1["pk"], "sk": b1["sk"]}}}, + {"Get": {"TableName": nul_table, "Key": {"pk": t1["pk"], "sk": t1["sk"]}}}, + ] + )["Responses"] + assert [r["Item"] for r in tg] == [b1, t1] + dynamodb_client.batch_write_item( + RequestItems={ + nul_table: [ + {"DeleteRequest": {"Key": {"pk": b1["pk"], "sk": b1["sk"]}}}, + {"DeleteRequest": {"Key": {"pk": t1["pk"], "sk": t1["sk"]}}}, + ] + } + ) + + def test_scan_counts_every_item(self, dynamodb_client, nul_table): + resp = dynamodb_client.scan(TableName=nul_table, Select="COUNT", ConsistentRead=True) + assert resp["Count"] == len(SORT_KEYS) + 2 + + def test_delete_item_on_a_nul_key(self, dynamodb_client, nul_table): + key = {"pk": {"S": f"del{NUL}"}, "sk": {"S": NUL}} + dynamodb_client.put_item(TableName=nul_table, Item={**key, "g": {"S": "plain"}}) + resp = dynamodb_client.delete_item(TableName=nul_table, Key=key, ReturnValues="ALL_OLD") + assert resp["Attributes"] == {**key, "g": {"S": "plain"}} + assert "Item" not in dynamodb_client.get_item(TableName=nul_table, Key=key, ConsistentRead=True) + + +@pytest.fixture(scope="module") +def nul_streams_client(endpoint_url): + """Streams client on the ExtendDB endpoint. The service routes Streams to a + separate endpoint boto3 resolves on its own, so this test is ExtendDB only, + as the stream tests in ``test_streams.py`` are.""" + if not endpoint_url: + pytest.skip("stream record fidelity is checked against ExtendDB servers only") + import os + + import boto3 + + kwargs: dict = dict( + service_name="dynamodbstreams", + region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), + endpoint_url=endpoint_url, + ) + if endpoint_url.startswith("https://"): + kwargs["verify"] = False + return boto3.client(**kwargs) + + +def test_stream_records_carry_nul_keys_names_and_values(dynamodb_client, nul_streams_client): + """INSERT, MODIFY, and REMOVE records for an item whose key, attribute + names, map keys, and values hold U+0000 and U+0001 come back byte-identical + in Keys, NewImage, and OldImage.""" + from test_streams import _drain_all_shards + + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"}, + ) as name: + stream_arn = dynamodb_client.describe_table(TableName=name)["Table"]["LatestStreamArn"] + key = {"pk": {"S": PK}, "sk": {"S": NUL}} + first = {**RICH_ITEM} + dynamodb_client.put_item(TableName=name, Item=first) + second = dynamodb_client.update_item( + TableName=name, + Key=key, + UpdateExpression="SET #a = :v REMOVE #n", + ExpressionAttributeNames={"#a": f"u{NUL}", "#n": f"n{NUL}n"}, + ExpressionAttributeValues={":v": {"S": f"{SOH}{NUL}"}}, + ReturnValues="ALL_NEW", + )["Attributes"] + dynamodb_client.delete_item(TableName=name, Key=key) + + deadline = time.monotonic() + 30 + records: list[dict] = [] + while time.monotonic() < deadline: + records = _drain_all_shards(nul_streams_client, stream_arn) + if len(records) >= 3: + break + time.sleep(0.5) + assert [r["eventName"] for r in records] == ["INSERT", "MODIFY", "REMOVE"] + for r in records: + assert r["dynamodb"]["Keys"] == key + assert records[0]["dynamodb"]["NewImage"] == first + assert "OldImage" not in records[0]["dynamodb"] + assert records[1]["dynamodb"]["OldImage"] == first + assert records[1]["dynamodb"]["NewImage"] == second + assert records[2]["dynamodb"]["OldImage"] == second + assert "NewImage" not in records[2]["dynamodb"] From 09f112f7ab9427628d9ada53cbedf94f14b794f7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:42 +0000 Subject: [PATCH 02/30] fix(storage-postgres): derive restored key columns and index rows from the decoded item Main's restore (#384) reads each backup_items document as text, parses it into an Item and writes the text into the target's item_data unchanged. On this branch that text carries the control-character escape, and the key columns and index rows are built by helpers that escape their input, so the parsed item was escaped a second time: a restored table whose items hold U+0000 or U+0001 got key columns and index rows in a form the read path does not produce. The item is now decoded with json_to_item before the key helpers see it, and the key helpers are the escaping ones from key_text, so every column is escaped exactly once; the item_data text is still copied as it is. The backup copy sizes each item from the decoded form for the same reason. The parallel Scan cross-segment check (#203) hashes the candidate key's text and compares it with the hash of the stored pk column; it now uses the escaping pk_to_text so both sides hash the same text for keys with control characters. A storage-level test restores a table whose keys, index keys, attribute names and nested values hold U+0000 and U+0001 and compares the stored rows of the base table and both index tables with the source's, then reads each item back. --- crates/storage-postgres/src/backup_engine.rs | 22 ++- .../storage-postgres/src/data/data_engine.rs | 8 +- .../storage-postgres/tests/backup_restore.rs | 132 ++++++++++++++++++ 3 files changed, 152 insertions(+), 10 deletions(-) diff --git a/crates/storage-postgres/src/backup_engine.rs b/crates/storage-postgres/src/backup_engine.rs index 3255dbb2e..faec7877c 100755 --- a/crates/storage-postgres/src/backup_engine.rs +++ b/crates/storage-postgres/src/backup_engine.rs @@ -17,8 +17,7 @@ use extenddb_storage::backup_definition::{ }; use extenddb_storage::error::StorageError; use extenddb_storage::util::{ - SortKeyValue, backup_arn, backup_id_epoch_millis, composite_pk_to_text, new_backup_id, - parse_sk, sk_column_n, + SortKeyValue, backup_arn, backup_id_epoch_millis, new_backup_id, sk_column_n, }; use extenddb_storage::{BackupEngine, BackupRestoreSource, RestoreRequest}; use futures::future::BoxFuture; @@ -26,9 +25,10 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use crate::PostgresEngine; use crate::create_table::RestoreRegistration; +use crate::data::key_text::{composite_pk_to_text, parse_sk}; use crate::data::{ all_sort_key_info, data_table_name, index_table_name, insert_index_rows_multi, - item_has_index_keys, project_item_for_index, + item_has_index_keys, json_to_item, project_item_for_index, }; /// Convert a `PostgreSQL` `TIMESTAMPTZ` to epoch seconds as `f64`, keeping the @@ -530,8 +530,14 @@ impl PostgresEngine { let mut batch_bytes: usize = 0; let mut item_count: i64 = 0; while let Some(item_json) = rows.try_next().await.map_err(db_err)? { - let item: Item = serde_json::from_str(&item_json) - .map_err(|e| StorageError::Internal(format!("Parse backup item: {e}")))?; + // The stored text carries the control-character escape; it is + // copied into the target's `item_data` as it is, and decoded here + // so that the key columns and index rows derived from it are + // escaped exactly once by the same helpers the write path uses. + let item = json_to_item( + serde_json::from_str(&item_json) + .map_err(|e| StorageError::Internal(format!("Parse backup item: {e}")))?, + )?; // The parsed item is kept for its keys and index projections; the // budget counts its stored text, which bounds both forms. batch_bytes += item_json.len(); @@ -1220,8 +1226,10 @@ impl BackupEngine for PostgresEngine { let mut rows = sqlx::query_as::<_, (String, String)>(&select_sql).fetch(&mut *snapshot); while let Some((pk, data)) = rows.try_next().await.map_err(db_err)? { - let item: Item = serde_json::from_str(&data) - .map_err(|e| StorageError::Internal(format!("Parse item: {e}")))?; + let item = + json_to_item(serde_json::from_str(&data).map_err(|e| { + StorageError::Internal(format!("Parse item: {e}")) + })?)?; let item_bytes = extenddb_core::types::item_size_bytes(&item); drop(item); size += i64::try_from(item_bytes).unwrap_or(i64::MAX); diff --git a/crates/storage-postgres/src/data/data_engine.rs b/crates/storage-postgres/src/data/data_engine.rs index 88dd03794..de71c0f2b 100755 --- a/crates/storage-postgres/src/data/data_engine.rs +++ b/crates/storage-postgres/src/data/data_engine.rs @@ -7,10 +7,10 @@ use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition, UpdateAction}; use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_storage::error::StorageError; -use extenddb_storage::util::pk_to_text; use extenddb_storage::{DataEngine, IdempotencyKey, StreamCapture, TransactGetOp, TransactWriteOp}; use futures::future::BoxFuture; +use super::key_text::pk_to_text; use crate::PostgresEngine; impl DataEngine for PostgresEngine { @@ -201,8 +201,10 @@ impl DataEngine for PostgresEngine { // ((hashtext(pk)::bigint & 2147483647) % total = seg), evaluated for // the candidate key. `key_info` is scan-shaped, so `key_schema[0]` is // the pk of whichever table (data or index) the scan targets, matching - // the `pk` column the predicate hashes. Bigint bitmask instead of - // abs() per CB-20 / SP-SCN-002 (hashtext() == i32::MIN). + // the `pk` column the predicate hashes, so the key text is the stored + // (escaped) form, as `pk_to_text` from `key_text` gives it. Bigint + // bitmask instead of abs() per CB-20 / SP-SCN-002 (hashtext() == + // i32::MIN). let pk_name = key_info.key_schema[0].attribute_name.clone(); let key = key.clone(); Box::pin(async move { diff --git a/crates/storage-postgres/tests/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index 783b8a04c..aafbac1f8 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -2622,3 +2622,135 @@ async fn a_definition_read_that_loses_its_connection_is_transient() { assert!(recovered, "the pool reconnects after the failover"); s.cleanup().await; } + +/// Every stored row of one physical table, each as the JSON text of the +/// whole row, in a stable order. Two tables with the same stored form compare +/// equal; a difference in any column (an escaped key text, an `item_data` +/// document) shows up. +async fn stored_rows(s: &Scratch, physical_id: &str) -> Vec { + sqlx::query_scalar(&format!( + "SELECT to_jsonb(t)::text FROM \"_ddb_{physical_id}\" t ORDER BY 1" + )) + .fetch_all(&s.db) + .await + .expect("read stored rows") +} + +/// Items holding U+0000 and U+0001 in key values, index key values, nested +/// values, and attribute names are stored through the control-character +/// escape. A restore copies `backup_items` text into the target as it is and +/// derives the key columns and index rows from it, so those must come out in +/// the same stored form as the source's (escaped once, not twice), and the +/// restored items must read back equal to what was written. +#[tokio::test] +async fn restore_keeps_control_characters_in_keys_indexes_and_items() { + if base_conn().is_none() { + eprintln!("SKIP restore_keeps_control_characters_in_keys_indexes_and_items: no PostgreSQL"); + return; + } + let s = scratch().await; + let src = indexed_source_with(&s, "nul_src", 0).await; + let key_info = |table_name: &str, table_id: &str, desc: &TableDescription| TableKeyInfo { + table_name: table_name.to_owned(), + account_id: ACCOUNT.to_owned(), + table_id: table_id.to_owned(), + key_schema: desc.key_schema.clone(), + base_key_schema: desc.key_schema.clone(), + attribute_definitions: desc.attribute_definitions.clone(), + ..Default::default() + }; + let src_desc = s + .engine + .describe_table( + ACCOUNT, + DescribeTableInput { + table_name: "nul_src".to_owned(), + }, + ) + .await + .expect("describe the source"); + let src_key_info = key_info("nul_src", &src, &src_desc); + let items: Vec = [ + serde_json::json!({ + "pk": {"S": "p\u{0}a"}, "sk": {"N": "1"}, + "g": {"S": "g\u{0}\u{1}"}, "l": {"S": "l\u{1}\u{1}x"}, + "n\u{0}ame": {"S": "v\u{0}"}, + "m": {"M": {"k\u{1}": {"S": "\u{0}"}, "plain": {"N": "2"}}}, + "list": {"L": [{"S": "\u{1}\u{2}"}, {"SS": ["a\u{0}", "b"]}]} + }), + serde_json::json!({ + "pk": {"S": "p\u{0}a"}, "sk": {"N": "2"}, + "g": {"S": "g\u{0}\u{1}"}, "l": {"S": "l\u{0}"} + }), + serde_json::json!({"pk": {"S": "\u{1}"}, "sk": {"N": "3"}, "l": {"S": "\u{1}\u{2}"}}), + serde_json::json!({"pk": {"S": "plain"}, "sk": {"N": "4"}, "g": {"S": "g"}}), + ] + .into_iter() + .map(|v| serde_json::from_value(v).expect("item")) + .collect(); + for item in &items { + s.engine + .put_item( + &src_key_info, + item.clone(), + false, + None, + &extenddb_core::expression::ExpressionMaps::default(), + None, + ) + .await + .expect("put"); + } + + let backup = s + .engine + .create_backup(ACCOUNT, "nul_src", "b") + .await + .expect("backup"); + let desc = restore(&s, "nul_dst", &backup.backup_arn) + .await + .expect("restore"); + assert_eq!(table_status(&s, "nul_dst").await.as_deref(), Some("ACTIVE")); + + // The base table and each index table hold the same stored rows as the + // source's, so every key column and document was escaped exactly once. + assert_eq!( + stored_rows(&s, &desc.table_id).await, + stored_rows(&s, &src).await + ); + let src_idx = index_ids(&s, &src).await; + let dst_idx = index_ids(&s, &desc.table_id).await; + assert_eq!(src_idx.len(), 2); + for ((name, a), (_, b)) in src_idx.iter().zip(&dst_idx) { + let want = stored_rows(&s, a).await; + assert!(!want.is_empty(), "index {name} has rows at the source"); + assert_eq!(stored_rows(&s, b).await, want, "index {name}"); + } + + // The restored items read back equal to what was written. + let dst_desc = s + .engine + .describe_table( + ACCOUNT, + DescribeTableInput { + table_name: "nul_dst".to_owned(), + }, + ) + .await + .expect("describe the restored table"); + let dst_key_info = key_info("nul_dst", &desc.table_id, &dst_desc); + for item in &items { + let key: Item = item + .iter() + .filter(|(k, _)| *k == "pk" || *k == "sk") + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + let got = s + .engine + .get_item(&dst_key_info, &key) + .await + .expect("point read"); + assert_eq!(got.as_ref(), Some(item)); + } + s.cleanup().await; +} From 4dff16d2464a9395583a30ae3807e94ab106b6a5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:42 +0000 Subject: [PATCH 03/30] fix(migrate): name the catalog store sessions so the exclusive-access check ignores them On PostgreSQL, `migrate --yes` with 004_escape_control_chars pending refused every upgrade from 0.1.14: "3 other connection(s) hold the catalog database: extenddb from ... (no application name)". The migrate command opens catalog management and settings stores for the resource-tag step through the configured connection string, and those sessions carry no application name, so the check for foreign sessions that the data code migration runs before rewriting rows counted the command's own connections. The bootstrapper's pools carry the name and were ignored. The connection string handed to the catalog stores now carries application_name=extenddb-migrate when it is a PostgreSQL URL. Other backends' connection strings and a URL that already names an application pass through unchanged. The CLI test file gains the upgrade path a fresh init never reaches: the data ledger row for 004_escape_control_chars removed and the catalog rolled back, then migrate without --yes lists it, migrate --yes applies it and the deployment serves. The existing pre-vector test did not cover this because init records the data migration, so the exclusive-access check never ran. --- crates/app/src/cmd_migrate.rs | 68 ++++++++++++++++++- tests/test_cli_vector_catalog_migration.py | 78 ++++++++++++++++++++++ 2 files changed, 145 insertions(+), 1 deletion(-) diff --git a/crates/app/src/cmd_migrate.rs b/crates/app/src/cmd_migrate.rs index 507755bfb..dfa9c5914 100755 --- a/crates/app/src/cmd_migrate.rs +++ b/crates/app/src/cmd_migrate.rs @@ -114,7 +114,8 @@ pub async fn run(args: MigrateArgs) -> anyhow::Result { // Serialize concurrent migrators, such as several replicas starting at // once, so they don't race each other applying schema changes. bootstrap.acquire_migration_lock().await.map_err(op_err)?; - let result = match CatalogResourceTagStep::open(app_config.storage.connection_config()).await { + let catalog_connection = with_migrate_application_name(app_config.storage.connection_config()); + let result = match CatalogResourceTagStep::open(&catalog_connection).await { Ok(rtag) => apply_migrations(bootstrap.as_ref(), &args, &rtag).await, Err(e) => Err(e), }; @@ -143,6 +144,29 @@ fn backend_args( Ok(args) } +/// `application_name` the migrate command carries on every PostgreSQL session +/// it opens. The exclusive-access check for `004_escape_control_chars` +/// (`extenddb-storage-postgres`, `migrations::MIGRATE_APPLICATION_NAME`) counts +/// every session on the catalog and data databases except those with this +/// name. The bootstrapper sets it on its own pools; the catalog stores opened +/// by [`CatalogResourceTagStep`] connect through the configured connection +/// string and would otherwise be counted as foreign sessions, which makes +/// `migrate --yes` refuse every upgrade from a release without that migration. +const MIGRATE_APPLICATION_NAME: &str = "extenddb-migrate"; + +/// `connection` with `application_name=extenddb-migrate` added to its query +/// string when it is a PostgreSQL URL. Other backends' connection strings and a +/// URL that already names an application are returned unchanged. +fn with_migrate_application_name(connection: &str) -> String { + let is_postgres = + connection.starts_with("postgres://") || connection.starts_with("postgresql://"); + if !is_postgres || connection.contains("application_name=") { + return connection.to_owned(); + } + let separator = if connection.contains('?') { '&' } else { '?' }; + format!("{connection}{separator}application_name={MIGRATE_APPLICATION_NAME}") +} + /// Run the version checks and apply pending migrations while the migration lock /// is held. Split out of `run` so that the lock is always released afterwards. async fn apply_migrations( @@ -762,6 +786,48 @@ mod backend_args_tests { } } +#[cfg(test)] +mod application_name_tests { + use super::with_migrate_application_name; + + #[test] + fn a_postgres_url_without_a_query_string_gets_the_name() { + assert_eq!( + with_migrate_application_name("postgresql://app:pw@db:5432/extenddb_catalog"), + "postgresql://app:pw@db:5432/extenddb_catalog?application_name=extenddb-migrate" + ); + assert_eq!( + with_migrate_application_name("postgres://db/cat"), + "postgres://db/cat?application_name=extenddb-migrate" + ); + } + + #[test] + fn a_postgres_url_with_a_query_string_gets_the_name_appended() { + assert_eq!( + with_migrate_application_name("postgresql://db/cat?sslmode=require"), + "postgresql://db/cat?sslmode=require&application_name=extenddb-migrate" + ); + } + + #[test] + fn an_existing_application_name_is_kept() { + let given = "postgresql://db/cat?application_name=ops"; + assert_eq!(with_migrate_application_name(given), given); + } + + #[test] + fn other_backends_are_unchanged() { + for given in [ + "/var/lib/extenddb/extenddb.sqlite", + "mongodb://127.0.0.1:27017/?replicaSet=rs0", + "cassandra://127.0.0.1:9042", + ] { + assert_eq!(with_migrate_application_name(given), given); + } + } +} + #[cfg(test)] mod newer_catalog_tests { use super::refuse_newer_catalog; diff --git a/tests/test_cli_vector_catalog_migration.py b/tests/test_cli_vector_catalog_migration.py index 452d30776..2e0c1b3ce 100644 --- a/tests/test_cli_vector_catalog_migration.py +++ b/tests/test_cli_vector_catalog_migration.py @@ -37,6 +37,9 @@ # Moves the version for the stored string encoding; changes no schema. A 0.0.2 # deployment has none of these three recorded. ENCODING_MIGRATION = "004_control_chars_encoding.sql" +# The data code migration that rewrites stored rows into the escaped encoding. +# Recorded in the data database's own `schema_history`, not the catalog's. +ENCODING_DATA_MIGRATION = "004_escape_control_chars" # The version the binary expects, written by the last catalog migration. Every # current-version assertion reads it from here so the next bump is one edit. @@ -88,6 +91,38 @@ def _backup_definitions_table_exists(cli_env): ) +def _data_conn(cli_env): + """The data database `init` creates beside the catalog (`_catalog`).""" + import psycopg2 + + data_db = cli_env["db_name"][: -len("_catalog")] + return psycopg2.connect(PG_ADMIN_CONN + "/" + data_db) + + +def _forget_data_migration(cli_env, name): + """Remove a data code migration's ledger row, as a deployment from before + that migration has it.""" + conn = _data_conn(cli_env) + try: + conn.autocommit = True + with conn.cursor() as cur: + cur.execute("DELETE FROM schema_history WHERE filename = %s", (name,)) + finally: + conn.close() + + +def _data_migration_recorded(cli_env, name): + conn = _data_conn(cli_env) + try: + with conn.cursor() as cur: + cur.execute( + "SELECT COUNT(*) FROM schema_history WHERE filename = %s", (name,) + ) + return cur.fetchone()[0] == 1 + finally: + conn.close() + + def _init(cli_env): result = _run_extenddb( "init", *_init_args(cli_env), @@ -213,6 +248,49 @@ def test_migrate_upgrades_a_pre_vector_deployment(self, cli_env): assert again.returncode == 0, again_output assert "up to date" in again_output.lower(), again_output + def test_migrate_applies_the_pending_string_encoding_data_migration(self, cli_env): + """The 0.1.14 upgrade: `004_escape_control_chars` pending in the data ledger. + + The data code migration rewrites stored rows, so migrate refuses to run it + while any other session holds the catalog or data database. The command + itself opens catalog stores for the resource-tag step before that check; + those sessions must carry the migrate application name or the check + counts them as foreign and every upgrade is refused. + + A fresh init records the data migration, so the ledger row is removed + here, with the catalog rolled back, to reproduce an upgrade from the + release before it. + """ + _init(cli_env) + _patch_config_port(cli_env["config_path"], cli_env["port"]) + _roll_catalog_back_to_pre_vector(cli_env) + _forget_data_migration(cli_env, ENCODING_DATA_MIGRATION) + + pending = _run_extenddb( + "migrate", *_pg_args(), config=cli_env["config_path"], check=False + ) + pending_output = pending.stdout + pending.stderr + assert pending.returncode == 3, pending_output + assert ENCODING_DATA_MIGRATION in pending_output, pending_output + + applied = _run_extenddb( + "migrate", "--yes", *_pg_args(), config=cli_env["config_path"], check=False + ) + output = applied.stdout + applied.stderr + assert applied.returncode == 0, output + assert "other connection(s) hold" not in output, output + assert f"Applying {ENCODING_DATA_MIGRATION}" in output, output + assert _catalog_version(cli_env) == CURRENT_CATALOG_VERSION + assert _data_migration_recorded(cli_env, ENCODING_DATA_MIGRATION) is True + + served = _run_extenddb("serve", config=cli_env["config_path"]) + assert served.returncode == 0, served.stdout + served.stderr + try: + assert _wait_for_server(cli_env["port"]), "upgraded deployment did not serve" + finally: + _run_extenddb("stop", config=cli_env["config_path"], check=False) + time.sleep(1) + def test_migrate_survives_an_applied_but_unrecorded_migration(self, cli_env): """A replay of the vector migration must succeed, not block the deployment. From 9323f76a6bff3e259052668074a606ae0c11bf93 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:42 +0000 Subject: [PATCH 04/30] refactor(app): move the migrate application_name helper into its own module Pure move of with_migrate_application_name, its constant and its four tests from cmd_migrate.rs into migrate_connection.rs. No behaviour change. cmd_migrate.rs goes back from 856 to 793 lines. --- crates/app/src/cmd_migrate.rs | 67 +-------------------------- crates/app/src/lib.rs | 1 + crates/app/src/migrate_connection.rs | 69 ++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 65 deletions(-) create mode 100644 crates/app/src/migrate_connection.rs diff --git a/crates/app/src/cmd_migrate.rs b/crates/app/src/cmd_migrate.rs index dfa9c5914..717bfe2ad 100755 --- a/crates/app/src/cmd_migrate.rs +++ b/crates/app/src/cmd_migrate.rs @@ -16,6 +16,8 @@ use extenddb_config as config; use extenddb_storage::error::StorageError; use extenddb_storage::management_store::OpError; +use crate::migrate_connection::with_migrate_application_name; + /// Exit status of a preview (`migrate` without `--yes`) that found work to do. /// Distinct from 1 so a script can tell "pending" from "failed". pub const EXIT_PENDING: u8 = 3; @@ -144,29 +146,6 @@ fn backend_args( Ok(args) } -/// `application_name` the migrate command carries on every PostgreSQL session -/// it opens. The exclusive-access check for `004_escape_control_chars` -/// (`extenddb-storage-postgres`, `migrations::MIGRATE_APPLICATION_NAME`) counts -/// every session on the catalog and data databases except those with this -/// name. The bootstrapper sets it on its own pools; the catalog stores opened -/// by [`CatalogResourceTagStep`] connect through the configured connection -/// string and would otherwise be counted as foreign sessions, which makes -/// `migrate --yes` refuse every upgrade from a release without that migration. -const MIGRATE_APPLICATION_NAME: &str = "extenddb-migrate"; - -/// `connection` with `application_name=extenddb-migrate` added to its query -/// string when it is a PostgreSQL URL. Other backends' connection strings and a -/// URL that already names an application are returned unchanged. -fn with_migrate_application_name(connection: &str) -> String { - let is_postgres = - connection.starts_with("postgres://") || connection.starts_with("postgresql://"); - if !is_postgres || connection.contains("application_name=") { - return connection.to_owned(); - } - let separator = if connection.contains('?') { '&' } else { '?' }; - format!("{connection}{separator}application_name={MIGRATE_APPLICATION_NAME}") -} - /// Run the version checks and apply pending migrations while the migration lock /// is held. Split out of `run` so that the lock is always released afterwards. async fn apply_migrations( @@ -786,48 +765,6 @@ mod backend_args_tests { } } -#[cfg(test)] -mod application_name_tests { - use super::with_migrate_application_name; - - #[test] - fn a_postgres_url_without_a_query_string_gets_the_name() { - assert_eq!( - with_migrate_application_name("postgresql://app:pw@db:5432/extenddb_catalog"), - "postgresql://app:pw@db:5432/extenddb_catalog?application_name=extenddb-migrate" - ); - assert_eq!( - with_migrate_application_name("postgres://db/cat"), - "postgres://db/cat?application_name=extenddb-migrate" - ); - } - - #[test] - fn a_postgres_url_with_a_query_string_gets_the_name_appended() { - assert_eq!( - with_migrate_application_name("postgresql://db/cat?sslmode=require"), - "postgresql://db/cat?sslmode=require&application_name=extenddb-migrate" - ); - } - - #[test] - fn an_existing_application_name_is_kept() { - let given = "postgresql://db/cat?application_name=ops"; - assert_eq!(with_migrate_application_name(given), given); - } - - #[test] - fn other_backends_are_unchanged() { - for given in [ - "/var/lib/extenddb/extenddb.sqlite", - "mongodb://127.0.0.1:27017/?replicaSet=rs0", - "cassandra://127.0.0.1:9042", - ] { - assert_eq!(with_migrate_application_name(given), given); - } - } -} - #[cfg(test)] mod newer_catalog_tests { use super::refuse_newer_catalog; diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 3857465bf..aa51d615d 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -36,6 +36,7 @@ mod cmd_verify; mod init_helpers; mod manage_http; mod manage_types; +mod migrate_connection; mod serve_helpers; mod util; diff --git a/crates/app/src/migrate_connection.rs b/crates/app/src/migrate_connection.rs new file mode 100644 index 000000000..527a609a6 --- /dev/null +++ b/crates/app/src/migrate_connection.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The `application_name` the migrate command sets on the PostgreSQL sessions +//! it opens through the configured connection string. + +/// `application_name` the migrate command carries on every PostgreSQL session +/// it opens. The exclusive-access check for `004_escape_control_chars` +/// (`extenddb-storage-postgres`, `migrations::MIGRATE_APPLICATION_NAME`) counts +/// every session on the catalog and data databases except those with this +/// name. The bootstrapper sets it on its own pools; the catalog stores opened +/// by `CatalogResourceTagStep` connect through the configured connection +/// string and would otherwise be counted as foreign sessions, which makes +/// `migrate --yes` refuse every upgrade from a release without that migration. +const MIGRATE_APPLICATION_NAME: &str = "extenddb-migrate"; + +/// `connection` with `application_name=extenddb-migrate` added to its query +/// string when it is a PostgreSQL URL. Other backends' connection strings and a +/// URL that already names an application are returned unchanged. +pub(crate) fn with_migrate_application_name(connection: &str) -> String { + let is_postgres = + connection.starts_with("postgres://") || connection.starts_with("postgresql://"); + if !is_postgres || connection.contains("application_name=") { + return connection.to_owned(); + } + let separator = if connection.contains('?') { '&' } else { '?' }; + format!("{connection}{separator}application_name={MIGRATE_APPLICATION_NAME}") +} + +#[cfg(test)] +mod application_name_tests { + use super::with_migrate_application_name; + + #[test] + fn a_postgres_url_without_a_query_string_gets_the_name() { + assert_eq!( + with_migrate_application_name("postgresql://app:pw@db:5432/extenddb_catalog"), + "postgresql://app:pw@db:5432/extenddb_catalog?application_name=extenddb-migrate" + ); + assert_eq!( + with_migrate_application_name("postgres://db/cat"), + "postgres://db/cat?application_name=extenddb-migrate" + ); + } + + #[test] + fn a_postgres_url_with_a_query_string_gets_the_name_appended() { + assert_eq!( + with_migrate_application_name("postgresql://db/cat?sslmode=require"), + "postgresql://db/cat?sslmode=require&application_name=extenddb-migrate" + ); + } + + #[test] + fn an_existing_application_name_is_kept() { + let given = "postgresql://db/cat?application_name=ops"; + assert_eq!(with_migrate_application_name(given), given); + } + + #[test] + fn other_backends_are_unchanged() { + for given in [ + "/var/lib/extenddb/extenddb.sqlite", + "mongodb://127.0.0.1:27017/?replicaSet=rs0", + "cassandra://127.0.0.1:9042", + ] { + assert_eq!(with_migrate_application_name(given), given); + } + } +} From 3e86e5c93cb82ce5f3ad73763d84a0464d53456f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:42 +0000 Subject: [PATCH 05/30] fix(app): replace an application_name already in the migrate connection string The exclusive-access check for 004_escape_control_chars skips only sessions named extenddb-migrate. A connection string that already set application_name kept the operator's name, so migrate --yes counted its own catalog sessions as foreign and refused the upgrade. The helper now drops any application_name parameter and appends extenddb-migrate. The unit test for an existing name fails on the previous helper and passes now. --- crates/app/src/migrate_connection.rs | 35 +++++++++++++++++++++------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/app/src/migrate_connection.rs b/crates/app/src/migrate_connection.rs index 527a609a6..a80d9a231 100644 --- a/crates/app/src/migrate_connection.rs +++ b/crates/app/src/migrate_connection.rs @@ -13,17 +13,26 @@ /// `migrate --yes` refuse every upgrade from a release without that migration. const MIGRATE_APPLICATION_NAME: &str = "extenddb-migrate"; -/// `connection` with `application_name=extenddb-migrate` added to its query -/// string when it is a PostgreSQL URL. Other backends' connection strings and a -/// URL that already names an application are returned unchanged. +/// `connection` with its `application_name` set to `extenddb-migrate` when it is +/// a PostgreSQL URL. An `application_name` already in the query string is +/// replaced: the exclusive-access check skips only sessions with this exact +/// name, so a URL that keeps an operator's name would make `migrate --yes` +/// count its own sessions as foreign and refuse. Other backends' connection +/// strings are returned unchanged. pub(crate) fn with_migrate_application_name(connection: &str) -> String { let is_postgres = connection.starts_with("postgres://") || connection.starts_with("postgresql://"); - if !is_postgres || connection.contains("application_name=") { + if !is_postgres { return connection.to_owned(); } - let separator = if connection.contains('?') { '&' } else { '?' }; - format!("{connection}{separator}application_name={MIGRATE_APPLICATION_NAME}") + let (base, query) = connection.split_once('?').unwrap_or((connection, "")); + let mut params: Vec<&str> = query + .split('&') + .filter(|p| !p.is_empty() && !p.starts_with("application_name=")) + .collect(); + let ours = format!("application_name={MIGRATE_APPLICATION_NAME}"); + params.push(&ours); + format!("{base}?{}", params.join("&")) } #[cfg(test)] @@ -51,9 +60,17 @@ mod application_name_tests { } #[test] - fn an_existing_application_name_is_kept() { - let given = "postgresql://db/cat?application_name=ops"; - assert_eq!(with_migrate_application_name(given), given); + fn an_existing_application_name_is_replaced() { + assert_eq!( + with_migrate_application_name("postgresql://db/cat?application_name=ops"), + "postgresql://db/cat?application_name=extenddb-migrate" + ); + assert_eq!( + with_migrate_application_name( + "postgresql://db/cat?sslmode=require&application_name=ops&connect_timeout=5" + ), + "postgresql://db/cat?sslmode=require&connect_timeout=5&application_name=extenddb-migrate" + ); } #[test] From 36b4aa64c724b78d76c6909ec8603e15b13ef4aa Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:52:43 +0000 Subject: [PATCH 06/30] test(storage-postgres): make the catalog version unreadable after the scratch setup serve_refuses_an_unreadable_catalog_version_with_the_shared_refusal wrote 'garbage' into catalog_version from the scratch setup's third migration step. The setup also applies 004_control_chars_encoding.sql after that step, and 004 sets catalog_version to 0.0.5, so the test read "0.0.5" and failed its first assertion before it reached serve. The test now passes the shipped 003 as the setup's third step and writes the unreadable version once the setup has returned. The test failed on the previous revision (left "0.0.5", right "garbage") and passes now in 5 runs of 5, with the other four tests in catalog_converge.rs. --- crates/storage-postgres/tests/catalog_converge.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/storage-postgres/tests/catalog_converge.rs b/crates/storage-postgres/tests/catalog_converge.rs index 0c49aafea..e1257746a 100644 --- a/crates/storage-postgres/tests/catalog_converge.rs +++ b/crates/storage-postgres/tests/catalog_converge.rs @@ -599,10 +599,15 @@ async fn serve_refuses_an_unreadable_catalog_version_with_the_shared_refusal() { return; } let s = Scratch::new( - "003_tampered_version.sql", - "UPDATE settings SET value = 'garbage' WHERE key = 'catalog_version';", + "003_backup_definitions.sql", + include_str!("../migrations/003_backup_definitions.sql"), ) .await; + // After the setup, whose 004 step stamps the current version. + sqlx::query("UPDATE settings SET value = 'garbage' WHERE key = 'catalog_version'") + .execute(&s.catalog) + .await + .expect("make the stored version unreadable"); assert_eq!(s.catalog_version().await, "garbage"); let expected = extenddb_storage::util::check_stored_catalog_version( Some("garbage"), From c9b675ace400f4e34fd2068856b7caab9ff6009d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:25:00 +0000 Subject: [PATCH 07/30] fix(storage-postgres): rebuild composite keys and queue partitions in migration 004 Migration 004 escaped every text key column with one SQL replace(). A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, and the replace grew a part without fixing its length prefix: the legacy index key 2:a\x01,1:b, became 2:a\x01\x02,1:b, where this build writes and looks up 3:a\x01\x02,1:b,. A Query on such a GSI missed the legacy row, and the next write of the item left it behind as a duplicate. Those rows are now rebuilt one at a time: the legacy value is split into its netstring parts, each part is escaped, and the parts are joined again by key_text::join_escaped_parts, the function composite_pk_to_text uses on the write path. The columns come from the catalog key schemas: pk of a table or index with several HASH attributes, base_pk of the index and vector tables of a table with several (limits.allow_multipart_table_keys), and pk of backup_items for a backup of such a table. Sort key columns hold one attribute each (sk_s, sk2_s, ...) and keep the replace(). gsi_pending.worker_partition is a hash of the stored base key text, which the escape changes for a key holding U+0001, while 004 rewrote only the jsonb columns of the queue. A row queued at upgrade time and the next write of the same item then went to different workers, which breaks the one item, one worker rule of the queue. 004 now recomputes the column for the queued rows whose item holds U+0001, through gsi_queue::worker_partition, the function enqueue_gsi_pending uses. Every row of an item moves to the same partition and keeps its id and ready_at. Live tests: rebuilds_composite_partition_keys_part_by_part seeds a table with two HASH attributes, a two-HASH GSI, a one-HASH GSI on the two-HASH table and a backup of each, with a raw U+0001 in a HASH part, and checks each rebuilt column against composite_pk_to_text. recomputes_the_worker_partition_of_rows_queued_before_the_upgrade seeds queued rows whose worker_partition was computed from the raw key, checks that they move to the partition this build computes, and that the next enqueue of the item lands there. Each fails with the previous migration. --- crates/storage-postgres/src/data/key_text.rs | 112 +++- crates/storage-postgres/src/gsi_queue.rs | 29 +- crates/storage-postgres/src/lib.rs | 1 + .../src/migration_004_keys.rs | 484 ++++++++++++++++++ crates/storage-postgres/src/migrations.rs | 156 ++++-- 5 files changed, 738 insertions(+), 44 deletions(-) create mode 100644 crates/storage-postgres/src/migration_004_keys.rs diff --git a/crates/storage-postgres/src/data/key_text.rs b/crates/storage-postgres/src/data/key_text.rs index a433907af..e58141d8b 100644 --- a/crates/storage-postgres/src/data/key_text.rs +++ b/crates/storage-postgres/src/data/key_text.rs @@ -59,9 +59,59 @@ pub(crate) fn composite_pk_to_text( ks.attribute_name )) })?; - parts.push(pk_to_text(val)?.into_owned()); + parts.push(util::pk_to_text(val)?); } - Ok(encode_netstring_composite(&parts)) + Ok(join_escaped_parts(&parts)) +} + +/// The stored text of a composite partition key whose parts, as +/// `extenddb_storage::util::pk_to_text` renders each HASH attribute, are +/// `raw_parts`: each part escaped, then netstring-joined. The netstring length +/// is that of the escaped part. +/// +/// [`composite_pk_to_text`] builds every composite key column through this +/// function, and migration `004_escape_control_chars` rebuilds legacy +/// composite key columns through it ([`reescape_legacy_composite`]). +pub(crate) fn join_escaped_parts>(raw_parts: &[S]) -> String { + let parts: Vec = raw_parts + .iter() + .map(|p| escape_control(p.as_ref()).into_owned()) + .collect(); + encode_netstring_composite(&parts) +} + +/// Split a netstring-joined composite key (`:,` per part, `len` +/// the part's length in bytes) into its parts. `None` when `text` is not a +/// sequence of well-formed netstrings. +pub(crate) fn split_netstring_composite(text: &str) -> Option> { + let mut parts = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + let colon = rest.find(':')?; + let digits = &rest[..colon]; + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let len: usize = digits.parse().ok()?; + let start = colon + 1; + let end = start.checked_add(len)?; + let part = rest.get(start..end)?; + if rest.as_bytes().get(end) != Some(&b',') { + return None; + } + parts.push(part); + rest = &rest[end + 1..]; + } + (!parts.is_empty()).then_some(parts) +} + +/// The stored form of a composite key column that a build without the escape +/// wrote: its netstring parts hold raw text, so each is escaped and the parts +/// are joined again with the new lengths, as [`composite_pk_to_text`] writes the +/// same key. Escaping the whole text instead would leave every length prefix +/// counting the raw part. `None` when `legacy` is not a netstring. +pub(crate) fn reescape_legacy_composite(legacy: &str) -> Option { + split_netstring_composite(legacy).map(|parts| join_escaped_parts(&parts)) } /// Sort key attribute value as a typed bind value, string keys escaped. @@ -128,6 +178,64 @@ mod tests { assert_eq!(text, "a\u{1}\u{1}"); } + #[test] + fn netstring_split_inverts_the_join() { + let cases: [&[&str]; 5] = [ + &["a", "b"], + &["", "x"], + &["1:a,", ",:", "z"], + &["a\u{1}\u{2}", "\u{e9}t\u{e9}", "12"], + &["only"], + ]; + for parts in cases { + let owned: Vec = parts.iter().map(|p| (*p).to_owned()).collect(); + let joined = encode_netstring_composite(&owned); + assert_eq!( + split_netstring_composite(&joined).as_deref(), + Some(parts), + "{joined:?}" + ); + } + for bad in [ + "", + "a", + "1:ab,", + "2:a,", + "x:ab,", + "+1:a,", + "1:a", + "1:a,2", + "1:\u{e9},", + ] { + assert_eq!(split_netstring_composite(bad), None, "{bad:?}"); + } + } + + #[test] + fn a_legacy_composite_key_is_rebuilt_as_the_write_path_builds_it() { + // The case from the review: a raw U+0001 in the first of two HASH + // parts. Escaping the whole text would give 2:a\x01\x02,1:b, with a + // length prefix that no longer matches its part. + let legacy = "2:a\u{1},1:b,"; + let rebuilt = reescape_legacy_composite(legacy).expect("a netstring"); + assert_eq!(rebuilt, "3:a\u{1}\u{2},1:b,"); + + let mut item = Item::new(); + item.insert("h1".to_owned(), AttributeValue::S("a\u{1}".into())); + item.insert("h2".to_owned(), AttributeValue::S("b".into())); + assert_eq!( + composite_pk_to_text(&item, &[ks("h1"), ks("h2")]).unwrap(), + rebuilt + ); + + // Parts without U+0001 keep their text and their lengths. + assert_eq!( + reescape_legacy_composite("1:x,2:yz,").as_deref(), + Some("1:x,2:yz,") + ); + assert_eq!(reescape_legacy_composite("a\u{1}b"), None); + } + #[test] fn stored_text_never_contains_nul() { for raw in ["\u{0}", "a\u{0}b", "\u{0}\u{1}\u{2}", "x\u{1}\u{1}y"] { diff --git a/crates/storage-postgres/src/gsi_queue.rs b/crates/storage-postgres/src/gsi_queue.rs index 44288f55d..053cbb25d 100644 --- a/crates/storage-postgres/src/gsi_queue.rs +++ b/crates/storage-postgres/src/gsi_queue.rs @@ -157,7 +157,7 @@ const PG_UNDEFINED_TABLE: &str = "SQLSTATE 42P01"; /// order. A local /// hash (not `std`'s, which is not guaranteed stable across builds) keeps the /// mapping fixed for a given key forever. -fn partition_for(base_pk_text: &str) -> i32 { +pub(crate) fn partition_for(base_pk_text: &str) -> i32 { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a offset basis for byte in base_pk_text.as_bytes() { hash ^= u64::from(*byte); @@ -166,6 +166,24 @@ fn partition_for(base_pk_text: &str) -> i32 { (hash % NUM_WORKERS) as i32 } +/// The `worker_partition` of a queued row: the partition of its base key, +/// which `new_item` carries for puts and updates and `old_item` for deletes +/// (the base key is immutable over an item's lifetime). The key text is the +/// stored (escaped) form, so a key holding U+0001 hashes differently from the +/// raw text a build without the escape hashed; migration +/// `004_escape_control_chars` recomputes the column of such rows through this +/// function. +pub(crate) fn worker_partition( + old_item: Option<&Item>, + new_item: Option<&Item>, + context: &PendingApplyContext, +) -> Result { + Ok(match new_item.or(old_item) { + Some(item) => partition_for(&composite_pk_to_text(item, context.base_key_schema())?), + None => 0, + }) +} + /// Check if a `StorageError` is caused by an undefined table (SQLSTATE 42P01). /// /// This occurs when an index table is dropped (table deleted) while an async @@ -325,14 +343,7 @@ pub(crate) async fn enqueue_gsi_pending( let old_json = old_item.map(crate::data::item_to_json).transpose()?; let new_json = new_item.map(crate::data::item_to_json).transpose()?; let context_json = crate::data::to_stored_json(context)?; - - // Route all updates for a given base item to one worker. - // The base key is immutable over an item's lifetime; `new_item` carries it - // for puts/updates, `old_item` for deletes. - let worker_partition = match new_item.or(old_item) { - Some(item) => partition_for(&composite_pk_to_text(item, context.base_key_schema())?), - None => 0, - }; + let worker_partition = worker_partition(old_item, new_item, context)?; let delay_interval = jitter_delay_ms(delay_ms) as f64 / 1000.0; sqlx::query( diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 85db7204b..cdcb6f6a1 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -21,6 +21,7 @@ mod delete_table; pub(crate) mod gsi_queue; mod management_store; mod metadata_engine; +mod migration_004_keys; mod migrations; mod operations; mod pg_util; diff --git a/crates/storage-postgres/src/migration_004_keys.rs b/crates/storage-postgres/src/migration_004_keys.rs new file mode 100644 index 000000000..73b60c253 --- /dev/null +++ b/crates/storage-postgres/src/migration_004_keys.rs @@ -0,0 +1,484 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Two rewrites of `004_escape_control_chars` (`migrations.rs`) that cannot be +//! done by escaping a stored text where it lies, because the text is derived +//! from the key strings: +//! +//! - A partition key column of a key schema with more than one HASH attribute +//! holds the netstring join of the parts (`:,` each), and the +//! escape changes a part's length. [`rebuild_composite_rows`] splits each +//! legacy value, escapes the parts and joins them again with the new +//! lengths, through the function the write path uses +//! (`key_text::join_escaped_parts`). +//! - `gsi_pending.worker_partition` is a hash of the stored base key text +//! (`gsi_queue::partition_for`), so it changes with the key text. +//! [`recompute_worker_partitions`] recomputes it with the function the +//! enqueue uses (`gsi_queue::worker_partition`). +//! +//! Both run inside the per-table transaction of `escape_rows_in_table`, before +//! that table's progress marker commits. + +use extenddb_storage::management_store::{OpError, OpResult}; + +use crate::data::key_text::reescape_legacy_composite; +use crate::gsi_queue::{PendingApplyContext, worker_partition}; + +/// The `backup_items` rows whose `pk` holds a composite key: the rows of a +/// backup whose table's key schema has more than one HASH attribute. A boolean +/// SQL expression over a `backup_items` row; `backups` is in the same catalog +/// database. +pub(crate) const BACKUP_ITEMS_COMPOSITE_ROWS: &str = "backup_arn IN (\ + SELECT b.backup_arn FROM backups b WHERE (\ + SELECT COUNT(*) FROM jsonb_array_elements(b.key_schema) e \ + WHERE e->>'KeyType' = 'HASH') > 1)"; + +/// Whether a catalog key schema (`[{"AttributeName", "KeyType"}, ...]`) has +/// more than one HASH attribute, so its partition key column holds a netstring +/// join. +pub(crate) fn has_composite_partition_key(key_schema: &serde_json::Value) -> bool { + key_schema.as_array().is_some_and(|elements| { + elements + .iter() + .filter(|e| e.get("KeyType").and_then(serde_json::Value::as_str) == Some("HASH")) + .count() + > 1 + }) +} + +/// Rebuild the composite key text in `col` of the rows that `rows` (a boolean +/// SQL expression over the row) selects and that hold U+0001, one row at a +/// time. A SQL `replace()` over the whole text would leave each length prefix +/// counting the raw part (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, +/// where this build writes and looks up `3:a\x01\x02,1:b,`). A value that is +/// not a netstring fails the migration, naming the table and column; the +/// table's transaction rolls back and nothing is marked. +pub(crate) async fn rebuild_composite_rows( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + quoted_table: &str, + col: &str, + rows: &str, +) -> OpResult { + let select = format!( + "SELECT ctid::text, \"{col}\" FROM {quoted_table} \ + WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) FOR UPDATE" + ); + let found: Vec<(String, String)> = sqlx::query_as(&select) + .fetch_all(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Find {quoted_table}.{col} to rebuild: {e}")))?; + let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); + for (ctid, legacy) in &found { + let rebuilt = reescape_legacy_composite(legacy).ok_or_else(|| { + OpError::Internal(format!( + "Re-encode {quoted_table}.{col}: the composite key {legacy:?} is not a netstring" + )) + })?; + sqlx::query(&update) + .bind(rebuilt) + .bind(ctid) + .execute(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Rebuild {quoted_table}.{col}: {e}")))?; + } + Ok(found.len() as u64) +} + +/// The partition a row queued with these columns gets from this build's +/// enqueue, or `None` when a column does not decode (a worker handles such a +/// row as a poison row, whatever partition holds it). +fn current_partition( + old_item: Option, + new_item: Option, + index_context: serde_json::Value, +) -> Option { + let old_item = old_item.map(crate::data::json_to_item).transpose().ok()?; + let new_item = new_item.map(crate::data::json_to_item).transpose().ok()?; + let context: PendingApplyContext = crate::data::stored_json_to(index_context).ok()?; + worker_partition(old_item.as_ref(), new_item.as_ref(), &context).ok() +} + +/// Recompute `worker_partition` of the queued rows whose item holds U+0001, +/// after their jsonb columns were re-encoded in the same transaction. +/// +/// A build without the escape hashed the raw base key; this build hashes the +/// escaped one, so for a key holding U+0001 a row queued before the upgrade and +/// the next write of the same item would be claimed by different workers, in +/// either order, which breaks the queue's one item, one worker rule. Every row +/// of one item moves to the same new partition and keeps its `id` and +/// `ready_at`, so the item's rows are still claimed in write order, and a row +/// enqueued after the upgrade gets a `ready_at` no earlier than theirs from the +/// partition clamp in `enqueue_gsi_pending`. +pub(crate) async fn recompute_worker_partitions( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, +) -> OpResult { + type Row = ( + i64, + i32, + Option, + Option, + serde_json::Value, + ); + // '\u0001' is how jsonb::text renders U+0001; chr(92) spells the backslash + // as in `escape_jsonb_rows`. The base key is in new_item, or in old_item for + // a delete, as `worker_partition` reads it. + let rows: Vec = sqlx::query_as( + "SELECT id, worker_partition, old_item, new_item, index_context FROM gsi_pending \ + WHERE position((chr(92) || 'u0001') IN COALESCE(new_item, old_item)::text) > 0 \ + ORDER BY id FOR UPDATE", + ) + .fetch_all(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Find gsi_pending rows to repartition: {e}")))?; + let mut changed: u64 = 0; + for (id, stored, old_item, new_item, index_context) in rows { + let Some(partition) = current_partition(old_item, new_item, index_context) else { + continue; + }; + if partition == stored { + continue; + } + sqlx::query("UPDATE gsi_pending SET worker_partition = $1 WHERE id = $2") + .bind(partition) + .bind(id) + .execute(&mut **tx) + .await + .map_err(|e| OpError::Internal(format!("Repartition gsi_pending row {id}: {e}")))?; + changed += 1; + } + Ok(changed) +} + +#[cfg(test)] +mod tests { + use super::has_composite_partition_key; + use serde_json::json; + + #[test] + fn only_a_key_schema_with_two_or_more_hash_attributes_is_composite() { + let one = json!([ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let two = json!([ + {"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let ranges = json!([ + {"AttributeName": "h", "KeyType": "HASH"}, + {"AttributeName": "r1", "KeyType": "RANGE"}, + {"AttributeName": "r2", "KeyType": "RANGE"} + ]); + assert!(!has_composite_partition_key(&one)); + assert!(has_composite_partition_key(&two)); + assert!(!has_composite_partition_key(&ranges)); + assert!(!has_composite_partition_key(&json!({}))); + } +} + +#[cfg(test)] +mod live { + //! Live checks against a scratch database, with the helpers and the + //! skip convention of `migrations::live_reencode`: without + //! `EXTENDDB_TEST_PG_CONNECTION_STRING` every test reports a skip and + //! passes. Each seeds rows the way a build without the escape wrote them. + + use extenddb_core::types::{ + AttributeDefinition, AttributeValue, Item, KeySchemaElement, KeyType, Projection, + ProjectionType, ScalarAttributeType, + }; + use serde_json::json; + use sqlx::PgPool; + + use crate::data::key_text::composite_pk_to_text; + use crate::gsi_queue::{ + GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending, partition_for, + worker_partition, + }; + use crate::migrations::live_reencode::{base_conn, scratch, skip}; + use crate::migrations::run_data_code_migrations; + + fn element(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } + } + + fn text(v: &str) -> AttributeValue { + AttributeValue::S(v.to_owned()) + } + + async fn exec(db: &PgPool, sql: &str, binds: &[serde_json::Value]) { + let mut q = sqlx::query(sql); + for b in binds { + q = q.bind(b.clone()); + } + q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); + } + + async fn texts(db: &PgPool, sql: &str) -> Vec { + sqlx::query_scalar(sql) + .fetch_all(db) + .await + .unwrap_or_else(|e| panic!("{sql}: {e}")) + } + + /// A table with two HASH attributes (`t2`), a two-HASH GSI on a one-HASH + /// table (`i2` on `t1`), a one-HASH GSI on `t2` (`i3`), and a backup of + /// each table, each holding a legacy row with a raw U+0001 in a HASH part. + async fn seed_composite(db: &PgPool) { + exec( + db, + "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'esc')", + &[], + ) + .await; + let one = json!([{"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}]); + let two = json!([{"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}]); + for (id, ks) in [("t1", &one), ("t2", &two)] { + exec( + db, + &format!( + "INSERT INTO tables (account_id, table_name, key_schema, \ + attribute_definitions, table_status, table_arn, table_id) \ + VALUES ('111122223333', '{id}', $1, '[]', 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/{id}', '{id}')" + ), + std::slice::from_ref(ks), + ) + .await; + } + for (table, index, ks) in [ + ( + "t1", + "i2", + json!([{"AttributeName": "g1", "KeyType": "HASH"}, + {"AttributeName": "g2", "KeyType": "HASH"}]), + ), + ( + "t2", + "i3", + json!([{"AttributeName": "g", "KeyType": "HASH"}]), + ), + ] { + exec( + db, + &format!( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, \ + key_schema, projection) VALUES ('{table}', '{index}', '{index}', 'GSI', \ + $1, '{{\"ProjectionType\": \"ALL\"}}')" + ), + &[ks], + ) + .await; + } + sqlx::raw_sql( + r#"CREATE TABLE "_ddb_t2" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, sk_s)); + CREATE TABLE "_ddb_i2" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); + CREATE TABLE "_ddb_i3" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); + INSERT INTO "_ddb_t2" VALUES + (E'2:a\x01,1:b,', 's', + '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}, "sk": {"S": "s"}}'), + ('1:x,1:y,', 's', '{"h1": {"S": "x"}, "h2": {"S": "y"}, "sk": {"S": "s"}}'); + INSERT INTO "_ddb_i2" VALUES + (E'2:g\x01,1:h,', NULL, E'p\x01', E's\x01', + '{"g1": {"S": "g\u0001"}, "g2": {"S": "h"}, "pk": {"S": "p\u0001"}}'); + INSERT INTO "_ddb_i3" VALUES + (E'g\x01', NULL, E'2:a\x01,1:b,', 's', + '{"g": {"S": "g\u0001"}, "h1": {"S": "a\u0001"}, "h2": {"S": "b"}}'); + INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, + key_schema, attribute_definitions) VALUES + ('b1', 'b1', 't1', 't1', '111122223333', + '[{"AttributeName": "pk", "KeyType": "HASH"}]', '[]'), + ('b2', 'b2', 't2', 't2', '111122223333', + '[{"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}]', '[]'); + INSERT INTO backup_items (backup_arn, pk, sk, item_data) VALUES + ('b1', E'p\x01', NULL, '{"pk": {"S": "p\u0001"}}'), + ('b2', E'2:a\x01,1:b,', NULL, '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}}');"#, + ) + .execute(db) + .await + .expect("seed the legacy rows"); + } + + #[tokio::test] + async fn rebuilds_composite_partition_keys_part_by_part() { + if base_conn().is_none() { + skip("rebuilds_composite_partition_keys_part_by_part"); + return; + } + let s = scratch().await; + seed_composite(&s.db).await; + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run the data code migrations"); + + // What this build writes and looks up for the legacy key + // h1 = "a\x01", h2 = "b": each part escaped, then joined. + let mut item = Item::new(); + item.insert("h1".to_owned(), text("a\u{1}")); + item.insert("h2".to_owned(), text("b")); + let ks = [element("h1", KeyType::Hash), element("h2", KeyType::Hash)]; + let expected = composite_pk_to_text(&item, &ks).expect("composite key text"); + assert_eq!(expected, "3:a\u{1}\u{2},1:b,"); + + // The table with two HASH attributes: the legacy row is rebuilt, the + // plain row keeps its text. + assert_eq!( + texts(&s.db, "SELECT pk FROM \"_ddb_t2\" ORDER BY pk").await, + vec!["1:x,1:y,".to_owned(), expected.clone()] + ); + // A two-HASH GSI: pk rebuilt, the one-HASH base key replaced. + let row: (String, String, String) = + sqlx::query_as("SELECT pk, base_pk, base_sk_s FROM \"_ddb_i2\"") + .fetch_one(&s.db) + .await + .expect("read _ddb_i2"); + assert_eq!( + row, + ( + "3:g\u{1}\u{2},1:h,".to_owned(), + "p\u{1}\u{2}".to_owned(), + "s\u{1}\u{2}".to_owned() + ) + ); + // A one-HASH GSI on the two-HASH table: pk replaced, base_pk rebuilt. + let row: (String, String) = sqlx::query_as("SELECT pk, base_pk FROM \"_ddb_i3\"") + .fetch_one(&s.db) + .await + .expect("read _ddb_i3"); + assert_eq!(row, ("g\u{1}\u{2}".to_owned(), expected.clone())); + // backup_items: the backup of the two-HASH table is rebuilt, the + // other replaced. + assert_eq!( + texts(&s.db, "SELECT pk FROM backup_items ORDER BY backup_arn").await, + vec!["p\u{1}\u{2}".to_owned(), expected] + ); + s.cleanup().await; + } + + fn context() -> PendingApplyContext { + PendingApplyContext::Gsi(GsiApplyContext { + base_key_schema: vec![element("pk", KeyType::Hash)], + attribute_definitions: vec![AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }], + index: GsiIndexDef { + index_id: "i1".to_owned(), + key_schema: vec![element("g", KeyType::Hash)], + projection: Projection { + projection_type: ProjectionType::All, + non_key_attributes: None, + }, + }, + }) + } + + /// The partition a build without the escape gave a row for `item`: the + /// hash of the raw key text. + fn legacy_partition(item: &Item) -> i32 { + let raw = + extenddb_storage::util::composite_pk_to_text(item, &[element("pk", KeyType::Hash)]) + .expect("raw key text"); + partition_for(&raw) + } + + #[tokio::test] + async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { + if base_conn().is_none() { + skip("recomputes_the_worker_partition_of_rows_queued_before_the_upgrade"); + return; + } + let ctx = context(); + // A key holding U+0001 whose raw and escaped texts hash to different + // workers, so the test sees the move. + let item = [ + "a\u{1}b", + "b\u{1}", + "\u{1}c", + "key\u{1}1", + "key\u{1}2", + "key\u{1}3", + ] + .into_iter() + .map(|k| { + let mut item = Item::new(); + item.insert("pk".to_owned(), text(k)); + item.insert("g".to_owned(), text("v")); + item + }) + .find(|item| { + legacy_partition(item) != worker_partition(None, Some(item), &ctx).expect("partition") + }) + .expect("a key whose partition moves"); + let current = worker_partition(None, Some(&item), &ctx).expect("partition"); + let legacy = legacy_partition(&item); + + // A key without U+0001 and a non-key string with it: same text both ways. + let mut plain = Item::new(); + plain.insert("pk".to_owned(), text("plain")); + plain.insert("note".to_owned(), text("n\u{1}")); + let plain_partition = legacy_partition(&plain); + + let s = scratch().await; + let raw_ctx = serde_json::to_value(&ctx).expect("context json"); + let raw = |i: &Item| serde_json::to_value(i).expect("item json"); + for (old_item, new_item, partition) in [ + (None, Some(raw(&item)), legacy), + (Some(raw(&item)), None, legacy), + (None, Some(raw(&plain)), plain_partition), + ] { + sqlx::query( + "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ + index_context) VALUES ('t1', $1, $2, $3, $4)", + ) + .bind(partition) + .bind(old_item) + .bind(new_item) + .bind(&raw_ctx) + .execute(&s.db) + .await + .expect("seed a queued row"); + } + + run_data_code_migrations(&s.db, &s.db) + .await + .expect("run the data code migrations"); + + let partitions: Vec = + sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id") + .fetch_all(&s.db) + .await + .expect("read gsi_pending"); + assert_eq!(partitions, vec![current, current, plain_partition]); + + // The next write of the item is queued on the same worker. + let mut tx = s.db.begin().await.expect("begin"); + enqueue_gsi_pending(&mut tx, "t1", None, Some(&item), 1, &ctx) + .await + .expect("enqueue the next write"); + tx.commit().await.expect("commit"); + let next: i32 = + sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id DESC LIMIT 1") + .fetch_one(&s.db) + .await + .expect("read the new row"); + assert_eq!(next, current); + s.cleanup().await; + } +} diff --git a/crates/storage-postgres/src/migrations.rs b/crates/storage-postgres/src/migrations.rs index 29502042d..f4e9c7fa2 100755 --- a/crates/storage-postgres/src/migrations.rs +++ b/crates/storage-postgres/src/migrations.rs @@ -662,21 +662,49 @@ async fn is_table_marked(pool: &PgPool, migration: &str, table: &str) -> OpResul } /// One physical table's rewrite work for `004_escape_control_chars`: the text -/// key columns that get the single-statement SQL replace, and the jsonb -/// columns whose rows are re-encoded one by one. +/// key columns, and the jsonb columns whose rows are re-encoded one by one. struct EscapeWork { /// Bare (unquoted) table name, e.g. `_ddb_` or `gsi_pending`. table: String, - text_columns: Vec, + text_columns: Vec, jsonb_columns: Vec, + /// `gsi_pending` only: recompute `worker_partition` after the re-encode + /// (`migration_004_keys::recompute_worker_partitions`). + recompute_worker_partition: bool, +} + +/// A text key column and the rows of it that hold a composite partition key. +struct TextKeyColumn { + name: String, + /// SQL boolean expression over the row, true where the column holds the + /// netstring join of several HASH attributes. Those rows are rebuilt one + /// by one (`migration_004_keys::rebuild_composite_rows`); the others hold + /// one attribute's text and get the single-statement SQL replace. + composite_rows: String, +} + +impl TextKeyColumn { + fn new(name: String, composite: bool) -> Self { + let composite_rows = if composite { "TRUE" } else { "FALSE" }.to_owned(); + Self { + name, + composite_rows, + } + } } /// Rewrite work for a dynamically named `_ddb_*` table, read from /// `information_schema.columns` so that exactly the sort key columns this /// table has (`sk_s`, `sk_s`, `base_sk_s`, ...) are covered. Returns /// `None` when the physical table does not exist (a catalog row mid-create or -/// mid-delete): such a table has no legacy rows to re-encode. -async fn dynamic_table_work(pool: &PgPool, table: String) -> OpResult> { +/// mid-delete): such a table has no legacy rows to re-encode. `composite` +/// names the columns whose key schema has more than one HASH attribute, so +/// they hold a netstring join on every row. +async fn dynamic_table_work( + pool: &PgPool, + table: String, + composite: &[&str], +) -> OpResult> { let text_columns: Vec = sqlx::query_scalar( "SELECT column_name::text FROM information_schema.columns \ WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'text' \ @@ -701,10 +729,18 @@ async fn dynamic_table_work(pool: &PgPool, table: String) -> OpResult OpResult let quoted = format!("\"{}\"", work.table); let mut rewritten: u64 = 0; - // Key text columns: TEXT has no escaping layer, so a single SQL statement - // per column is exact. NULL columns never match (position() is NULL). + // Key text columns holding one attribute's text: TEXT has no escaping + // layer, so a single SQL statement per column is exact. NULL columns never + // match (position() is NULL). Rows holding a composite key are rebuilt + // part by part instead, before any other column of the row changes. for col in &work.text_columns { + let TextKeyColumn { + name, + composite_rows, + } = col; let sql = format!( - "UPDATE {quoted} SET \"{col}\" = replace(\"{col}\", chr(1), chr(1) || chr(2)) \ - WHERE position(chr(1) IN \"{col}\") > 0" + "UPDATE {quoted} SET \"{name}\" = replace(\"{name}\", chr(1), chr(1) || chr(2)) \ + WHERE position(chr(1) IN \"{name}\") > 0 AND NOT ({composite_rows})" ); let done = sqlx::query(&sql) .execute(&mut *tx) .await - .map_err(|e| OpError::Internal(format!("Re-encode {}.{col}: {e}", work.table)))?; + .map_err(|e| OpError::Internal(format!("Re-encode {}.{name}: {e}", work.table)))?; rewritten += done.rows_affected(); + if composite_rows != "FALSE" { + rewritten += crate::migration_004_keys::rebuild_composite_rows( + &mut tx, + "ed, + name, + composite_rows, + ) + .await?; + } } for col in &work.jsonb_columns { rewritten += escape_jsonb_rows(&mut tx, "ed, col).await?; } + if work.recompute_worker_partition { + rewritten += crate::migration_004_keys::recompute_worker_partitions(&mut tx).await?; + } sqlx::query(&format!( "INSERT INTO {CODE_MIGRATION_PROGRESS_TABLE} (migration_name, table_name) \ @@ -911,41 +969,64 @@ async fn escape_legacy_control_chars(catalog_pool: &PgPool, data_pool: &PgPool) // Every data table, index table, and vector index table, enumerated from // the catalog. Their text key columns are read from information_schema so - // single-sort-key, multi-sort-key, and base_* layouts are all covered. - let table_ids: Vec = - sqlx::query_scalar("SELECT table_id FROM tables ORDER BY table_id") + // single-sort-key, multi-sort-key, and base_* layouts are all covered. A + // partition key column whose key schema has more than one HASH attribute + // holds a netstring join (`key_text::composite_pk_to_text`): `pk` of a + // table or index with such a key schema, and `base_pk` of the index and + // vector tables of a table with one. + use crate::migration_004_keys::has_composite_partition_key as composite; + let tables: Vec<(String, serde_json::Value)> = + sqlx::query_as("SELECT table_id, key_schema FROM tables ORDER BY table_id") .fetch_all(catalog_pool) .await .map_err(|e| OpError::Internal(format!("Enumerate tables: {e}")))?; - for id in table_ids { - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}")).await? { + let composite_tables: std::collections::HashSet<&str> = tables + .iter() + .filter(|(_, ks)| composite(ks)) + .map(|(id, _)| id.as_str()) + .collect(); + for (id, ks) in &tables { + let cols: &[&str] = if composite(ks) { &["pk"] } else { &[] }; + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), cols).await? { work.push((data_pool, w)); } } - let index_ids: Vec = - sqlx::query_scalar("SELECT index_id FROM indexes ORDER BY index_id") + let indexes: Vec<(String, String, serde_json::Value)> = + sqlx::query_as("SELECT index_id, table_id, key_schema FROM indexes ORDER BY index_id") .fetch_all(catalog_pool) .await .map_err(|e| OpError::Internal(format!("Enumerate indexes: {e}")))?; - for id in index_ids { - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}")).await? { + for (id, table_id, ks) in &indexes { + let mut cols: Vec<&str> = Vec::new(); + if composite(ks) { + cols.push("pk"); + } + if composite_tables.contains(table_id.as_str()) { + cols.push("base_pk"); + } + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), &cols).await? { work.push((data_pool, w)); } } - let vector_ids: Vec = - sqlx::query_scalar("SELECT index_id FROM vector_indexes ORDER BY index_id") + let vectors: Vec<(String, String)> = + sqlx::query_as("SELECT index_id, table_id FROM vector_indexes ORDER BY index_id") .fetch_all(catalog_pool) .await .map_err(|e| OpError::Internal(format!("Enumerate vector indexes: {e}")))?; - for id in vector_ids { - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_vec_{id}")).await? { + for (id, table_id) in &vectors { + let cols: &[&str] = if composite_tables.contains(table_id.as_str()) { + &["base_pk"] + } else { + &[] + }; + if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_vec_{id}"), cols).await? { work.push((data_pool, w)); } } // Fixed tables holding item documents. gsi_pending and stream_records live // in the data database; backup_items lives in the catalog database. - if let Some(w) = fixed_table_work( + if let Some(mut w) = fixed_table_work( data_pool, "gsi_pending", &[], @@ -953,14 +1034,23 @@ async fn escape_legacy_control_chars(catalog_pool: &PgPool, data_pool: &PgPool) ) .await? { + w.recompute_worker_partition = true; work.push((data_pool, w)); } if let Some(w) = fixed_table_work(data_pool, "stream_records", &[], &["record_data"]).await? { work.push((data_pool, w)); } - if let Some(w) = + if let Some(mut w) = fixed_table_work(catalog_pool, "backup_items", &["pk", "sk"], &["item_data"]).await? { + // `pk` is the data table's `pk` as the backup copied it, so a backup of + // a table with several HASH attributes holds a netstring join there. + for col in &mut w.text_columns { + if col.name == "pk" { + col.composite_rows = + crate::migration_004_keys::BACKUP_ITEMS_COMPOSITE_ROWS.to_owned(); + } + } work.push((catalog_pool, w)); } @@ -1238,7 +1328,7 @@ mod tests { } #[cfg(test)] -mod live_reencode { +pub(crate) mod live_reencode { //! Live checks for `004_escape_control_chars` against a scratch database. //! //! Follows the convention of `tests/key_collation.rs`: each test needs @@ -1259,14 +1349,14 @@ mod live_reencode { unapplied_required_data_migrations, }; - struct Scratch { - db: PgPool, + pub(crate) struct Scratch { + pub(crate) db: PgPool, admin: PgPool, db_name: String, } impl Scratch { - async fn cleanup(self) { + pub(crate) async fn cleanup(self) { let Scratch { db, admin, db_name } = self; db.close().await; sqlx::query(&format!( @@ -1279,19 +1369,19 @@ mod live_reencode { } } - fn base_conn() -> Option { + pub(crate) fn base_conn() -> Option { let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").ok()?; (!conn.trim().is_empty()).then(|| conn.trim_end_matches('/').to_owned()) } - fn skip(test: &str) { + pub(crate) fn skip(test: &str) { eprintln!( "SKIP {test}: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is no \ PostgreSQL to build a scratch database in." ); } - async fn scratch() -> Scratch { + pub(crate) async fn scratch() -> Scratch { let base = base_conn().expect("caller checks base_conn() first"); let db_name = format!("eddb_esc_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); let admin = PgPoolOptions::new() From 0bd7324a9e59290926c2bfd8c08915caa56356b3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:01:28 +0000 Subject: [PATCH 08/30] fix(storage-postgres): rewrite legacy keys longest first in migration 004 Two legacy keys that differ only by a U+0002 after a U+0001, such as a\x01 and a\x01\x02 with the same sort key, escape to two different texts, but the first one's new text, a\x01\x02, is the second one's legacy text. PostgreSQL checks the primary key as each row changes, so the one statement 004 issued per key column failed with a unique violation when it met the shorter key first, which depends on where the two rows are stored. The migration stopped with the catalog at 0.0.5 and 004 not recorded, and a retry failed the same way. The composite key rebuild had the same failure on 2:a\x01,1:b, beside 3:a\x01\x02,1:b,. The statement now runs under a savepoint. On a unique violation it is rolled back and the column is rewritten row by row, longest legacy text first, and the composite key rebuild uses the same order. Every rewrite makes the text longer and the escape is injective, so when a row's new text is another row's legacy text, that other row is longer and was rewritten first; migration_004_order.rs states the argument in full. Both paths read the rows through one cursor in that order, 500 rows at a time, where the rebuild loaded every matching key of the table at once. A duplicate that remains is reported with PostgreSQL's DETAIL, which names the key, and with the DynamoDB table or index of the physical table. Live tests store each pair with the shorter key first in the heap: a partition key pair with one sort key, a sort key pair, a two-HASH composite pair, a base_pk pair on an index table, and one table on each path with more rows than one batch and its pair in two batches. Each checks that 004 completes and that every final text is the escape of its legacy text, and each fails with the previous migration. A pair whose byte order is the reverse of its length order, a\x01b beside a\x01\x02b, fails when the rows are ordered by their text instead of their length. a_duplicate_that_remains_is_reported_with_its_key checks the error text, and an_error_names_the_dynamodb_table checks that an error names the DynamoDB table. --- crates/storage-postgres/src/lib.rs | 1 + .../src/migration_004_keys.rs | 40 +- .../src/migration_004_order.rs | 513 ++++++++++++++++++ crates/storage-postgres/src/migrations.rs | 129 ++++- 4 files changed, 628 insertions(+), 55 deletions(-) create mode 100644 crates/storage-postgres/src/migration_004_order.rs diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index cdcb6f6a1..a4f096180 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -22,6 +22,7 @@ pub(crate) mod gsi_queue; mod management_store; mod metadata_engine; mod migration_004_keys; +mod migration_004_order; mod migrations; mod operations; mod pg_util; diff --git a/crates/storage-postgres/src/migration_004_keys.rs b/crates/storage-postgres/src/migration_004_keys.rs index 73b60c253..3ed75d3fb 100644 --- a/crates/storage-postgres/src/migration_004_keys.rs +++ b/crates/storage-postgres/src/migration_004_keys.rs @@ -48,40 +48,28 @@ pub(crate) fn has_composite_partition_key(key_schema: &serde_json::Value) -> boo /// Rebuild the composite key text in `col` of the rows that `rows` (a boolean /// SQL expression over the row) selects and that hold U+0001, one row at a -/// time. A SQL `replace()` over the whole text would leave each length prefix -/// counting the raw part (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, -/// where this build writes and looks up `3:a\x01\x02,1:b,`). A value that is -/// not a netstring fails the migration, naming the table and column; the -/// table's transaction rolls back and nothing is marked. +/// time, longest legacy text first and in batches +/// (`migration_004_order::rewrite_longest_first`). A SQL `replace()` over the +/// whole text would leave each length prefix counting the raw part +/// (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, where this build writes and +/// looks up `3:a\x01\x02,1:b,`). A value that is not a netstring fails the +/// migration, naming the table and column (`what`); the table's transaction +/// rolls back and nothing is marked. pub(crate) async fn rebuild_composite_rows( tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, quoted_table: &str, col: &str, rows: &str, + what: &str, ) -> OpResult { - let select = format!( - "SELECT ctid::text, \"{col}\" FROM {quoted_table} \ - WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) FOR UPDATE" - ); - let found: Vec<(String, String)> = sqlx::query_as(&select) - .fetch_all(&mut **tx) - .await - .map_err(|e| OpError::Internal(format!("Find {quoted_table}.{col} to rebuild: {e}")))?; - let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); - for (ctid, legacy) in &found { - let rebuilt = reescape_legacy_composite(legacy).ok_or_else(|| { + crate::migration_004_order::rewrite_longest_first(tx, quoted_table, col, rows, what, |legacy| { + reescape_legacy_composite(legacy).ok_or_else(|| { OpError::Internal(format!( - "Re-encode {quoted_table}.{col}: the composite key {legacy:?} is not a netstring" + "Re-encode {what}: the composite key {legacy:?} is not a netstring" )) - })?; - sqlx::query(&update) - .bind(rebuilt) - .bind(ctid) - .execute(&mut **tx) - .await - .map_err(|e| OpError::Internal(format!("Rebuild {quoted_table}.{col}: {e}")))?; - } - Ok(found.len() as u64) + }) + }) + .await } /// The partition a row queued with these columns gets from this build's diff --git a/crates/storage-postgres/src/migration_004_order.rs b/crates/storage-postgres/src/migration_004_order.rs new file mode 100644 index 000000000..fd5bb8070 --- /dev/null +++ b/crates/storage-postgres/src/migration_004_order.rs @@ -0,0 +1,513 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Row-by-row rewrites of one key column for `004_escape_control_chars` +//! (`migrations.rs`), in an order that keeps the table's primary key valid +//! after every row. +//! +//! `PostgreSQL` checks a primary key as each row changes, not at the end of the +//! statement. Two legacy keys that differ only by a U+0002 after a U+0001, such +//! as `a\x01` and `a\x01\x02` with the same other key columns, escape to two +//! different texts, `a\x01\x02` and `a\x01\x02\x02`, but the first one's new +//! text is the second one's legacy text. If the shorter one is rewritten first, +//! the table holds `a\x01\x02` twice until the longer one is rewritten, and the +//! update fails with SQLSTATE 23505. A one-statement `UPDATE` meets the two rows +//! in heap order, so whether it fails depends on where they are stored. +//! +//! [`rewrite_longest_first`] rewrites the rows in descending byte length of +//! their legacy text, which never produces such a duplicate: +//! +//! - Every rewrite makes the text longer. Every row it rewrites holds a U+0001, +//! and the escape adds one byte for each; a rebuilt composite key also gives +//! each part its new length, which never takes fewer digits than the old one. +//! - Suppose rewriting row `r` gives the text that row `s` holds, and the two +//! rows agree on the other key columns. If `s` has not been rewritten yet, it +//! holds its legacy text, and that text is the new text of `r`, so it is +//! longer than the legacy text of `r` and `s` was rewritten earlier. If `s` +//! has been rewritten, the two rows have the same new text, and since the +//! escape is injective their legacy texts were equal. +//! - Each other key column holds the legacy texts of every row, or, when an +//! earlier pass of the same transaction rewrote it, their escapes. Either +//! way two rows agree on it now exactly when they agreed before the +//! migration. Two rows that agreed on every key column before the migration +//! would have broken the primary key, so no rewrite meets a duplicate. + +use extenddb_storage::management_store::{OpError, OpResult}; + +/// Rows read from the cursor per round trip, the batch `escape_jsonb_rows` +/// fetches. +pub(crate) const BATCH: usize = 500; + +/// The cursor [`rewrite_longest_first`] declares and closes before returning. +const CURSOR: &str = "escape_004_longest_first"; + +/// Rewrite `col` of the rows that hold U+0001 and that `rows` (a boolean SQL +/// expression over the row) selects, one row at a time, longest legacy text +/// first; `rewrite` gives a row's new text from its legacy text. Runs inside +/// the caller's per-table transaction and returns the number of rows changed. +/// `what` names the column in errors, with the DynamoDB table when the caller +/// knows it. +/// +/// One cursor is declared over the matching rows in that order and read +/// [`BATCH`] rows at a time, so this process holds one batch, and `PostgreSQL` +/// sorts the matching rows in `work_mem`, spilling to temporary files beyond +/// it. The cursor's rows are fixed when it is declared and each is returned +/// once, so no row is rewritten twice. Each row is locked as the cursor +/// returns it, as the single-statement path locks the rows it updates. +pub(crate) async fn rewrite_longest_first( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + quoted_table: &str, + col: &str, + rows: &str, + what: &str, + rewrite: impl Fn(&str) -> OpResult, +) -> OpResult { + let failed = |step: &str, e: &sqlx::Error| { + OpError::Internal(format!("{step} {what}: {}", with_detail(e))) + }; + sqlx::query(&format!( + "DECLARE {CURSOR} NO SCROLL CURSOR FOR \ + SELECT ctid::text, \"{col}\" FROM {quoted_table} \ + WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) \ + ORDER BY octet_length(\"{col}\") DESC FOR UPDATE" + )) + .execute(&mut **tx) + .await + .map_err(|e| failed("Find the rows to rewrite in", &e))?; + let fetch = format!("FETCH {BATCH} FROM {CURSOR}"); + let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); + let mut changed: u64 = 0; + loop { + let batch: Vec<(String, String)> = sqlx::query_as(&fetch) + .fetch_all(&mut **tx) + .await + .map_err(|e| failed("Read the rows to rewrite in", &e))?; + for (ctid, legacy) in &batch { + let done = sqlx::query(&update) + .bind(rewrite(legacy)?) + .bind(ctid) + .execute(&mut **tx) + .await + .map_err(|e| failed("Re-encode", &e))?; + changed += done.rows_affected(); + } + if batch.len() < BATCH { + break; + } + } + sqlx::query(&format!("CLOSE {CURSOR}")) + .execute(&mut **tx) + .await + .map_err(|e| failed("Close the cursor over", &e))?; + Ok(changed) +} + +/// A database error as text, with `PostgreSQL`'s DETAIL when the error has one; +/// for a unique violation the DETAIL names the key already present. sqlx's +/// `Display` writes the message alone. The DETAIL is quoted with its control +/// characters escaped, since the keys this migration rewrites hold them. +pub(crate) fn with_detail(e: &sqlx::Error) -> String { + let detail = match e { + sqlx::Error::Database(db) => db + .try_downcast_ref::() + .and_then(sqlx::postgres::PgDatabaseError::detail), + _ => None, + }; + match detail { + Some(detail) => format!("{e} (DETAIL: {detail:?})"), + None => e.to_string(), + } +} + +#[cfg(test)] +mod live { + //! Live checks with the scratch database and the skip convention of + //! `migrations::live_reencode`. The tables are created by the DDL + //! `CreateTable` runs, so their primary keys are the production ones. Each + //! test stores legacy keys that differ only by a U+0002 after a U+0001, + //! the shorter one first in the heap, the order a one-statement rewrite + //! fails on. `item_data` is `{}`: the tests check the key columns. + + use extenddb_core::types::{ + AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType, + }; + use extenddb_storage::management_store::OpError; + use extenddb_storage::util::escape_control; + use sqlx::PgPool; + + use super::{BATCH, rewrite_longest_first}; + use crate::PostgresEngine; + use crate::data::key_text::reescape_legacy_composite; + use crate::migrations::live_reencode::{base_conn, scratch, skip}; + use crate::migrations::run_data_code_migrations; + + fn key(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } + } + + fn string_attributes(key_schema: &[KeySchemaElement]) -> Vec { + key_schema + .iter() + .map(|k| AttributeDefinition { + attribute_name: k.attribute_name.clone(), + attribute_type: ScalarAttributeType::S, + }) + .collect() + } + + fn json(value: &T) -> serde_json::Value { + serde_json::to_value(value).expect("json") + } + + /// The account, the `tables` row and the data table of table `id`. + async fn table(db: &PgPool, id: &str, key_schema: &[KeySchemaElement]) { + let attributes = string_attributes(key_schema); + sqlx::query( + "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'order') \ + ON CONFLICT DO NOTHING", + ) + .execute(db) + .await + .expect("seed the account"); + sqlx::query( + "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ + table_status, table_arn, table_id) VALUES ('111122223333', $1, $2, $3, 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/' || $1, $1)", + ) + .bind(id) + .bind(json(&key_schema)) + .bind(json(&attributes)) + .execute(db) + .await + .expect("seed the tables row"); + let mut tx = db.begin().await.expect("begin"); + PostgresEngine::create_data_table(&mut tx, id, key_schema, &attributes) + .await + .expect("create the data table"); + tx.commit().await.expect("commit"); + } + + /// The `indexes` row and the data table of GSI `id` on table `table_id`. + async fn index( + db: &PgPool, + table_id: &str, + base_key_schema: &[KeySchemaElement], + id: &str, + key_schema: &[KeySchemaElement], + ) { + sqlx::query( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ + projection) VALUES ($1, $2, $2, 'GSI', $3, '{\"ProjectionType\": \"ALL\"}')", + ) + .bind(table_id) + .bind(id) + .bind(json(&key_schema)) + .execute(db) + .await + .expect("seed the indexes row"); + let mut tx = db.begin().await.expect("begin"); + PostgresEngine::create_index_data_table( + &mut tx, + id, + key_schema, + &string_attributes(key_schema), + base_key_schema, + &string_attributes(base_key_schema), + ) + .await + .expect("create the index data table"); + tx.commit().await.expect("commit"); + } + + /// Insert rows into `_ddb_` one at a time, in the order given, which + /// is their heap order in a new table. + async fn insert(db: &PgPool, id: &str, columns: &[&str], rows: &[Vec]) { + let names: Vec = columns.iter().map(|c| format!("\"{c}\"")).collect(); + let params: Vec = (1..=columns.len()).map(|i| format!("${i}")).collect(); + let sql = format!( + "INSERT INTO \"_ddb_{id}\" ({}, item_data) VALUES ({}, '{{}}')", + names.join(", "), + params.join(", ") + ); + for row in rows { + let mut q = sqlx::query(&sql); + for value in row { + q = q.bind(value); + } + q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); + } + } + + fn row(values: &[&str]) -> Vec { + values.iter().map(|v| (*v).to_owned()).collect() + } + + /// Every value of `col` in `_ddb_`, sorted. + async fn column(db: &PgPool, id: &str, col: &str) -> Vec { + let sql = format!("SELECT \"{col}\" FROM \"_ddb_{id}\""); + let mut values: Vec = sqlx::query_scalar(&sql) + .fetch_all(db) + .await + .unwrap_or_else(|e| panic!("{sql}: {e}")); + values.sort(); + values + } + + /// The escape of each legacy text, sorted: what 004 must leave. + fn escaped>(legacy: &[S]) -> Vec { + let mut values: Vec = legacy + .iter() + .map(|t| escape_control(t.as_ref()).into_owned()) + .collect(); + values.sort(); + values + } + + fn rebuilt>(legacy: &[S]) -> Vec { + let mut values: Vec = legacy + .iter() + .map(|t| reescape_legacy_composite(t.as_ref()).expect("a netstring")) + .collect(); + values.sort(); + values + } + + async fn migrate(db: &PgPool) { + run_data_code_migrations(db, db) + .await + .expect("004 completes"); + } + + #[tokio::test] + async fn rewrites_a_partition_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_a_partition_key_pair_longest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "tp", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["a\u{1}", "a\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tp", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "tp", "pk").await, escaped(&legacy)); + s.cleanup().await; + } + + #[tokio::test] + async fn rewrites_a_sort_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_a_sort_key_pair_longest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "ts", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["s\u{1}", "s\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|sk| row(&["p", sk])).collect(); + insert(&s.db, "ts", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "ts", "sk_s").await, escaped(&legacy)); + assert_eq!(column(&s.db, "ts", "pk").await, vec!["p", "p"]); + s.cleanup().await; + } + + #[tokio::test] + async fn rebuilds_a_composite_partition_key_pair_longest_first() { + if base_conn().is_none() { + skip("rebuilds_a_composite_partition_key_pair_longest_first"); + return; + } + let s = scratch().await; + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tc", &ks).await; + // h1 = "a\x01" and h1 = "a\x01\x02", h2 = "b": the first one's rebuilt + // text is the second one's legacy text. + let legacy = ["2:a\u{1},1:b,", "3:a\u{1}\u{2},1:b,"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tc", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + let expected = rebuilt(&legacy); + assert_eq!( + expected, + vec!["3:a\u{1}\u{2},1:b,", "4:a\u{1}\u{2}\u{2},1:b,"] + ); + assert_eq!(column(&s.db, "tc", "pk").await, expected); + s.cleanup().await; + } + + #[tokio::test] + async fn rewrites_an_index_base_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_an_index_base_key_pair_longest_first"); + return; + } + let s = scratch().await; + let base = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + table(&s.db, "tb", &base).await; + index(&s.db, "tb", &base, "ib", &[key("g", KeyType::Hash)]).await; + // Two base items with the same index key and base sort key. The base + // table's own pair is the partition key case above; it is left empty + // here so the index table is the one that is checked. + let legacy = ["p\u{1}", "p\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|p| row(&["g", p, "s"])).collect(); + insert(&s.db, "ib", &["pk", "base_pk", "base_sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "ib", "base_pk").await, escaped(&legacy)); + s.cleanup().await; + } + + /// More rows than one batch on both paths: a single-attribute column whose + /// one-statement rewrite fails, and a composite partition key column. The + /// pair of each table is three U+0001 long, so the rows between its two + /// lengths put the longer one in the first batch and the shorter one in the + /// second. Every final text is the escape of its legacy text; a row + /// rewritten twice would hold a longer one. + #[tokio::test] + async fn rewrites_each_row_once_across_batches() { + if base_conn().is_none() { + skip("rewrites_each_row_once_across_batches"); + return; + } + let fillers = 600; + assert!(fillers > BATCH); + let s = scratch().await; + + table( + &s.db, + "tf", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let short = "a\u{1}\u{1}\u{1}"; + let long = "a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2}"; + assert_eq!(escape_control(short), long); + let mut legacy = vec![short.to_owned()]; + legacy.extend((0..fillers).map(|i| format!("k\u{1}{i:04}"))); + legacy.push(long.to_owned()); + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tf", &["pk", "sk_s"], &rows).await; + + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tk", &ks).await; + let short = "4:a\u{1}\u{1}\u{1},1:b,"; + let long = "7:a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2},1:b,"; + assert_eq!(reescape_legacy_composite(short).as_deref(), Some(long)); + let mut composite = vec![short.to_owned()]; + composite.extend((0..fillers).map(|i| format!("5:k\u{1}{i:03},1:b,"))); + composite.push(long.to_owned()); + let rows: Vec> = composite.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tk", &["pk", "sk_s"], &rows).await; + + migrate(&s.db).await; + assert_eq!(column(&s.db, "tf", "pk").await, escaped(&legacy)); + assert_eq!(column(&s.db, "tk", "pk").await, rebuilt(&composite)); + s.cleanup().await; + } + + /// A pair whose byte order is the reverse of its length order: the escape + /// of `a\x01b` is `a\x01\x02b`, which sorts below it, so an order by the + /// text itself, highest first, would rewrite the shorter key first. + #[tokio::test] + async fn rewrites_a_pair_whose_byte_order_is_shortest_first() { + if base_conn().is_none() { + skip("rewrites_a_pair_whose_byte_order_is_shortest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "tv", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["a\u{1}b", "a\u{1}\u{2}b"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tv", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "tv", "pk").await, escaped(&legacy)); + s.cleanup().await; + } + + /// An error from a rewrite names the DynamoDB table of the physical table: + /// here a two-HASH table whose `pk` is not a netstring. + #[tokio::test] + async fn an_error_names_the_dynamodb_table() { + if base_conn().is_none() { + skip("an_error_names_the_dynamodb_table"); + return; + } + let s = scratch().await; + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tn", &ks).await; + insert(&s.db, "tn", &["pk", "sk_s"], &[row(&["x\u{1}", "s"])]).await; + let err = run_data_code_migrations(&s.db, &s.db) + .await + .expect_err("a composite key that is not a netstring"); + let OpError::Internal(text) = err else { + panic!("{err:?}"); + }; + assert!( + text.contains("_ddb_tn.pk (table \"tn\" of account 111122223333)"), + "{text}" + ); + s.cleanup().await; + } + + #[tokio::test] + async fn a_duplicate_that_remains_is_reported_with_its_key() { + if base_conn().is_none() { + skip("a_duplicate_that_remains_is_reported_with_its_key"); + return; + } + let s = scratch().await; + sqlx::raw_sql( + r#"CREATE TABLE "dup" (pk TEXT COLLATE "C" PRIMARY KEY); + INSERT INTO "dup" VALUES (E'x\x01'), (E'y\x01');"#, + ) + .execute(&s.db) + .await + .expect("seed"); + let mut tx = s.db.begin().await.expect("begin"); + // A rewrite that gives every row one text: the second update fails. + let err = rewrite_longest_first(&mut tx, "\"dup\"", "pk", "TRUE", "dup.pk (t)", |_| { + Ok("z\u{1}".to_owned()) + }) + .await + .expect_err("a duplicate"); + let OpError::Internal(text) = err else { + panic!("{err:?}"); + }; + assert!(text.starts_with("Re-encode dup.pk (t): "), "{text}"); + assert!( + text.contains("(DETAIL: \"Key (pk)=(z\\u{1}) already exists.\")"), + "{text}" + ); + tx.rollback().await.expect("rollback"); + s.cleanup().await; + } +} diff --git a/crates/storage-postgres/src/migrations.rs b/crates/storage-postgres/src/migrations.rs index f4e9c7fa2..35035ffbd 100755 --- a/crates/storage-postgres/src/migrations.rs +++ b/crates/storage-postgres/src/migrations.rs @@ -671,6 +671,19 @@ struct EscapeWork { /// `gsi_pending` only: recompute `worker_partition` after the re-encode /// (`migration_004_keys::recompute_worker_partitions`). recompute_worker_partition: bool, + /// The DynamoDB table (and index) the physical table holds, for errors. + ddb_name: Option, +} + +impl EscapeWork { + /// `.`, with the DynamoDB name when known: how errors name a + /// column. + fn column(&self, col: &str) -> String { + match &self.ddb_name { + Some(ddb) => format!("{}.{col} ({ddb})", self.table), + None => format!("{}.{col}", self.table), + } + } } /// A text key column and the rows of it that hold a composite partition key. @@ -741,6 +754,7 @@ async fn dynamic_table_work( text_columns, jsonb_columns, recompute_worker_partition: false, + ddb_name: None, })) } @@ -788,6 +802,7 @@ async fn fixed_table_work( .collect(), jsonb_columns, recompute_worker_partition: false, + ddb_name: None, })) } @@ -874,28 +889,67 @@ async fn escape_rows_in_table(pool: &PgPool, work: &EscapeWork) -> OpResult // Key text columns holding one attribute's text: TEXT has no escaping // layer, so a single SQL statement per column is exact. NULL columns never - // match (position() is NULL). Rows holding a composite key are rebuilt - // part by part instead, before any other column of the row changes. + // match (position() is NULL). The statement can fail on the primary key + // when two legacy keys differ only by a U+0002 after a U+0001, depending + // on the order it meets them (`migration_004_order`); it runs under a + // savepoint, and on a unique violation the column is rewritten again row + // by row, longest legacy text first. Rows holding a composite key are + // rebuilt part by part instead; the other columns of the row keep the + // replace(). for col in &work.text_columns { let TextKeyColumn { name, composite_rows, } = col; + let what = work.column(name); + let single_rows = format!("NOT ({composite_rows})"); let sql = format!( "UPDATE {quoted} SET \"{name}\" = replace(\"{name}\", chr(1), chr(1) || chr(2)) \ - WHERE position(chr(1) IN \"{name}\") > 0 AND NOT ({composite_rows})" + WHERE position(chr(1) IN \"{name}\") > 0 AND {single_rows}" ); - let done = sqlx::query(&sql) + sqlx::query("SAVEPOINT escape_column") .execute(&mut *tx) .await - .map_err(|e| OpError::Internal(format!("Re-encode {}.{name}: {e}", work.table)))?; - rewritten += done.rows_affected(); + .map_err(|e| OpError::Internal(format!("Savepoint before {what}: {e}")))?; + match sqlx::query(&sql).execute(&mut *tx).await { + Ok(done) => { + sqlx::query("RELEASE SAVEPOINT escape_column") + .execute(&mut *tx) + .await + .map_err(|e| OpError::Internal(format!("Release savepoint of {what}: {e}")))?; + rewritten += done.rows_affected(); + } + Err(e) if crate::pg_util::is_unique_violation(&e) => { + sqlx::query("ROLLBACK TO SAVEPOINT escape_column") + .execute(&mut *tx) + .await + .map_err(|e| OpError::Internal(format!("Roll back {what}: {e}")))?; + // Legacy text holds no U+0000, so the escape is the replace() + // above. + rewritten += crate::migration_004_order::rewrite_longest_first( + &mut tx, + "ed, + name, + &single_rows, + &what, + |legacy| Ok(extenddb_storage::util::escape_control(legacy).into_owned()), + ) + .await?; + } + Err(e) => { + return Err(OpError::Internal(format!( + "Re-encode {what}: {}", + crate::migration_004_order::with_detail(&e) + ))); + } + } if composite_rows != "FALSE" { rewritten += crate::migration_004_keys::rebuild_composite_rows( &mut tx, "ed, name, composite_rows, + &what, ) .await?; } @@ -975,28 +1029,42 @@ async fn escape_legacy_control_chars(catalog_pool: &PgPool, data_pool: &PgPool) // table or index with such a key schema, and `base_pk` of the index and // vector tables of a table with one. use crate::migration_004_keys::has_composite_partition_key as composite; - let tables: Vec<(String, serde_json::Value)> = - sqlx::query_as("SELECT table_id, key_schema FROM tables ORDER BY table_id") - .fetch_all(catalog_pool) - .await - .map_err(|e| OpError::Internal(format!("Enumerate tables: {e}")))?; + let tables: Vec<(String, String, String, serde_json::Value)> = sqlx::query_as( + "SELECT table_id, table_name, account_id, key_schema FROM tables ORDER BY table_id", + ) + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate tables: {e}")))?; let composite_tables: std::collections::HashSet<&str> = tables .iter() - .filter(|(_, ks)| composite(ks)) - .map(|(id, _)| id.as_str()) + .filter(|(_, _, _, ks)| composite(ks)) + .map(|(id, _, _, _)| id.as_str()) + .collect(); + // How errors name the DynamoDB table of a physical table. + let ddb_tables: std::collections::HashMap<&str, String> = tables + .iter() + .map(|(id, name, account, _)| (id.as_str(), format!("table {name:?} of account {account}"))) .collect(); - for (id, ks) in &tables { + let ddb_table = |table_id: &str| { + ddb_tables + .get(table_id) + .cloned() + .unwrap_or_else(|| format!("table id {table_id}")) + }; + for (id, _, _, ks) in &tables { let cols: &[&str] = if composite(ks) { &["pk"] } else { &[] }; - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), cols).await? { + if let Some(mut w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), cols).await? { + w.ddb_name = Some(ddb_table(id)); work.push((data_pool, w)); } } - let indexes: Vec<(String, String, serde_json::Value)> = - sqlx::query_as("SELECT index_id, table_id, key_schema FROM indexes ORDER BY index_id") - .fetch_all(catalog_pool) - .await - .map_err(|e| OpError::Internal(format!("Enumerate indexes: {e}")))?; - for (id, table_id, ks) in &indexes { + let indexes: Vec<(String, String, String, serde_json::Value)> = sqlx::query_as( + "SELECT index_id, table_id, index_name, key_schema FROM indexes ORDER BY index_id", + ) + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate indexes: {e}")))?; + for (id, table_id, name, ks) in &indexes { let mut cols: Vec<&str> = Vec::new(); if composite(ks) { cols.push("pk"); @@ -1004,22 +1072,25 @@ async fn escape_legacy_control_chars(catalog_pool: &PgPool, data_pool: &PgPool) if composite_tables.contains(table_id.as_str()) { cols.push("base_pk"); } - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), &cols).await? { + if let Some(mut w) = dynamic_table_work(data_pool, format!("_ddb_{id}"), &cols).await? { + w.ddb_name = Some(format!("index {name:?} of {}", ddb_table(table_id))); work.push((data_pool, w)); } } - let vectors: Vec<(String, String)> = - sqlx::query_as("SELECT index_id, table_id FROM vector_indexes ORDER BY index_id") - .fetch_all(catalog_pool) - .await - .map_err(|e| OpError::Internal(format!("Enumerate vector indexes: {e}")))?; - for (id, table_id) in &vectors { + let vectors: Vec<(String, String, String)> = sqlx::query_as( + "SELECT index_id, table_id, index_name FROM vector_indexes ORDER BY index_id", + ) + .fetch_all(catalog_pool) + .await + .map_err(|e| OpError::Internal(format!("Enumerate vector indexes: {e}")))?; + for (id, table_id, name) in &vectors { let cols: &[&str] = if composite_tables.contains(table_id.as_str()) { &["base_pk"] } else { &[] }; - if let Some(w) = dynamic_table_work(data_pool, format!("_ddb_vec_{id}"), cols).await? { + if let Some(mut w) = dynamic_table_work(data_pool, format!("_ddb_vec_{id}"), cols).await? { + w.ddb_name = Some(format!("vector index {name:?} of {}", ddb_table(table_id))); work.push((data_pool, w)); } } From a620d856757eb99c7d3f3aef880db02c403d998c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:34:05 +0000 Subject: [PATCH 09/30] fix(storage-postgres): re-encode legacy strings in catalog migration 6 Main replaced the per-backend upgrade mechanisms with the shared migration runner (#666, #681). The merge drops this branch's data migration 004_escape_control_chars, catalog 0.0.5, the server's startup check for 004 and the migrate command's exclusive-access step; this commit gives the re-encode its place in the runner as migration 6, escape_control_chars. - The registry carries migration 6. PostgreSQL applies it with two code bodies: the catalog body rewrites backup_items, and the data body rewrites the data, index and vector index tables, gsi_pending (recomputing worker_partition) and stream_records. The rewrites are those of 004: the part by part rebuild of composite partition keys, the longest first rewrite after a unique violation, and the jsonb re-encode. SQLite, Cassandra and MongoDB record the migration as not applicable. - Each body runs in the runner's transaction and commits with its ledger row, so the per-table progress table is gone: a run that stops leaves the store as it was, and a recorded store is not rewritten again. The migration is breaking and not convergent, so an earlier binary refuses the migrated catalog and --reconverge skips it. - A server refuses a store where migration 6 is pending, which replaces the startup check for 004, and init applies it to a new store, which has nothing to rewrite. - The check for other sessions moves to each body's detect, which the runner calls before a run's first write. It leaves out the runner's sessions, the migration lock's session and status sessions by their application_name, which the runner sets over any name in the connection string, so the migrate command's own naming helper goes away. It runs in a migrating run only, not in a status read, so the preview still runs beside a server, and only while the store holds something to rewrite. EXTENDDB_MIGRATE_IGNORE_CONNECTIONS still skips it. A test harness whose own sessions hold its scratch databases builds its target with with_other_sessions_allowed. The live tests of 004 now run the bodies' rewrites. A golden test runs migration 6 on the 0.1.14 fixture after giving its rows legacy strings, and a runner test checks that a session on the data database stops the run with exit 5 before any write, and that the run completes once the session is gone, with connection strings that name an application. --- .../storage-cassandra/src/migrations/mod.rs | 4 + crates/storage-mongodb/src/migrations/mod.rs | 5 + crates/storage-postgres/src/data/key_text.rs | 2 +- crates/storage-postgres/src/gsi_queue.rs | 4 +- .../src/migration_004_keys.rs | 472 -------------- .../src/migration_004_order.rs | 513 ---------------- .../src/migrations/backend.rs | 5 + .../m0006_escape_control_chars/guard.rs | 131 ++++ .../m0006_escape_control_chars/keys.rs | 135 ++++ .../m0006_escape_control_chars/mod.rs | 578 ++++++++++++++++++ .../m0006_escape_control_chars/order.rs | 119 ++++ .../src/migrations/m0006_guard_tests.rs | 195 ++++++ .../src/migrations/m0006_keys_tests.rs | 332 ++++++++++ .../src/migrations/m0006_order_tests.rs | 389 ++++++++++++ .../src/migrations/m0006_tests.rs | 493 +++++++++++++++ crates/storage-postgres/src/migrations/mod.rs | 50 +- .../golden/0006_escape_control_chars.txt | 66 ++ .../tests/migrations_golden.rs | 216 ++++++- .../tests/migrations_support/mod.rs | 10 + crates/storage-sqlite/src/migrations/mod.rs | 4 + crates/storage/src/migrations/registry.rs | 4 + crates/storage/src/util/control_chars.rs | 5 +- docs/design/04-component-storage.md | 4 +- docs/getting-started.md | 6 +- docs/manuals/04-quickstart-setup-guide.md | 4 +- docs/manuals/07-upgrade-manual.md | 22 +- docs/manuals/08-install-linux.md | 2 +- docs/manuals/09-install-macos.md | 2 +- 28 files changed, 2768 insertions(+), 1004 deletions(-) delete mode 100644 crates/storage-postgres/src/migration_004_keys.rs delete mode 100644 crates/storage-postgres/src/migration_004_order.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_escape_control_chars/guard.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_escape_control_chars/keys.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_escape_control_chars/mod.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_escape_control_chars/order.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_guard_tests.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_keys_tests.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_order_tests.rs create mode 100644 crates/storage-postgres/src/migrations/m0006_tests.rs create mode 100644 crates/storage-postgres/tests/fixtures/golden/0006_escape_control_chars.txt diff --git a/crates/storage-cassandra/src/migrations/mod.rs b/crates/storage-cassandra/src/migrations/mod.rs index aae33b64f..44a8b2229 100644 --- a/crates/storage-cassandra/src/migrations/mod.rs +++ b/crates/storage-cassandra/src/migrations/mod.rs @@ -127,6 +127,10 @@ pub fn migration(id: MigrationId) -> Migration { "0005_drop_continuous_backups.cql" )], }, + MigrationId::EscapeControlChars => Migration::NotApplicable( + "Cassandra stores U+0000 in strings as written, so its stored form of strings does \ + not change", + ), } } diff --git a/crates/storage-mongodb/src/migrations/mod.rs b/crates/storage-mongodb/src/migrations/mod.rs index 9a3c88598..d5a41da40 100644 --- a/crates/storage-mongodb/src/migrations/mod.rs +++ b/crates/storage-mongodb/src/migrations/mod.rs @@ -137,6 +137,11 @@ pub fn migration(id: MigrationId) -> Migration { m0005_drop_continuous_backups::SOURCE, )], }, + MigrationId::EscapeControlChars => Migration::NotApplicable( + "string values already held U+0000; field names an earlier release stored are read \ + back as written unless they hold U+0001 followed by U+0001 or U+0002, and are not \ + rewritten (see the upgrade manual)", + ), } } diff --git a/crates/storage-postgres/src/data/key_text.rs b/crates/storage-postgres/src/data/key_text.rs index e58141d8b..3e5bfceac 100644 --- a/crates/storage-postgres/src/data/key_text.rs +++ b/crates/storage-postgres/src/data/key_text.rs @@ -70,7 +70,7 @@ pub(crate) fn composite_pk_to_text( /// is that of the escaped part. /// /// [`composite_pk_to_text`] builds every composite key column through this -/// function, and migration `004_escape_control_chars` rebuilds legacy +/// function, and catalog migration 6, `escape_control_chars`, rebuilds legacy /// composite key columns through it ([`reescape_legacy_composite`]). pub(crate) fn join_escaped_parts>(raw_parts: &[S]) -> String { let parts: Vec = raw_parts diff --git a/crates/storage-postgres/src/gsi_queue.rs b/crates/storage-postgres/src/gsi_queue.rs index 053cbb25d..435736bd8 100644 --- a/crates/storage-postgres/src/gsi_queue.rs +++ b/crates/storage-postgres/src/gsi_queue.rs @@ -170,8 +170,8 @@ pub(crate) fn partition_for(base_pk_text: &str) -> i32 { /// which `new_item` carries for puts and updates and `old_item` for deletes /// (the base key is immutable over an item's lifetime). The key text is the /// stored (escaped) form, so a key holding U+0001 hashes differently from the -/// raw text a build without the escape hashed; migration -/// `004_escape_control_chars` recomputes the column of such rows through this +/// raw text a build without the escape hashed; catalog migration 6, +/// `escape_control_chars`, recomputes the column of such rows through this /// function. pub(crate) fn worker_partition( old_item: Option<&Item>, diff --git a/crates/storage-postgres/src/migration_004_keys.rs b/crates/storage-postgres/src/migration_004_keys.rs deleted file mode 100644 index 3ed75d3fb..000000000 --- a/crates/storage-postgres/src/migration_004_keys.rs +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Two rewrites of `004_escape_control_chars` (`migrations.rs`) that cannot be -//! done by escaping a stored text where it lies, because the text is derived -//! from the key strings: -//! -//! - A partition key column of a key schema with more than one HASH attribute -//! holds the netstring join of the parts (`:,` each), and the -//! escape changes a part's length. [`rebuild_composite_rows`] splits each -//! legacy value, escapes the parts and joins them again with the new -//! lengths, through the function the write path uses -//! (`key_text::join_escaped_parts`). -//! - `gsi_pending.worker_partition` is a hash of the stored base key text -//! (`gsi_queue::partition_for`), so it changes with the key text. -//! [`recompute_worker_partitions`] recomputes it with the function the -//! enqueue uses (`gsi_queue::worker_partition`). -//! -//! Both run inside the per-table transaction of `escape_rows_in_table`, before -//! that table's progress marker commits. - -use extenddb_storage::management_store::{OpError, OpResult}; - -use crate::data::key_text::reescape_legacy_composite; -use crate::gsi_queue::{PendingApplyContext, worker_partition}; - -/// The `backup_items` rows whose `pk` holds a composite key: the rows of a -/// backup whose table's key schema has more than one HASH attribute. A boolean -/// SQL expression over a `backup_items` row; `backups` is in the same catalog -/// database. -pub(crate) const BACKUP_ITEMS_COMPOSITE_ROWS: &str = "backup_arn IN (\ - SELECT b.backup_arn FROM backups b WHERE (\ - SELECT COUNT(*) FROM jsonb_array_elements(b.key_schema) e \ - WHERE e->>'KeyType' = 'HASH') > 1)"; - -/// Whether a catalog key schema (`[{"AttributeName", "KeyType"}, ...]`) has -/// more than one HASH attribute, so its partition key column holds a netstring -/// join. -pub(crate) fn has_composite_partition_key(key_schema: &serde_json::Value) -> bool { - key_schema.as_array().is_some_and(|elements| { - elements - .iter() - .filter(|e| e.get("KeyType").and_then(serde_json::Value::as_str) == Some("HASH")) - .count() - > 1 - }) -} - -/// Rebuild the composite key text in `col` of the rows that `rows` (a boolean -/// SQL expression over the row) selects and that hold U+0001, one row at a -/// time, longest legacy text first and in batches -/// (`migration_004_order::rewrite_longest_first`). A SQL `replace()` over the -/// whole text would leave each length prefix counting the raw part -/// (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, where this build writes and -/// looks up `3:a\x01\x02,1:b,`). A value that is not a netstring fails the -/// migration, naming the table and column (`what`); the table's transaction -/// rolls back and nothing is marked. -pub(crate) async fn rebuild_composite_rows( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, - quoted_table: &str, - col: &str, - rows: &str, - what: &str, -) -> OpResult { - crate::migration_004_order::rewrite_longest_first(tx, quoted_table, col, rows, what, |legacy| { - reescape_legacy_composite(legacy).ok_or_else(|| { - OpError::Internal(format!( - "Re-encode {what}: the composite key {legacy:?} is not a netstring" - )) - }) - }) - .await -} - -/// The partition a row queued with these columns gets from this build's -/// enqueue, or `None` when a column does not decode (a worker handles such a -/// row as a poison row, whatever partition holds it). -fn current_partition( - old_item: Option, - new_item: Option, - index_context: serde_json::Value, -) -> Option { - let old_item = old_item.map(crate::data::json_to_item).transpose().ok()?; - let new_item = new_item.map(crate::data::json_to_item).transpose().ok()?; - let context: PendingApplyContext = crate::data::stored_json_to(index_context).ok()?; - worker_partition(old_item.as_ref(), new_item.as_ref(), &context).ok() -} - -/// Recompute `worker_partition` of the queued rows whose item holds U+0001, -/// after their jsonb columns were re-encoded in the same transaction. -/// -/// A build without the escape hashed the raw base key; this build hashes the -/// escaped one, so for a key holding U+0001 a row queued before the upgrade and -/// the next write of the same item would be claimed by different workers, in -/// either order, which breaks the queue's one item, one worker rule. Every row -/// of one item moves to the same new partition and keeps its `id` and -/// `ready_at`, so the item's rows are still claimed in write order, and a row -/// enqueued after the upgrade gets a `ready_at` no earlier than theirs from the -/// partition clamp in `enqueue_gsi_pending`. -pub(crate) async fn recompute_worker_partitions( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, -) -> OpResult { - type Row = ( - i64, - i32, - Option, - Option, - serde_json::Value, - ); - // '\u0001' is how jsonb::text renders U+0001; chr(92) spells the backslash - // as in `escape_jsonb_rows`. The base key is in new_item, or in old_item for - // a delete, as `worker_partition` reads it. - let rows: Vec = sqlx::query_as( - "SELECT id, worker_partition, old_item, new_item, index_context FROM gsi_pending \ - WHERE position((chr(92) || 'u0001') IN COALESCE(new_item, old_item)::text) > 0 \ - ORDER BY id FOR UPDATE", - ) - .fetch_all(&mut **tx) - .await - .map_err(|e| OpError::Internal(format!("Find gsi_pending rows to repartition: {e}")))?; - let mut changed: u64 = 0; - for (id, stored, old_item, new_item, index_context) in rows { - let Some(partition) = current_partition(old_item, new_item, index_context) else { - continue; - }; - if partition == stored { - continue; - } - sqlx::query("UPDATE gsi_pending SET worker_partition = $1 WHERE id = $2") - .bind(partition) - .bind(id) - .execute(&mut **tx) - .await - .map_err(|e| OpError::Internal(format!("Repartition gsi_pending row {id}: {e}")))?; - changed += 1; - } - Ok(changed) -} - -#[cfg(test)] -mod tests { - use super::has_composite_partition_key; - use serde_json::json; - - #[test] - fn only_a_key_schema_with_two_or_more_hash_attributes_is_composite() { - let one = json!([ - {"AttributeName": "pk", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"} - ]); - let two = json!([ - {"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"} - ]); - let ranges = json!([ - {"AttributeName": "h", "KeyType": "HASH"}, - {"AttributeName": "r1", "KeyType": "RANGE"}, - {"AttributeName": "r2", "KeyType": "RANGE"} - ]); - assert!(!has_composite_partition_key(&one)); - assert!(has_composite_partition_key(&two)); - assert!(!has_composite_partition_key(&ranges)); - assert!(!has_composite_partition_key(&json!({}))); - } -} - -#[cfg(test)] -mod live { - //! Live checks against a scratch database, with the helpers and the - //! skip convention of `migrations::live_reencode`: without - //! `EXTENDDB_TEST_PG_CONNECTION_STRING` every test reports a skip and - //! passes. Each seeds rows the way a build without the escape wrote them. - - use extenddb_core::types::{ - AttributeDefinition, AttributeValue, Item, KeySchemaElement, KeyType, Projection, - ProjectionType, ScalarAttributeType, - }; - use serde_json::json; - use sqlx::PgPool; - - use crate::data::key_text::composite_pk_to_text; - use crate::gsi_queue::{ - GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending, partition_for, - worker_partition, - }; - use crate::migrations::live_reencode::{base_conn, scratch, skip}; - use crate::migrations::run_data_code_migrations; - - fn element(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } - } - - fn text(v: &str) -> AttributeValue { - AttributeValue::S(v.to_owned()) - } - - async fn exec(db: &PgPool, sql: &str, binds: &[serde_json::Value]) { - let mut q = sqlx::query(sql); - for b in binds { - q = q.bind(b.clone()); - } - q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); - } - - async fn texts(db: &PgPool, sql: &str) -> Vec { - sqlx::query_scalar(sql) - .fetch_all(db) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) - } - - /// A table with two HASH attributes (`t2`), a two-HASH GSI on a one-HASH - /// table (`i2` on `t1`), a one-HASH GSI on `t2` (`i3`), and a backup of - /// each table, each holding a legacy row with a raw U+0001 in a HASH part. - async fn seed_composite(db: &PgPool) { - exec( - db, - "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'esc')", - &[], - ) - .await; - let one = json!([{"AttributeName": "pk", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"}]); - let two = json!([{"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"}]); - for (id, ks) in [("t1", &one), ("t2", &two)] { - exec( - db, - &format!( - "INSERT INTO tables (account_id, table_name, key_schema, \ - attribute_definitions, table_status, table_arn, table_id) \ - VALUES ('111122223333', '{id}', $1, '[]', 'ACTIVE', \ - 'arn:aws:dynamodb:us-east-1:111122223333:table/{id}', '{id}')" - ), - std::slice::from_ref(ks), - ) - .await; - } - for (table, index, ks) in [ - ( - "t1", - "i2", - json!([{"AttributeName": "g1", "KeyType": "HASH"}, - {"AttributeName": "g2", "KeyType": "HASH"}]), - ), - ( - "t2", - "i3", - json!([{"AttributeName": "g", "KeyType": "HASH"}]), - ), - ] { - exec( - db, - &format!( - "INSERT INTO indexes (table_id, index_id, index_name, index_type, \ - key_schema, projection) VALUES ('{table}', '{index}', '{index}', 'GSI', \ - $1, '{{\"ProjectionType\": \"ALL\"}}')" - ), - &[ks], - ) - .await; - } - sqlx::raw_sql( - r#"CREATE TABLE "_ddb_t2" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, sk_s)); - CREATE TABLE "_ddb_i2" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); - CREATE TABLE "_ddb_i3" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); - INSERT INTO "_ddb_t2" VALUES - (E'2:a\x01,1:b,', 's', - '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}, "sk": {"S": "s"}}'), - ('1:x,1:y,', 's', '{"h1": {"S": "x"}, "h2": {"S": "y"}, "sk": {"S": "s"}}'); - INSERT INTO "_ddb_i2" VALUES - (E'2:g\x01,1:h,', NULL, E'p\x01', E's\x01', - '{"g1": {"S": "g\u0001"}, "g2": {"S": "h"}, "pk": {"S": "p\u0001"}}'); - INSERT INTO "_ddb_i3" VALUES - (E'g\x01', NULL, E'2:a\x01,1:b,', 's', - '{"g": {"S": "g\u0001"}, "h1": {"S": "a\u0001"}, "h2": {"S": "b"}}'); - INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, - key_schema, attribute_definitions) VALUES - ('b1', 'b1', 't1', 't1', '111122223333', - '[{"AttributeName": "pk", "KeyType": "HASH"}]', '[]'), - ('b2', 'b2', 't2', 't2', '111122223333', - '[{"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}]', '[]'); - INSERT INTO backup_items (backup_arn, pk, sk, item_data) VALUES - ('b1', E'p\x01', NULL, '{"pk": {"S": "p\u0001"}}'), - ('b2', E'2:a\x01,1:b,', NULL, '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}}');"#, - ) - .execute(db) - .await - .expect("seed the legacy rows"); - } - - #[tokio::test] - async fn rebuilds_composite_partition_keys_part_by_part() { - if base_conn().is_none() { - skip("rebuilds_composite_partition_keys_part_by_part"); - return; - } - let s = scratch().await; - seed_composite(&s.db).await; - run_data_code_migrations(&s.db, &s.db) - .await - .expect("run the data code migrations"); - - // What this build writes and looks up for the legacy key - // h1 = "a\x01", h2 = "b": each part escaped, then joined. - let mut item = Item::new(); - item.insert("h1".to_owned(), text("a\u{1}")); - item.insert("h2".to_owned(), text("b")); - let ks = [element("h1", KeyType::Hash), element("h2", KeyType::Hash)]; - let expected = composite_pk_to_text(&item, &ks).expect("composite key text"); - assert_eq!(expected, "3:a\u{1}\u{2},1:b,"); - - // The table with two HASH attributes: the legacy row is rebuilt, the - // plain row keeps its text. - assert_eq!( - texts(&s.db, "SELECT pk FROM \"_ddb_t2\" ORDER BY pk").await, - vec!["1:x,1:y,".to_owned(), expected.clone()] - ); - // A two-HASH GSI: pk rebuilt, the one-HASH base key replaced. - let row: (String, String, String) = - sqlx::query_as("SELECT pk, base_pk, base_sk_s FROM \"_ddb_i2\"") - .fetch_one(&s.db) - .await - .expect("read _ddb_i2"); - assert_eq!( - row, - ( - "3:g\u{1}\u{2},1:h,".to_owned(), - "p\u{1}\u{2}".to_owned(), - "s\u{1}\u{2}".to_owned() - ) - ); - // A one-HASH GSI on the two-HASH table: pk replaced, base_pk rebuilt. - let row: (String, String) = sqlx::query_as("SELECT pk, base_pk FROM \"_ddb_i3\"") - .fetch_one(&s.db) - .await - .expect("read _ddb_i3"); - assert_eq!(row, ("g\u{1}\u{2}".to_owned(), expected.clone())); - // backup_items: the backup of the two-HASH table is rebuilt, the - // other replaced. - assert_eq!( - texts(&s.db, "SELECT pk FROM backup_items ORDER BY backup_arn").await, - vec!["p\u{1}\u{2}".to_owned(), expected] - ); - s.cleanup().await; - } - - fn context() -> PendingApplyContext { - PendingApplyContext::Gsi(GsiApplyContext { - base_key_schema: vec![element("pk", KeyType::Hash)], - attribute_definitions: vec![AttributeDefinition { - attribute_name: "pk".to_owned(), - attribute_type: ScalarAttributeType::S, - }], - index: GsiIndexDef { - index_id: "i1".to_owned(), - key_schema: vec![element("g", KeyType::Hash)], - projection: Projection { - projection_type: ProjectionType::All, - non_key_attributes: None, - }, - }, - }) - } - - /// The partition a build without the escape gave a row for `item`: the - /// hash of the raw key text. - fn legacy_partition(item: &Item) -> i32 { - let raw = - extenddb_storage::util::composite_pk_to_text(item, &[element("pk", KeyType::Hash)]) - .expect("raw key text"); - partition_for(&raw) - } - - #[tokio::test] - async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { - if base_conn().is_none() { - skip("recomputes_the_worker_partition_of_rows_queued_before_the_upgrade"); - return; - } - let ctx = context(); - // A key holding U+0001 whose raw and escaped texts hash to different - // workers, so the test sees the move. - let item = [ - "a\u{1}b", - "b\u{1}", - "\u{1}c", - "key\u{1}1", - "key\u{1}2", - "key\u{1}3", - ] - .into_iter() - .map(|k| { - let mut item = Item::new(); - item.insert("pk".to_owned(), text(k)); - item.insert("g".to_owned(), text("v")); - item - }) - .find(|item| { - legacy_partition(item) != worker_partition(None, Some(item), &ctx).expect("partition") - }) - .expect("a key whose partition moves"); - let current = worker_partition(None, Some(&item), &ctx).expect("partition"); - let legacy = legacy_partition(&item); - - // A key without U+0001 and a non-key string with it: same text both ways. - let mut plain = Item::new(); - plain.insert("pk".to_owned(), text("plain")); - plain.insert("note".to_owned(), text("n\u{1}")); - let plain_partition = legacy_partition(&plain); - - let s = scratch().await; - let raw_ctx = serde_json::to_value(&ctx).expect("context json"); - let raw = |i: &Item| serde_json::to_value(i).expect("item json"); - for (old_item, new_item, partition) in [ - (None, Some(raw(&item)), legacy), - (Some(raw(&item)), None, legacy), - (None, Some(raw(&plain)), plain_partition), - ] { - sqlx::query( - "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ - index_context) VALUES ('t1', $1, $2, $3, $4)", - ) - .bind(partition) - .bind(old_item) - .bind(new_item) - .bind(&raw_ctx) - .execute(&s.db) - .await - .expect("seed a queued row"); - } - - run_data_code_migrations(&s.db, &s.db) - .await - .expect("run the data code migrations"); - - let partitions: Vec = - sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id") - .fetch_all(&s.db) - .await - .expect("read gsi_pending"); - assert_eq!(partitions, vec![current, current, plain_partition]); - - // The next write of the item is queued on the same worker. - let mut tx = s.db.begin().await.expect("begin"); - enqueue_gsi_pending(&mut tx, "t1", None, Some(&item), 1, &ctx) - .await - .expect("enqueue the next write"); - tx.commit().await.expect("commit"); - let next: i32 = - sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id DESC LIMIT 1") - .fetch_one(&s.db) - .await - .expect("read the new row"); - assert_eq!(next, current); - s.cleanup().await; - } -} diff --git a/crates/storage-postgres/src/migration_004_order.rs b/crates/storage-postgres/src/migration_004_order.rs deleted file mode 100644 index fd5bb8070..000000000 --- a/crates/storage-postgres/src/migration_004_order.rs +++ /dev/null @@ -1,513 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Row-by-row rewrites of one key column for `004_escape_control_chars` -//! (`migrations.rs`), in an order that keeps the table's primary key valid -//! after every row. -//! -//! `PostgreSQL` checks a primary key as each row changes, not at the end of the -//! statement. Two legacy keys that differ only by a U+0002 after a U+0001, such -//! as `a\x01` and `a\x01\x02` with the same other key columns, escape to two -//! different texts, `a\x01\x02` and `a\x01\x02\x02`, but the first one's new -//! text is the second one's legacy text. If the shorter one is rewritten first, -//! the table holds `a\x01\x02` twice until the longer one is rewritten, and the -//! update fails with SQLSTATE 23505. A one-statement `UPDATE` meets the two rows -//! in heap order, so whether it fails depends on where they are stored. -//! -//! [`rewrite_longest_first`] rewrites the rows in descending byte length of -//! their legacy text, which never produces such a duplicate: -//! -//! - Every rewrite makes the text longer. Every row it rewrites holds a U+0001, -//! and the escape adds one byte for each; a rebuilt composite key also gives -//! each part its new length, which never takes fewer digits than the old one. -//! - Suppose rewriting row `r` gives the text that row `s` holds, and the two -//! rows agree on the other key columns. If `s` has not been rewritten yet, it -//! holds its legacy text, and that text is the new text of `r`, so it is -//! longer than the legacy text of `r` and `s` was rewritten earlier. If `s` -//! has been rewritten, the two rows have the same new text, and since the -//! escape is injective their legacy texts were equal. -//! - Each other key column holds the legacy texts of every row, or, when an -//! earlier pass of the same transaction rewrote it, their escapes. Either -//! way two rows agree on it now exactly when they agreed before the -//! migration. Two rows that agreed on every key column before the migration -//! would have broken the primary key, so no rewrite meets a duplicate. - -use extenddb_storage::management_store::{OpError, OpResult}; - -/// Rows read from the cursor per round trip, the batch `escape_jsonb_rows` -/// fetches. -pub(crate) const BATCH: usize = 500; - -/// The cursor [`rewrite_longest_first`] declares and closes before returning. -const CURSOR: &str = "escape_004_longest_first"; - -/// Rewrite `col` of the rows that hold U+0001 and that `rows` (a boolean SQL -/// expression over the row) selects, one row at a time, longest legacy text -/// first; `rewrite` gives a row's new text from its legacy text. Runs inside -/// the caller's per-table transaction and returns the number of rows changed. -/// `what` names the column in errors, with the DynamoDB table when the caller -/// knows it. -/// -/// One cursor is declared over the matching rows in that order and read -/// [`BATCH`] rows at a time, so this process holds one batch, and `PostgreSQL` -/// sorts the matching rows in `work_mem`, spilling to temporary files beyond -/// it. The cursor's rows are fixed when it is declared and each is returned -/// once, so no row is rewritten twice. Each row is locked as the cursor -/// returns it, as the single-statement path locks the rows it updates. -pub(crate) async fn rewrite_longest_first( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, - quoted_table: &str, - col: &str, - rows: &str, - what: &str, - rewrite: impl Fn(&str) -> OpResult, -) -> OpResult { - let failed = |step: &str, e: &sqlx::Error| { - OpError::Internal(format!("{step} {what}: {}", with_detail(e))) - }; - sqlx::query(&format!( - "DECLARE {CURSOR} NO SCROLL CURSOR FOR \ - SELECT ctid::text, \"{col}\" FROM {quoted_table} \ - WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) \ - ORDER BY octet_length(\"{col}\") DESC FOR UPDATE" - )) - .execute(&mut **tx) - .await - .map_err(|e| failed("Find the rows to rewrite in", &e))?; - let fetch = format!("FETCH {BATCH} FROM {CURSOR}"); - let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); - let mut changed: u64 = 0; - loop { - let batch: Vec<(String, String)> = sqlx::query_as(&fetch) - .fetch_all(&mut **tx) - .await - .map_err(|e| failed("Read the rows to rewrite in", &e))?; - for (ctid, legacy) in &batch { - let done = sqlx::query(&update) - .bind(rewrite(legacy)?) - .bind(ctid) - .execute(&mut **tx) - .await - .map_err(|e| failed("Re-encode", &e))?; - changed += done.rows_affected(); - } - if batch.len() < BATCH { - break; - } - } - sqlx::query(&format!("CLOSE {CURSOR}")) - .execute(&mut **tx) - .await - .map_err(|e| failed("Close the cursor over", &e))?; - Ok(changed) -} - -/// A database error as text, with `PostgreSQL`'s DETAIL when the error has one; -/// for a unique violation the DETAIL names the key already present. sqlx's -/// `Display` writes the message alone. The DETAIL is quoted with its control -/// characters escaped, since the keys this migration rewrites hold them. -pub(crate) fn with_detail(e: &sqlx::Error) -> String { - let detail = match e { - sqlx::Error::Database(db) => db - .try_downcast_ref::() - .and_then(sqlx::postgres::PgDatabaseError::detail), - _ => None, - }; - match detail { - Some(detail) => format!("{e} (DETAIL: {detail:?})"), - None => e.to_string(), - } -} - -#[cfg(test)] -mod live { - //! Live checks with the scratch database and the skip convention of - //! `migrations::live_reencode`. The tables are created by the DDL - //! `CreateTable` runs, so their primary keys are the production ones. Each - //! test stores legacy keys that differ only by a U+0002 after a U+0001, - //! the shorter one first in the heap, the order a one-statement rewrite - //! fails on. `item_data` is `{}`: the tests check the key columns. - - use extenddb_core::types::{ - AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType, - }; - use extenddb_storage::management_store::OpError; - use extenddb_storage::util::escape_control; - use sqlx::PgPool; - - use super::{BATCH, rewrite_longest_first}; - use crate::PostgresEngine; - use crate::data::key_text::reescape_legacy_composite; - use crate::migrations::live_reencode::{base_conn, scratch, skip}; - use crate::migrations::run_data_code_migrations; - - fn key(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } - } - - fn string_attributes(key_schema: &[KeySchemaElement]) -> Vec { - key_schema - .iter() - .map(|k| AttributeDefinition { - attribute_name: k.attribute_name.clone(), - attribute_type: ScalarAttributeType::S, - }) - .collect() - } - - fn json(value: &T) -> serde_json::Value { - serde_json::to_value(value).expect("json") - } - - /// The account, the `tables` row and the data table of table `id`. - async fn table(db: &PgPool, id: &str, key_schema: &[KeySchemaElement]) { - let attributes = string_attributes(key_schema); - sqlx::query( - "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'order') \ - ON CONFLICT DO NOTHING", - ) - .execute(db) - .await - .expect("seed the account"); - sqlx::query( - "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ - table_status, table_arn, table_id) VALUES ('111122223333', $1, $2, $3, 'ACTIVE', \ - 'arn:aws:dynamodb:us-east-1:111122223333:table/' || $1, $1)", - ) - .bind(id) - .bind(json(&key_schema)) - .bind(json(&attributes)) - .execute(db) - .await - .expect("seed the tables row"); - let mut tx = db.begin().await.expect("begin"); - PostgresEngine::create_data_table(&mut tx, id, key_schema, &attributes) - .await - .expect("create the data table"); - tx.commit().await.expect("commit"); - } - - /// The `indexes` row and the data table of GSI `id` on table `table_id`. - async fn index( - db: &PgPool, - table_id: &str, - base_key_schema: &[KeySchemaElement], - id: &str, - key_schema: &[KeySchemaElement], - ) { - sqlx::query( - "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ - projection) VALUES ($1, $2, $2, 'GSI', $3, '{\"ProjectionType\": \"ALL\"}')", - ) - .bind(table_id) - .bind(id) - .bind(json(&key_schema)) - .execute(db) - .await - .expect("seed the indexes row"); - let mut tx = db.begin().await.expect("begin"); - PostgresEngine::create_index_data_table( - &mut tx, - id, - key_schema, - &string_attributes(key_schema), - base_key_schema, - &string_attributes(base_key_schema), - ) - .await - .expect("create the index data table"); - tx.commit().await.expect("commit"); - } - - /// Insert rows into `_ddb_` one at a time, in the order given, which - /// is their heap order in a new table. - async fn insert(db: &PgPool, id: &str, columns: &[&str], rows: &[Vec]) { - let names: Vec = columns.iter().map(|c| format!("\"{c}\"")).collect(); - let params: Vec = (1..=columns.len()).map(|i| format!("${i}")).collect(); - let sql = format!( - "INSERT INTO \"_ddb_{id}\" ({}, item_data) VALUES ({}, '{{}}')", - names.join(", "), - params.join(", ") - ); - for row in rows { - let mut q = sqlx::query(&sql); - for value in row { - q = q.bind(value); - } - q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); - } - } - - fn row(values: &[&str]) -> Vec { - values.iter().map(|v| (*v).to_owned()).collect() - } - - /// Every value of `col` in `_ddb_`, sorted. - async fn column(db: &PgPool, id: &str, col: &str) -> Vec { - let sql = format!("SELECT \"{col}\" FROM \"_ddb_{id}\""); - let mut values: Vec = sqlx::query_scalar(&sql) - .fetch_all(db) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")); - values.sort(); - values - } - - /// The escape of each legacy text, sorted: what 004 must leave. - fn escaped>(legacy: &[S]) -> Vec { - let mut values: Vec = legacy - .iter() - .map(|t| escape_control(t.as_ref()).into_owned()) - .collect(); - values.sort(); - values - } - - fn rebuilt>(legacy: &[S]) -> Vec { - let mut values: Vec = legacy - .iter() - .map(|t| reescape_legacy_composite(t.as_ref()).expect("a netstring")) - .collect(); - values.sort(); - values - } - - async fn migrate(db: &PgPool) { - run_data_code_migrations(db, db) - .await - .expect("004 completes"); - } - - #[tokio::test] - async fn rewrites_a_partition_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_a_partition_key_pair_longest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "tp", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["a\u{1}", "a\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tp", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "tp", "pk").await, escaped(&legacy)); - s.cleanup().await; - } - - #[tokio::test] - async fn rewrites_a_sort_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_a_sort_key_pair_longest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "ts", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["s\u{1}", "s\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|sk| row(&["p", sk])).collect(); - insert(&s.db, "ts", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "ts", "sk_s").await, escaped(&legacy)); - assert_eq!(column(&s.db, "ts", "pk").await, vec!["p", "p"]); - s.cleanup().await; - } - - #[tokio::test] - async fn rebuilds_a_composite_partition_key_pair_longest_first() { - if base_conn().is_none() { - skip("rebuilds_a_composite_partition_key_pair_longest_first"); - return; - } - let s = scratch().await; - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tc", &ks).await; - // h1 = "a\x01" and h1 = "a\x01\x02", h2 = "b": the first one's rebuilt - // text is the second one's legacy text. - let legacy = ["2:a\u{1},1:b,", "3:a\u{1}\u{2},1:b,"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tc", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - let expected = rebuilt(&legacy); - assert_eq!( - expected, - vec!["3:a\u{1}\u{2},1:b,", "4:a\u{1}\u{2}\u{2},1:b,"] - ); - assert_eq!(column(&s.db, "tc", "pk").await, expected); - s.cleanup().await; - } - - #[tokio::test] - async fn rewrites_an_index_base_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_an_index_base_key_pair_longest_first"); - return; - } - let s = scratch().await; - let base = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; - table(&s.db, "tb", &base).await; - index(&s.db, "tb", &base, "ib", &[key("g", KeyType::Hash)]).await; - // Two base items with the same index key and base sort key. The base - // table's own pair is the partition key case above; it is left empty - // here so the index table is the one that is checked. - let legacy = ["p\u{1}", "p\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|p| row(&["g", p, "s"])).collect(); - insert(&s.db, "ib", &["pk", "base_pk", "base_sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "ib", "base_pk").await, escaped(&legacy)); - s.cleanup().await; - } - - /// More rows than one batch on both paths: a single-attribute column whose - /// one-statement rewrite fails, and a composite partition key column. The - /// pair of each table is three U+0001 long, so the rows between its two - /// lengths put the longer one in the first batch and the shorter one in the - /// second. Every final text is the escape of its legacy text; a row - /// rewritten twice would hold a longer one. - #[tokio::test] - async fn rewrites_each_row_once_across_batches() { - if base_conn().is_none() { - skip("rewrites_each_row_once_across_batches"); - return; - } - let fillers = 600; - assert!(fillers > BATCH); - let s = scratch().await; - - table( - &s.db, - "tf", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let short = "a\u{1}\u{1}\u{1}"; - let long = "a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2}"; - assert_eq!(escape_control(short), long); - let mut legacy = vec![short.to_owned()]; - legacy.extend((0..fillers).map(|i| format!("k\u{1}{i:04}"))); - legacy.push(long.to_owned()); - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tf", &["pk", "sk_s"], &rows).await; - - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tk", &ks).await; - let short = "4:a\u{1}\u{1}\u{1},1:b,"; - let long = "7:a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2},1:b,"; - assert_eq!(reescape_legacy_composite(short).as_deref(), Some(long)); - let mut composite = vec![short.to_owned()]; - composite.extend((0..fillers).map(|i| format!("5:k\u{1}{i:03},1:b,"))); - composite.push(long.to_owned()); - let rows: Vec> = composite.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tk", &["pk", "sk_s"], &rows).await; - - migrate(&s.db).await; - assert_eq!(column(&s.db, "tf", "pk").await, escaped(&legacy)); - assert_eq!(column(&s.db, "tk", "pk").await, rebuilt(&composite)); - s.cleanup().await; - } - - /// A pair whose byte order is the reverse of its length order: the escape - /// of `a\x01b` is `a\x01\x02b`, which sorts below it, so an order by the - /// text itself, highest first, would rewrite the shorter key first. - #[tokio::test] - async fn rewrites_a_pair_whose_byte_order_is_shortest_first() { - if base_conn().is_none() { - skip("rewrites_a_pair_whose_byte_order_is_shortest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "tv", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["a\u{1}b", "a\u{1}\u{2}b"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tv", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "tv", "pk").await, escaped(&legacy)); - s.cleanup().await; - } - - /// An error from a rewrite names the DynamoDB table of the physical table: - /// here a two-HASH table whose `pk` is not a netstring. - #[tokio::test] - async fn an_error_names_the_dynamodb_table() { - if base_conn().is_none() { - skip("an_error_names_the_dynamodb_table"); - return; - } - let s = scratch().await; - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tn", &ks).await; - insert(&s.db, "tn", &["pk", "sk_s"], &[row(&["x\u{1}", "s"])]).await; - let err = run_data_code_migrations(&s.db, &s.db) - .await - .expect_err("a composite key that is not a netstring"); - let OpError::Internal(text) = err else { - panic!("{err:?}"); - }; - assert!( - text.contains("_ddb_tn.pk (table \"tn\" of account 111122223333)"), - "{text}" - ); - s.cleanup().await; - } - - #[tokio::test] - async fn a_duplicate_that_remains_is_reported_with_its_key() { - if base_conn().is_none() { - skip("a_duplicate_that_remains_is_reported_with_its_key"); - return; - } - let s = scratch().await; - sqlx::raw_sql( - r#"CREATE TABLE "dup" (pk TEXT COLLATE "C" PRIMARY KEY); - INSERT INTO "dup" VALUES (E'x\x01'), (E'y\x01');"#, - ) - .execute(&s.db) - .await - .expect("seed"); - let mut tx = s.db.begin().await.expect("begin"); - // A rewrite that gives every row one text: the second update fails. - let err = rewrite_longest_first(&mut tx, "\"dup\"", "pk", "TRUE", "dup.pk (t)", |_| { - Ok("z\u{1}".to_owned()) - }) - .await - .expect_err("a duplicate"); - let OpError::Internal(text) = err else { - panic!("{err:?}"); - }; - assert!(text.starts_with("Re-encode dup.pk (t): "), "{text}"); - assert!( - text.contains("(DETAIL: \"Key (pk)=(z\\u{1}) already exists.\")"), - "{text}" - ); - tx.rollback().await.expect("rollback"); - s.cleanup().await; - } -} diff --git a/crates/storage-postgres/src/migrations/backend.rs b/crates/storage-postgres/src/migrations/backend.rs index 2924fa23f..412945dbc 100644 --- a/crates/storage-postgres/src/migrations/backend.rs +++ b/crates/storage-postgres/src/migrations/backend.rs @@ -57,6 +57,10 @@ pub struct PostgresStores { lock: Option, /// The `application_name` of this runner's sessions. pub(crate) application: String, + /// Whether migration 6's `detect` looks for other sessions: in a run, not + /// in a status read, and not for a target that allows them + /// ([`PostgresTarget::with_other_sessions_allowed`]). + pub(crate) checks_sessions: bool, } impl PostgresStores { @@ -277,6 +281,7 @@ impl PostgresMigrations { data_watch, lock, application, + checks_sessions: !read_only && !target.other_sessions_allowed, }, catalog_name, data_name, diff --git a/crates/storage-postgres/src/migrations/m0006_escape_control_chars/guard.rs b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/guard.rs new file mode 100644 index 000000000..a7a956638 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/guard.rs @@ -0,0 +1,131 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The sessions check of migration 6's `detect`: the run stops, before its +//! first write, while another session holds a database a body rewrites. +//! +//! The bodies rewrite rows in place and cannot tell a row a running server +//! writes from a legacy row: a server of an earlier release still writing +//! leaves rows in the earlier encoding behind it. `migrate --yes` waits for +//! the servers of releases that take the serving key, and the upgrade manual +//! says to stop every server first; this check finds a server of an earlier +//! release, or any other client, that was not stopped. The runner's own +//! sessions, the migration lock's session and read-only status sessions are +//! left out by `application_name`. A store with nothing to rewrite (no +//! table, no backup, no queued or stream row), such as the one `init` +//! creates, needs no check. Setting [`IGNORE_CONNECTIONS_ENV`] skips the +//! check, for a database whose only other sessions are idle connections a +//! connection pooler holds. +//! +//! The migrator connects as the application role, which is not a superuser. +//! For sessions of other roles PostgreSQL then shows `datname`, `usename` +//! and `application_name` but hides `backend_type` and `client_addr`, so a +//! filter on `backend_type` alone would miss an operator's `psql` or a server +//! running as another role. A session is counted when it has a role +//! (`usename`), which background workers such as autovacuum never have, and +//! its type is `client backend` or hidden. + +use extenddb_storage::migrations::MigrationError; +use sqlx::PgPool; + +use super::super::connect::{RUNNER_APPLICATION_PREFIX, STATUS_APPLICATION}; +use super::db_error; + +/// Skips the check when set, to any value. +pub(crate) const IGNORE_CONNECTIONS_ENV: &str = "EXTENDDB_MIGRATE_IGNORE_CONNECTIONS"; + +/// `application_name` of the migration lock's session (`locks.rs`). +const LOCK_APPLICATION: &str = "extenddb migrate"; + +/// Whether the public schema of the database `pool` reaches has `table` and +/// the table holds a row. +async fn has_row(pool: &PgPool, table: &str) -> Result { + let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL") + .bind(format!("public.{table}")) + .fetch_one(pool) + .await + .map_err(|e| db_error(&format!("look for {table}"), &e))?; + if !exists { + return Ok(false); + } + sqlx::query_scalar(&format!("SELECT EXISTS (SELECT 1 FROM {table})")) + .fetch_one(pool) + .await + .map_err(|e| db_error(&format!("read {table}"), &e)) +} + +/// Whether the catalog body has rows to rewrite: `backup_items` holds one. +pub(crate) async fn catalog_has_rows(catalog: &PgPool) -> Result { + if std::env::var_os(IGNORE_CONNECTIONS_ENV).is_some() { + return Ok(false); + } + has_row(catalog, "backup_items").await +} + +/// Whether the data body may have rows to rewrite: the catalog lists a table, +/// or `gsi_pending` or `stream_records` holds a row. +pub(crate) async fn data_has_rows(catalog: &PgPool, data: &PgPool) -> Result { + if std::env::var_os(IGNORE_CONNECTIONS_ENV).is_some() { + return Ok(false); + } + Ok(has_row(catalog, "tables").await? + || has_row(data, "gsi_pending").await? + || has_row(data, "stream_records").await?) +} + +/// One item naming the other sessions on the database `pool` reaches, or none; +/// `which` names the database (`"data"` or `"catalog"`). +pub(crate) async fn other_sessions(pool: &PgPool, which: &str) -> Result, MigrationError> { + type Row = (String, Option, Option); + let (database, others): (String, Vec) = { + let database: String = sqlx::query_scalar("SELECT current_database()::text") + .fetch_one(pool) + .await + .map_err(|e| db_error("name the database", &e))?; + let others = sqlx::query_as( + "SELECT usename::text, application_name, client_addr::text \ + FROM pg_stat_activity \ + WHERE datname = current_database() \ + AND usename IS NOT NULL \ + AND coalesce(backend_type, 'client backend') = 'client backend' \ + AND pid <> pg_backend_pid() \ + AND NOT starts_with(coalesce(application_name, ''), $1) \ + AND coalesce(application_name, '') NOT IN ($2, $3)", + ) + .bind(RUNNER_APPLICATION_PREFIX) + .bind(LOCK_APPLICATION) + .bind(STATUS_APPLICATION) + .fetch_all(pool) + .await + .map_err(|e| db_error("look for other sessions", &e))?; + (database, others) + }; + if others.is_empty() { + return Ok(Vec::new()); + } + let mut described: Vec = others + .iter() + .map(|(user, app, addr)| { + format!( + "{user} from {} ({})", + addr.as_deref().unwrap_or("no client address shown"), + match app.as_deref() { + Some("") | None => "no application name", + Some(a) => a, + } + ) + }) + .collect(); + described.sort(); + described.dedup(); + Ok(vec![format!( + "{} other session(s) hold the {which} database {database}: {}. Migration 6 rewrites \ + stored strings and runs with every ExtendDB server stopped and every other session \ + on the database closed, because a server still writing would leave rows in the \ + earlier encoding. Stop them and run `extenddb migrate --yes` again. If the only \ + other sessions are idle connections a connection pooler holds, set \ + {IGNORE_CONNECTIONS_ENV}=1 to skip this check", + others.len(), + described.join("; ") + )]) +} diff --git a/crates/storage-postgres/src/migrations/m0006_escape_control_chars/keys.rs b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/keys.rs new file mode 100644 index 000000000..4e6658301 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/keys.rs @@ -0,0 +1,135 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Two rewrites of migration 6 that cannot be done by escaping a stored text +//! where it lies, because the text is derived from the key strings: +//! +//! - A partition key column of a key schema with more than one HASH attribute +//! holds the netstring join of the parts (`:,` each), and the +//! escape changes a part's length. [`rebuild_composite_rows`] splits each +//! legacy value, escapes the parts and joins them again with the new +//! lengths, through the function the write path uses +//! (`key_text::join_escaped_parts`). +//! - `gsi_pending.worker_partition` is a hash of the stored base key text +//! (`gsi_queue::partition_for`), so it changes with the key text. +//! [`recompute_worker_partitions`] recomputes it with the function the +//! enqueue uses (`gsi_queue::worker_partition`). +//! +//! Both run in the data body's transaction, after the table's other columns. + +use extenddb_storage::migrations::MigrationError; +use sqlx::PgConnection; + +use super::{db_error, rewrite_longest_first}; +use crate::data::key_text::reescape_legacy_composite; +use crate::gsi_queue::{PendingApplyContext, worker_partition}; + +/// The `backup_items` rows whose `pk` holds a composite key: the rows of a +/// backup whose table's key schema has more than one HASH attribute. A boolean +/// SQL expression over a `backup_items` row; `backups` is in the same catalog +/// database. +pub(crate) const BACKUP_ITEMS_COMPOSITE_ROWS: &str = "backup_arn IN (\ + SELECT b.backup_arn FROM backups b WHERE (\ + SELECT COUNT(*) FROM jsonb_array_elements(b.key_schema) e \ + WHERE e->>'KeyType' = 'HASH') > 1)"; + +/// Whether a catalog key schema (`[{"AttributeName", "KeyType"}, ...]`) has +/// more than one HASH attribute, so its partition key column holds a netstring +/// join. +pub(crate) fn has_composite_partition_key(key_schema: &serde_json::Value) -> bool { + key_schema.as_array().is_some_and(|elements| { + elements + .iter() + .filter(|e| e.get("KeyType").and_then(serde_json::Value::as_str) == Some("HASH")) + .count() + > 1 + }) +} + +/// Rebuild the composite key text in `col` of the rows that `rows` (a boolean +/// SQL expression over the row) selects and that hold U+0001, one row at a +/// time, longest legacy text first and in batches ([`rewrite_longest_first`]). +/// A SQL `replace()` over the whole text would leave each length prefix +/// counting the raw part (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, +/// where this release writes and looks up `3:a\x01\x02,1:b,`). A value that is +/// not a netstring fails the body, naming the table and column (`what`), and +/// the store's transaction rolls back. +pub(crate) async fn rebuild_composite_rows( + conn: &mut PgConnection, + quoted_table: &str, + col: &str, + rows: &str, + what: &str, +) -> Result { + rewrite_longest_first(conn, quoted_table, col, rows, what, |legacy| { + reescape_legacy_composite(legacy).ok_or_else(|| { + MigrationError::Store(format!( + "re-encode {what}: the composite key {legacy:?} is not a netstring" + )) + }) + }) + .await +} + +/// The partition a row queued with these columns gets from this release's +/// enqueue, or `None` when a column does not decode (a worker handles such a +/// row as a poison row, whatever partition holds it). +fn current_partition( + old_item: Option, + new_item: Option, + index_context: serde_json::Value, +) -> Option { + let old_item = old_item.map(crate::data::json_to_item).transpose().ok()?; + let new_item = new_item.map(crate::data::json_to_item).transpose().ok()?; + let context: PendingApplyContext = crate::data::stored_json_to(index_context).ok()?; + worker_partition(old_item.as_ref(), new_item.as_ref(), &context).ok() +} + +/// Recompute `worker_partition` of the queued rows whose item holds U+0001, +/// after their jsonb columns were re-encoded in the same transaction. +/// +/// A release without the escape hashed the raw base key; this release hashes +/// the escaped one, so for a key holding U+0001 a row queued before the +/// upgrade and the next write of the same item would be claimed by different +/// workers, in either order, which breaks the queue's one item, one worker +/// rule. Every row of one item moves to the same new partition and keeps its +/// `id` and `ready_at`, so the item's rows are still claimed in write order, +/// and a row enqueued after the upgrade gets a `ready_at` no earlier than +/// theirs from the partition clamp in `enqueue_gsi_pending`. +pub(crate) async fn recompute_worker_partitions(conn: &mut PgConnection) -> Result { + type Row = ( + i64, + i32, + Option, + Option, + serde_json::Value, + ); + // '\u0001' is how jsonb::text renders U+0001; chr(92) spells the backslash + // as in `escape_jsonb_rows`. The base key is in new_item, or in old_item for + // a delete, as `worker_partition` reads it. + let rows: Vec = sqlx::query_as( + "SELECT id, worker_partition, old_item, new_item, index_context FROM gsi_pending \ + WHERE position((chr(92) || 'u0001') IN COALESCE(new_item, old_item)::text) > 0 \ + ORDER BY id FOR UPDATE", + ) + .fetch_all(&mut *conn) + .await + .map_err(|e| db_error("find the gsi_pending rows to repartition", &e))?; + let mut changed: u64 = 0; + for (id, stored, old_item, new_item, index_context) in rows { + let Some(partition) = current_partition(old_item, new_item, index_context) else { + continue; + }; + if partition == stored { + continue; + } + sqlx::query("UPDATE gsi_pending SET worker_partition = $1 WHERE id = $2") + .bind(partition) + .bind(id) + .execute(&mut *conn) + .await + .map_err(|e| db_error(&format!("repartition gsi_pending row {id}"), &e))?; + changed += 1; + } + Ok(changed) +} diff --git a/crates/storage-postgres/src/migrations/m0006_escape_control_chars/mod.rs b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/mod.rs new file mode 100644 index 000000000..5d7e5c5f5 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/mod.rs @@ -0,0 +1,578 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Migration 6, `escape_control_chars`, PostgreSQL: re-encode the rows an +//! earlier release wrote, whose strings are stored raw. +//! +//! This release stores every string through the order-preserving escape in +//! `extenddb_storage::util::escape_control` (U+0000 as U+0001 U+0001, U+0001 +//! as U+0001 U+0002), so that U+0000, which DynamoDB accepts anywhere a string +//! appears, can be held in `TEXT` and `jsonb` columns. A row an earlier +//! release wrote holds its strings raw, and a raw U+0001 followed by U+0001 or +//! U+0002 reads back differently under the decoder (a lone U+0001 reads back +//! unchanged). Earlier releases could not store U+0000, so for their rows the +//! escape of the stored text is the re-encode, and a row without U+0001 +//! encodes to itself and is left alone. +//! +//! Two bodies, one per database. The catalog body rewrites `backup_items`, +//! which lives in the catalog database; the data body rewrites every data +//! table, index table and vector index table (the text key columns and +//! `item_data`), `gsi_pending` and `stream_records`, and recomputes +//! `gsi_pending.worker_partition` for the rows it changes. Tables are listed +//! from the catalog rows; a row whose table is `DELETING`, or whose physical +//! table is missing, is skipped and noted. +//! +//! The escape is not idempotent: an escaped row also holds U+0001, and a +//! legacy U+0001 U+0002 cannot be told from an escaped U+0001. Each body runs +//! in the runner's transaction and commits with its ledger row, so a run that +//! stops leaves the store as it was, and a store whose row is recorded is +//! never rewritten again; the migration is not convergent. A server of this +//! release refuses a store where the migration is pending, so the bodies see +//! only rows earlier releases wrote, provided those servers are stopped: +//! each body's `detect` stops a run, before the run's first write, while +//! another session holds the database the body rewrites (see [`guard`]). A +//! status read does not look for sessions, so the preview runs beside a +//! server as for every other migration. +//! +//! The key text and document rewrites call the write path's escape and key +//! text functions (`escape_control`, `escape_json_strings`, +//! `key_text::reescape_legacy_composite`, `gsi_queue::worker_partition`), so +//! a migrated row is the row this release writes for the same item. +//! +//! This module's checksum covers `mod.rs`, `keys.rs`, `order.rs` and +//! `guard.rs`, and is pinned once the migration is released. They are +//! excluded from rustfmt and clippy so neither can require an edit. + +mod guard; +mod keys; +mod order; + +use async_trait::async_trait; +use extenddb_storage::migrations::{CodeBody, Done, MigrationError}; +use sqlx::{PgConnection, PgPool}; + +use super::PostgresStores; + +pub(crate) use guard::other_sessions; +#[cfg(test)] +pub(crate) use guard::{IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows}; +pub(crate) use keys::{BACKUP_ITEMS_COMPOSITE_ROWS, has_composite_partition_key}; +pub(crate) use order::{BATCH, rewrite_longest_first, with_detail}; + +/// The text of every file of this module, whose SHA-256 the checksum test pins. +pub(crate) const SOURCE: &str = concat!( + include_str!("mod.rs"), + include_str!("keys.rs"), + include_str!("order.rs"), + include_str!("guard.rs"), +); + +/// Recorded as this migration's checksum. Changes only with a new migration. +const FINGERPRINT: &str = "0006_escape_control_chars/postgres/1"; + +/// The catalog body: `backup_items`. +pub(crate) struct EscapeBackupItems; + +/// The data body: the data, index and vector index tables, `gsi_pending` and +/// `stream_records`. +pub(crate) struct EscapeDataRows; + +#[async_trait] +impl CodeBody for EscapeBackupItems { + fn fingerprint(&self) -> &'static str { + FINGERPRINT + } + + /// Another session on the catalog database, while `backup_items` holds a + /// row. + async fn detect(&self, stores: &PostgresStores) -> Result, MigrationError> { + if !stores.checks_sessions || !guard::catalog_has_rows(&stores.catalog).await? { + return Ok(Vec::new()); + } + other_sessions(&stores.catalog, "catalog").await + } + + async fn run(&self, stores: &PostgresStores) -> Result { + let mut conn = stores + .catalog + .acquire() + .await + .map_err(|e| MigrationError::store("reach the catalog database", e))?; + escape_catalog(&mut conn).await.map(|notes| Done { notes }) + } +} + +#[async_trait] +impl CodeBody for EscapeDataRows { + fn fingerprint(&self) -> &'static str { + FINGERPRINT + } + + /// Another session on the data database, while the catalog lists a table + /// or `gsi_pending` or `stream_records` holds a row. + async fn detect(&self, stores: &PostgresStores) -> Result, MigrationError> { + if !stores.checks_sessions || !guard::data_has_rows(&stores.catalog, &stores.data).await? { + return Ok(Vec::new()); + } + other_sessions(&stores.data, "data").await + } + + async fn run(&self, stores: &PostgresStores) -> Result { + let mut conn = stores + .data + .acquire() + .await + .map_err(|e| MigrationError::store("reach the data database", e))?; + escape_data(&stores.catalog, &mut conn).await.map(|notes| Done { notes }) + } +} + +/// A failed statement as a migration error: `what`, the database's message +/// with its DETAIL ([`with_detail`]), and the SQLSTATE, which the runner reads +/// to run the body again after a lock timeout. +pub(crate) fn db_error(what: &str, e: &sqlx::Error) -> MigrationError { + let message = format!("{what}: {}", with_detail(e)); + match e.as_database_error().and_then(|d| d.code()) { + Some(code) => MigrationError::Database { + message, + sqlstate: code.into_owned(), + }, + None => MigrationError::Store(message), + } +} + +/// One physical table's rewrite: its text key columns, and the jsonb columns +/// whose rows are re-encoded one by one. +struct EscapeWork { + /// Bare (unquoted) table name, e.g. `_ddb_` or `gsi_pending`. + table: String, + text_columns: Vec, + jsonb_columns: Vec, + /// `gsi_pending` only: recompute `worker_partition` after the re-encode + /// ([`keys::recompute_worker_partitions`]). + recompute_worker_partition: bool, + /// The DynamoDB table (and index) the physical table holds, for errors + /// and notes. + ddb_name: Option, +} + +impl EscapeWork { + /// `
.`, with the DynamoDB name when known: how errors name a + /// column. + fn column(&self, col: &str) -> String { + match &self.ddb_name { + Some(ddb) => format!("{}.{col} ({ddb})", self.table), + None => format!("{}.{col}", self.table), + } + } + + /// `
`, with the DynamoDB name when known: how notes name a table. + fn label(&self) -> String { + match &self.ddb_name { + Some(ddb) => format!("{} ({ddb})", self.table), + None => self.table.clone(), + } + } +} + +/// A text key column and the rows of it that hold a composite partition key. +struct TextKeyColumn { + name: String, + /// SQL boolean expression over the row, true where the column holds the + /// netstring join of several HASH attributes. Those rows are rebuilt one + /// by one ([`keys::rebuild_composite_rows`]); the others hold one + /// attribute's text and get the single-statement SQL replace. + composite_rows: String, +} + +impl TextKeyColumn { + fn new(name: String, composite: bool) -> Self { + let composite_rows = if composite { "TRUE" } else { "FALSE" }.to_owned(); + Self { + name, + composite_rows, + } + } +} + +/// The columns of `table` in the public schema of type `data_type` among +/// `names` (or, for `None`, the key columns `pk`, `base_pk`, `sk*_s` and +/// `base_sk*_s`), in column order. +async fn columns( + conn: &mut PgConnection, + table: &str, + data_type: &str, + names: Option<&[&str]>, +) -> Result, MigrationError> { + let names: Option> = names.map(|n| n.iter().map(|c| (*c).to_owned()).collect()); + sqlx::query_scalar( + "SELECT column_name::text FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = $2 \ + AND CASE WHEN $3::text[] IS NULL \ + THEN column_name IN ('pk', 'base_pk') OR column_name::text ~ '^(base_)?sk[0-9]*_s$' \ + ELSE column_name::text = ANY($3) END \ + ORDER BY ordinal_position", + ) + .bind(table) + .bind(data_type) + .bind(names) + .fetch_all(&mut *conn) + .await + .map_err(|e| db_error(&format!("list the {data_type} columns of {table}"), &e)) +} + +/// The rewrite of a `_ddb_*` table, whose columns are read from +/// `information_schema.columns` so that exactly the sort key columns this +/// table has (`sk_s`, `sk_s`, `base_sk_s`, ...) are covered. `None` +/// when the physical table does not exist. `composite` names the columns +/// whose key schema has more than one HASH attribute, so they hold a +/// netstring join on every row. +async fn dynamic_table_work( + conn: &mut PgConnection, + table: String, + composite: &[&str], +) -> Result, MigrationError> { + let text_columns = columns(conn, &table, "text", None).await?; + let jsonb_columns = columns(conn, &table, "jsonb", Some(&["item_data"])).await?; + if text_columns.is_empty() && jsonb_columns.is_empty() { + return Ok(None); + } + let text_columns = text_columns + .into_iter() + .map(|name| { + let composite = composite.contains(&name.as_str()); + TextKeyColumn::new(name, composite) + }) + .collect(); + Ok(Some(EscapeWork { + table, + text_columns, + jsonb_columns, + recompute_worker_partition: false, + ddb_name: None, + })) +} + +/// The rewrite of a fixed-name table, with the candidate columns filtered +/// through `information_schema.columns`. `None` when the table is absent. +async fn fixed_table_work( + conn: &mut PgConnection, + table: &str, + text: &[&str], + jsonb: &[&str], +) -> Result, MigrationError> { + let text_columns = if text.is_empty() { + Vec::new() + } else { + columns(conn, table, "text", Some(text)).await? + }; + let jsonb_columns = columns(conn, table, "jsonb", Some(jsonb)).await?; + if text_columns.is_empty() && jsonb_columns.is_empty() { + return Ok(None); + } + Ok(Some(EscapeWork { + table: table.to_owned(), + text_columns: text_columns + .into_iter() + .map(|name| TextKeyColumn::new(name, false)) + .collect(), + jsonb_columns, + recompute_worker_partition: false, + ddb_name: None, + })) +} + +/// The re-encoded form of a stored jsonb value, or `None` when re-encoding +/// does not change it. `escape_json_strings` only changes strings and object +/// keys containing U+0000 or U+0001, so a plain document and a document whose +/// strings hold the literal six-character text backslash-u-0001 both come +/// back equal and are skipped. +pub(crate) fn reencoded_json(value: &serde_json::Value) -> Option { + let escaped = extenddb_storage::util::escape_json_strings(value.clone()); + (escaped != *value).then_some(escaped) +} + +/// Re-encode the rows of one jsonb column whose stored document contains +/// U+0001. +/// +/// The candidate ctids are read once, before any row of this column is +/// touched, so no row is visited twice; an update moves a row (a ctid names a +/// row version), always after its value was read. The values are then read +/// in batches of [`BATCH`] by ctid, so a large table never loads into memory. +async fn escape_jsonb_rows( + conn: &mut PgConnection, + quoted_table: &str, + col: &str, +) -> Result { + // '\u0001' (six characters) is how jsonb::text renders a raw U+0001 inside + // a string or key. It also matches a stored string whose content is a + // literal backslash followed by u0001 (rendered '\\u0001'), which is + // harmless: that row re-encodes to itself and is skipped below. jsonb text + // rendering is why SQL replace() is not used here: it would corrupt that + // literal-backslash case. The backslash is spelled chr(92) so the + // predicate reads the same under either value of + // standard_conforming_strings; a plain '\u0001' literal would become the + // single byte 0x01 with the setting off and match nothing. + let select_ctids = format!( + "SELECT ctid::text FROM {quoted_table} \ + WHERE position((chr(92) || 'u0001') IN \"{col}\"::text) > 0 FOR UPDATE" + ); + let ctids: Vec = sqlx::query_scalar(&select_ctids) + .fetch_all(&mut *conn) + .await + .map_err(|e| db_error(&format!("find the rows to re-encode in {quoted_table}"), &e))?; + + let fetch_batch = + format!("SELECT ctid::text, \"{col}\" FROM {quoted_table} WHERE ctid = ANY($1::tid[])"); + let update_row = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); + let mut changed: u64 = 0; + for batch in ctids.chunks(BATCH) { + let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&fetch_batch) + .bind(batch.to_vec()) + .fetch_all(&mut *conn) + .await + .map_err(|e| db_error(&format!("read rows of {quoted_table}"), &e))?; + for (ctid, value) in rows { + if let Some(escaped) = reencoded_json(&value) { + sqlx::query(&update_row) + .bind(escaped) + .bind(&ctid) + .execute(&mut *conn) + .await + .map_err(|e| db_error(&format!("re-encode a row of {quoted_table}"), &e))?; + changed += 1; + } + } + } + Ok(changed) +} + +/// Rewrite one table; returns the number of row updates. +async fn escape_rows_in_table( + conn: &mut PgConnection, + work: &EscapeWork, +) -> Result { + let quoted = format!("\"{}\"", work.table); + let mut rewritten: u64 = 0; + + // Key text columns holding one attribute's text: TEXT has no escaping + // layer, so a single SQL statement per column is exact. NULL columns never + // match (position() is NULL). The statement can fail on the primary key + // when two legacy keys differ only by a U+0002 after a U+0001, depending + // on the order it meets them (`order`); it runs under a savepoint, and on + // a unique violation the column is rewritten again row by row, longest + // legacy text first. Rows holding a composite key are rebuilt part by + // part instead; the other columns of the row keep the replace(). + for col in &work.text_columns { + let TextKeyColumn { + name, + composite_rows, + } = col; + let what = work.column(name); + let single_rows = format!("NOT ({composite_rows})"); + let sql = format!( + "UPDATE {quoted} SET \"{name}\" = replace(\"{name}\", chr(1), chr(1) || chr(2)) \ + WHERE position(chr(1) IN \"{name}\") > 0 AND {single_rows}" + ); + sqlx::query("SAVEPOINT escape_column") + .execute(&mut *conn) + .await + .map_err(|e| db_error(&format!("savepoint before {what}"), &e))?; + match sqlx::query(&sql).execute(&mut *conn).await { + Ok(done) => { + sqlx::query("RELEASE SAVEPOINT escape_column") + .execute(&mut *conn) + .await + .map_err(|e| db_error(&format!("release the savepoint of {what}"), &e))?; + rewritten += done.rows_affected(); + } + Err(e) if crate::pg_util::is_unique_violation(&e) => { + sqlx::query("ROLLBACK TO SAVEPOINT escape_column") + .execute(&mut *conn) + .await + .map_err(|e| db_error(&format!("roll back {what}"), &e))?; + // Legacy text holds no U+0000, so the escape is the replace() + // above. + rewritten += rewrite_longest_first(conn, "ed, name, &single_rows, &what, |legacy| { + Ok(extenddb_storage::util::escape_control(legacy).into_owned()) + }) + .await?; + } + Err(e) => return Err(db_error(&format!("re-encode {what}"), &e)), + } + if composite_rows != "FALSE" { + rewritten += + keys::rebuild_composite_rows(conn, "ed, name, composite_rows, &what).await?; + } + } + + for col in &work.jsonb_columns { + rewritten += escape_jsonb_rows(conn, "ed, col).await?; + } + if work.recompute_worker_partition { + rewritten += keys::recompute_worker_partitions(conn).await?; + } + Ok(rewritten) +} + +/// Rewrite every table of `work` in order; one note per table with a change. +async fn escape_all( + conn: &mut PgConnection, + work: &[EscapeWork], + notes: &mut Vec, +) -> Result<(), MigrationError> { + for w in work { + let rewritten = escape_rows_in_table(conn, w).await?; + if rewritten > 0 { + notes.push(format!("{}: {rewritten} row update(s)", w.label())); + } + } + Ok(()) +} + +/// The catalog body on `conn`, the catalog database in the runner's +/// transaction. `backup_items.pk` is the data table's `pk` as the backup +/// copied it, so a backup of a table with several HASH attributes holds a +/// netstring join there. +pub(crate) async fn escape_catalog(conn: &mut PgConnection) -> Result, MigrationError> { + let mut notes = Vec::new(); + let mut work = Vec::new(); + if let Some(mut w) = fixed_table_work(conn, "backup_items", &["pk", "sk"], &["item_data"]).await? { + for col in &mut w.text_columns { + if col.name == "pk" { + col.composite_rows = BACKUP_ITEMS_COMPOSITE_ROWS.to_owned(); + } + } + work.push(w); + } + escape_all(conn, &work, &mut notes).await?; + Ok(notes) +} + +/// The data body on `conn`, the data database in the runner's transaction, +/// with the tables listed from `catalog`. +/// +/// A partition key column whose key schema has more than one HASH attribute +/// holds a netstring join (`key_text::composite_pk_to_text`): `pk` of a table +/// or index with such a key schema, and `base_pk` of the index and vector +/// tables of a table with one. +pub(crate) async fn escape_data( + catalog: &PgPool, + conn: &mut PgConnection, +) -> Result, MigrationError> { + let mut notes = Vec::new(); + let mut work: Vec = Vec::new(); + + type TableRow = (String, String, String, String, serde_json::Value); + let tables: Vec = sqlx::query_as( + "SELECT table_id, table_name, account_id, table_status, key_schema FROM tables \ + ORDER BY table_id COLLATE \"C\"", + ) + .fetch_all(catalog) + .await + .map_err(|e| db_error("list tables", &e))?; + let deleting: std::collections::HashSet<&str> = tables + .iter() + .filter(|(_, _, _, status, _)| status == "DELETING") + .map(|(id, _, _, _, _)| id.as_str()) + .collect(); + let composite_tables: std::collections::HashSet<&str> = tables + .iter() + .filter(|(_, _, _, _, ks)| has_composite_partition_key(ks)) + .map(|(id, _, _, _, _)| id.as_str()) + .collect(); + // How errors and notes name the DynamoDB table of a physical table. + let ddb_tables: std::collections::HashMap<&str, String> = tables + .iter() + .map(|(id, name, account, _, _)| (id.as_str(), format!("table {name:?} of account {account}"))) + .collect(); + let ddb_table = |table_id: &str| { + ddb_tables + .get(table_id) + .cloned() + .unwrap_or_else(|| format!("table id {table_id}")) + }; + let skip = |label: String, physical: &str, notes: &mut Vec, table_id: &str| { + if deleting.contains(table_id) { + notes.push(format!("{label}: skipped, the table is being deleted")); + } else { + notes.push(format!("{label}: skipped, its physical table {physical} does not exist")); + } + }; + + for (id, _, _, _, ks) in &tables { + let label = ddb_table(id); + let physical = format!("_ddb_{id}"); + let cols: &[&str] = if has_composite_partition_key(ks) { &["pk"] } else { &[] }; + match dynamic_table_work(conn, physical.clone(), cols).await? { + Some(mut w) if !deleting.contains(id.as_str()) => { + w.ddb_name = Some(label); + work.push(w); + } + _ => skip(label, &physical, &mut notes, id), + } + } + let indexes: Vec<(String, String, String, serde_json::Value)> = sqlx::query_as( + "SELECT index_id, table_id, index_name, key_schema FROM indexes \ + ORDER BY index_id COLLATE \"C\"", + ) + .fetch_all(catalog) + .await + .map_err(|e| db_error("list indexes", &e))?; + for (id, table_id, name, ks) in &indexes { + let label = format!("index {name:?} of {}", ddb_table(table_id)); + let physical = format!("_ddb_{id}"); + let mut cols: Vec<&str> = Vec::new(); + if has_composite_partition_key(ks) { + cols.push("pk"); + } + if composite_tables.contains(table_id.as_str()) { + cols.push("base_pk"); + } + match dynamic_table_work(conn, physical.clone(), &cols).await? { + Some(mut w) if !deleting.contains(table_id.as_str()) => { + w.ddb_name = Some(label); + work.push(w); + } + _ => skip(label, &physical, &mut notes, table_id), + } + } + let vectors: Vec<(String, String, String)> = sqlx::query_as( + "SELECT index_id, table_id, index_name FROM vector_indexes \ + ORDER BY index_id COLLATE \"C\"", + ) + .fetch_all(catalog) + .await + .map_err(|e| db_error("list vector indexes", &e))?; + for (id, table_id, name) in &vectors { + let label = format!("vector index {name:?} of {}", ddb_table(table_id)); + let physical = format!("_ddb_vec_{id}"); + let cols: &[&str] = if composite_tables.contains(table_id.as_str()) { + &["base_pk"] + } else { + &[] + }; + match dynamic_table_work(conn, physical.clone(), cols).await? { + Some(mut w) if !deleting.contains(table_id.as_str()) => { + w.ddb_name = Some(label); + work.push(w); + } + _ => skip(label, &physical, &mut notes, table_id), + } + } + + // Fixed tables holding item documents. + if let Some(mut w) = + fixed_table_work(conn, "gsi_pending", &[], &["old_item", "new_item", "index_context"]) + .await? + { + w.recompute_worker_partition = true; + work.push(w); + } + if let Some(w) = fixed_table_work(conn, "stream_records", &[], &["record_data"]).await? { + work.push(w); + } + + escape_all(conn, &work, &mut notes).await?; + Ok(notes) +} diff --git a/crates/storage-postgres/src/migrations/m0006_escape_control_chars/order.rs b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/order.rs new file mode 100644 index 000000000..b8876f7fd --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_escape_control_chars/order.rs @@ -0,0 +1,119 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Row-by-row rewrites of one key column for migration 6, in an order that +//! keeps the table's primary key valid after every row. +//! +//! `PostgreSQL` checks a primary key as each row changes, not at the end of the +//! statement. Two legacy keys that differ only by a U+0002 after a U+0001, such +//! as `a\x01` and `a\x01\x02` with the same other key columns, escape to two +//! different texts, `a\x01\x02` and `a\x01\x02\x02`, but the first one's new +//! text is the second one's legacy text. If the shorter one is rewritten first, +//! the table holds `a\x01\x02` twice until the longer one is rewritten, and the +//! update fails with SQLSTATE 23505. A one-statement `UPDATE` meets the two rows +//! in heap order, so whether it fails depends on where they are stored. +//! +//! [`rewrite_longest_first`] rewrites the rows in descending byte length of +//! their legacy text, which never produces such a duplicate: +//! +//! - Every rewrite makes the text longer. Every row it rewrites holds a U+0001, +//! and the escape adds one byte for each; a rebuilt composite key also gives +//! each part its new length, which never takes fewer digits than the old one. +//! - Suppose rewriting row `r` gives the text that row `s` holds, and the two +//! rows agree on the other key columns. If `s` has not been rewritten yet, it +//! holds its legacy text, and that text is the new text of `r`, so it is +//! longer than the legacy text of `r` and `s` was rewritten earlier. If `s` +//! has been rewritten, the two rows have the same new text, and since the +//! escape is injective their legacy texts were equal. +//! - Each other key column holds the legacy texts of every row, or, when an +//! earlier pass of the same transaction rewrote it, their escapes. Either +//! way two rows agree on it now exactly when they agreed before the +//! migration. Two rows that agreed on every key column before the migration +//! would have broken the primary key, so no rewrite meets a duplicate. + +use extenddb_storage::migrations::MigrationError; +use sqlx::PgConnection; + +use super::db_error; + +/// Rows read from the cursor per round trip, and the batch `escape_jsonb_rows` +/// reads. +pub(crate) const BATCH: usize = 500; + +/// The cursor [`rewrite_longest_first`] declares and closes before returning. +const CURSOR: &str = "escape_0006_longest_first"; + +/// Rewrite `col` of the rows that hold U+0001 and that `rows` (a boolean SQL +/// expression over the row) selects, one row at a time, longest legacy text +/// first; `rewrite` gives a row's new text from its legacy text. Runs in the +/// caller's transaction and returns the number of rows changed. `what` names +/// the column in errors, with the DynamoDB table when the caller knows it. +/// +/// One cursor is declared over the matching rows in that order and read +/// [`BATCH`] rows at a time, so this process holds one batch, and `PostgreSQL` +/// sorts the matching rows in `work_mem`, spilling to temporary files beyond +/// it. The cursor's rows are fixed when it is declared and each is returned +/// once, so no row is rewritten twice. Each row is locked as the cursor +/// returns it, as the single-statement path locks the rows it updates. +pub(crate) async fn rewrite_longest_first( + conn: &mut PgConnection, + quoted_table: &str, + col: &str, + rows: &str, + what: &str, + rewrite: impl Fn(&str) -> Result, +) -> Result { + let failed = |step: &str, e: &sqlx::Error| db_error(&format!("{step} {what}"), e); + sqlx::query(&format!( + "DECLARE {CURSOR} NO SCROLL CURSOR FOR \ + SELECT ctid::text, \"{col}\" FROM {quoted_table} \ + WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) \ + ORDER BY octet_length(\"{col}\") DESC FOR UPDATE" + )) + .execute(&mut *conn) + .await + .map_err(|e| failed("find the rows to rewrite in", &e))?; + let fetch = format!("FETCH {BATCH} FROM {CURSOR}"); + let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); + let mut changed: u64 = 0; + loop { + let batch: Vec<(String, String)> = sqlx::query_as(&fetch) + .fetch_all(&mut *conn) + .await + .map_err(|e| failed("read the rows to rewrite in", &e))?; + for (ctid, legacy) in &batch { + let done = sqlx::query(&update) + .bind(rewrite(legacy)?) + .bind(ctid) + .execute(&mut *conn) + .await + .map_err(|e| failed("re-encode", &e))?; + changed += done.rows_affected(); + } + if batch.len() < BATCH { + break; + } + } + sqlx::query(&format!("CLOSE {CURSOR}")) + .execute(&mut *conn) + .await + .map_err(|e| failed("close the cursor over", &e))?; + Ok(changed) +} + +/// A database error as text, with `PostgreSQL`'s DETAIL when the error has one; +/// for a unique violation the DETAIL names the key already present. sqlx's +/// `Display` writes the message alone. The DETAIL is quoted with its control +/// characters escaped, since the keys this migration rewrites hold them. +pub(crate) fn with_detail(e: &sqlx::Error) -> String { + let detail = match e { + sqlx::Error::Database(db) => db + .try_downcast_ref::() + .and_then(sqlx::postgres::PgDatabaseError::detail), + _ => None, + }; + match detail { + Some(detail) => format!("{e} (DETAIL: {detail:?})"), + None => e.to_string(), + } +} diff --git a/crates/storage-postgres/src/migrations/m0006_guard_tests.rs b/crates/storage-postgres/src/migrations/m0006_guard_tests.rs new file mode 100644 index 000000000..2552ea163 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_guard_tests.rs @@ -0,0 +1,195 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 6's sessions check (`other_sessions`, which both +//! bodies' `detect` call), with the scratch database and the skip convention +//! of `m0006_tests`. That the runner stops on a `detect` item before its first +//! write is checked over two databases in `tests/migrations_golden.rs`. + +use sqlx::PgPool; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; + +use super::m0006_escape_control_chars::{ + IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows, other_sessions, +}; +use super::m0006_tests::{base_conn, scratch, seed, skip, test_application}; + +/// `PgPool::close` returns before PostgreSQL removes the closed session from +/// `pg_stat_activity`, so a check right after a close can still count it. +/// Read the items again until there are none, for at most five seconds, and +/// return the last answer. +async fn after_close(pool: &PgPool, which: &str) -> Vec { + let mut items = other_sessions(pool, which) + .await + .expect("look for sessions"); + for _ in 0..50 { + if items.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + items = other_sessions(pool, which) + .await + .expect("look for sessions"); + } + items +} + +/// A pool of one unnamed connection to `database`, as a server or an +/// operator's `psql` would hold. +async fn unnamed(base: &str, database: &str) -> PgPool { + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/{database}")) + .await + .expect("connect as another client would"); + sqlx::query("SELECT 1").execute(&pool).await.unwrap(); + pool +} + +/// A server (or any other session) still connected to the data database is +/// one item; the runner's own sessions are not. +#[tokio::test] +async fn another_session_on_the_data_database_is_reported() { + if base_conn().is_none() { + skip("another_session_on_the_data_database_is_reported"); + return; + } + let s = scratch().await; + seed(&s.db).await; + let base = base_conn().unwrap(); + assert_eq!(after_close(&s.db, "data").await, Vec::::new()); + + let server = unnamed(&base, &s.db_name).await; + let items = other_sessions(&s.db, "data").await.unwrap(); + assert_eq!(items.len(), 1, "{items:?}"); + assert!( + items[0].contains(&format!( + "1 other session(s) hold the data database {}", + s.db_name + )), + "{items:?}" + ); + assert!(items[0].contains("no application name"), "{items:?}"); + assert!(items[0].contains(IGNORE_CONNECTIONS_ENV), "{items:?}"); + + server.close().await; + assert_eq!(after_close(&s.db, "data").await, Vec::::new()); + s.cleanup().await; +} + +/// With the catalog in its own database, a session holding only that database +/// is reported by the catalog body's check, which names the catalog database, +/// and not by the data body's. +#[tokio::test] +async fn a_session_on_a_separate_catalog_is_reported_for_the_catalog() { + if base_conn().is_none() { + skip("a_session_on_a_separate_catalog_is_reported_for_the_catalog"); + return; + } + let data = scratch().await; + let catalog = scratch().await; + let base = base_conn().unwrap(); + + let client = unnamed(&base, &catalog.db_name).await; + assert_eq!(after_close(&data.db, "data").await, Vec::::new()); + let items = other_sessions(&catalog.db, "catalog").await.unwrap(); + assert_eq!(items.len(), 1, "{items:?}"); + assert!( + items[0].contains(&format!( + "other session(s) hold the catalog database {}", + catalog.db_name + )), + "{items:?}" + ); + + client.close().await; + assert_eq!( + after_close(&catalog.db, "catalog").await, + Vec::::new() + ); + data.cleanup().await; + catalog.cleanup().await; +} + +/// The migrator connects as the application role, which is not a superuser, +/// and `pg_stat_activity` hides `backend_type` of other roles' sessions from +/// it. A session of another role (an operator's `psql`, a server under a +/// different role) still counts. +#[tokio::test] +async fn another_roles_session_counts_from_a_non_superuser_pool() { + if base_conn().is_none() { + skip("another_roles_session_counts_from_a_non_superuser_pool"); + return; + } + let s = scratch().await; + let base = base_conn().unwrap(); + let role = format!( + "eddb_guard_{}", + &uuid::Uuid::new_v4().simple().to_string()[..12] + ); + sqlx::query(&format!( + "CREATE ROLE \"{role}\" LOGIN PASSWORD 'guard-test' NOSUPERUSER" + )) + .execute(&s.admin) + .await + .expect("create a plain login role"); + + // The migrator's view: the plain role, named as a runner. + let options = format!("{base}/{}", s.db_name) + .parse::() + .expect("scratch connection string") + .username(&role) + .password("guard-test") + .application_name(&test_application()); + let migrator = PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .expect("connect as the plain role"); + // Only the scratch pool is connected, and it is named as a runner. + assert_eq!(after_close(&migrator, "data").await, Vec::::new()); + + // A superuser session with no application name. The plain role sees its + // datname and usename but not its backend_type. + let holder = unnamed(&base, &s.db_name).await; + let hidden: Option = sqlx::query_scalar( + "SELECT backend_type FROM pg_stat_activity \ + WHERE datname = current_database() AND usename <> current_user LIMIT 1", + ) + .fetch_one(&migrator) + .await + .expect("read another role's row"); + assert!( + hidden.is_none(), + "this test needs a role that cannot see other sessions' backend_type" + ); + let items = other_sessions(&migrator, "data").await.unwrap(); + assert_eq!(items.len(), 1, "{items:?}"); + assert!(items[0].contains("no client address shown"), "{items:?}"); + + holder.close().await; + assert_eq!(after_close(&migrator, "data").await, Vec::::new()); + migrator.close().await; + sqlx::query(&format!("DROP ROLE \"{role}\"")) + .execute(&s.admin) + .await + .expect("remove the test role"); + s.cleanup().await; +} + +/// A store with nothing to rewrite needs no check: a fresh store, such as the +/// one `init` creates, has no table, no backup and no queued or stream row. +#[tokio::test] +async fn only_a_store_with_rows_is_checked() { + if base_conn().is_none() { + skip("only_a_store_with_rows_is_checked"); + return; + } + let s = scratch().await; + assert!(!catalog_has_rows(&s.db).await.unwrap()); + assert!(!data_has_rows(&s.db, &s.db).await.unwrap()); + seed(&s.db).await; + assert!(catalog_has_rows(&s.db).await.unwrap()); + assert!(data_has_rows(&s.db, &s.db).await.unwrap()); + s.cleanup().await; +} diff --git a/crates/storage-postgres/src/migrations/m0006_keys_tests.rs b/crates/storage-postgres/src/migrations/m0006_keys_tests.rs new file mode 100644 index 000000000..9d5ae9812 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_keys_tests.rs @@ -0,0 +1,332 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 6's composite key rebuild and `worker_partition` +//! recompute, with the scratch database and the skip convention of +//! `m0006_tests`: without `EXTENDDB_TEST_PG_CONNECTION_STRING` every live test +//! reports a skip and passes. Each seeds rows the way a release without the +//! escape wrote them. + +//! Live checks against a scratch database, with the helpers and the +//! skip convention of `migrations::live_reencode`: without +//! `EXTENDDB_TEST_PG_CONNECTION_STRING` every test reports a skip and +//! passes. Each seeds rows the way a build without the escape wrote them. + +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, Item, KeySchemaElement, KeyType, Projection, + ProjectionType, ScalarAttributeType, +}; +use serde_json::json; +use sqlx::PgPool; + +use super::m0006_tests::{base_conn, run_pool, scratch, skip}; +use crate::data::key_text::composite_pk_to_text; +use crate::gsi_queue::{ + GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending, partition_for, + worker_partition, +}; + +fn element(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +fn text(v: &str) -> AttributeValue { + AttributeValue::S(v.to_owned()) +} + +async fn exec(db: &PgPool, sql: &str, binds: &[serde_json::Value]) { + let mut q = sqlx::query(sql); + for b in binds { + q = q.bind(b.clone()); + } + q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); +} + +async fn texts(db: &PgPool, sql: &str) -> Vec { + sqlx::query_scalar(sql) + .fetch_all(db) + .await + .unwrap_or_else(|e| panic!("{sql}: {e}")) +} + +/// A table with two HASH attributes (`t2`), a two-HASH GSI on a one-HASH +/// table (`i2` on `t1`), a one-HASH GSI on `t2` (`i3`), and a backup of +/// each table, each holding a legacy row with a raw U+0001 in a HASH part. +async fn seed_composite(db: &PgPool) { + exec( + db, + "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'esc')", + &[], + ) + .await; + let one = json!([{"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}]); + let two = json!([{"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}]); + for (id, ks) in [("t1", &one), ("t2", &two)] { + exec( + db, + &format!( + "INSERT INTO tables (account_id, table_name, key_schema, \ + attribute_definitions, table_status, table_arn, table_id) \ + VALUES ('111122223333', '{id}', $1, '[]', 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/{id}', '{id}')" + ), + std::slice::from_ref(ks), + ) + .await; + } + for (table, index, ks) in [ + ( + "t1", + "i2", + json!([{"AttributeName": "g1", "KeyType": "HASH"}, + {"AttributeName": "g2", "KeyType": "HASH"}]), + ), + ( + "t2", + "i3", + json!([{"AttributeName": "g", "KeyType": "HASH"}]), + ), + ] { + exec( + db, + &format!( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, \ + key_schema, projection) VALUES ('{table}', '{index}', '{index}', 'GSI', \ + $1, '{{\"ProjectionType\": \"ALL\"}}')" + ), + &[ks], + ) + .await; + } + sqlx::raw_sql( + r#"CREATE TABLE "_ddb_t2" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, sk_s)); + CREATE TABLE "_ddb_i2" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); + CREATE TABLE "_ddb_i3" ( + pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", + base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", + item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); + INSERT INTO "_ddb_t2" VALUES + (E'2:a\x01,1:b,', 's', + '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}, "sk": {"S": "s"}}'), + ('1:x,1:y,', 's', '{"h1": {"S": "x"}, "h2": {"S": "y"}, "sk": {"S": "s"}}'); + INSERT INTO "_ddb_i2" VALUES + (E'2:g\x01,1:h,', NULL, E'p\x01', E's\x01', + '{"g1": {"S": "g\u0001"}, "g2": {"S": "h"}, "pk": {"S": "p\u0001"}}'); + INSERT INTO "_ddb_i3" VALUES + (E'g\x01', NULL, E'2:a\x01,1:b,', 's', + '{"g": {"S": "g\u0001"}, "h1": {"S": "a\u0001"}, "h2": {"S": "b"}}'); + INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, + key_schema, attribute_definitions) VALUES + ('b1', 'b1', 't1', 't1', '111122223333', + '[{"AttributeName": "pk", "KeyType": "HASH"}]', '[]'), + ('b2', 'b2', 't2', 't2', '111122223333', + '[{"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}]', '[]'); + INSERT INTO backup_items (backup_arn, pk, sk, item_data) VALUES + ('b1', E'p\x01', NULL, '{"pk": {"S": "p\u0001"}}'), + ('b2', E'2:a\x01,1:b,', NULL, '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}}');"#, + ) + .execute(db) + .await + .expect("seed the legacy rows"); +} + +#[tokio::test] +async fn rebuilds_composite_partition_keys_part_by_part() { + if base_conn().is_none() { + skip("rebuilds_composite_partition_keys_part_by_part"); + return; + } + let s = scratch().await; + seed_composite(&s.db).await; + run_pool(&s.db).await.expect("run the data code migrations"); + + // What this build writes and looks up for the legacy key + // h1 = "a\x01", h2 = "b": each part escaped, then joined. + let mut item = Item::new(); + item.insert("h1".to_owned(), text("a\u{1}")); + item.insert("h2".to_owned(), text("b")); + let ks = [element("h1", KeyType::Hash), element("h2", KeyType::Hash)]; + let expected = composite_pk_to_text(&item, &ks).expect("composite key text"); + assert_eq!(expected, "3:a\u{1}\u{2},1:b,"); + + // The table with two HASH attributes: the legacy row is rebuilt, the + // plain row keeps its text. + assert_eq!( + texts(&s.db, "SELECT pk FROM \"_ddb_t2\" ORDER BY pk").await, + vec!["1:x,1:y,".to_owned(), expected.clone()] + ); + // A two-HASH GSI: pk rebuilt, the one-HASH base key replaced. + let row: (String, String, String) = + sqlx::query_as("SELECT pk, base_pk, base_sk_s FROM \"_ddb_i2\"") + .fetch_one(&s.db) + .await + .expect("read _ddb_i2"); + assert_eq!( + row, + ( + "3:g\u{1}\u{2},1:h,".to_owned(), + "p\u{1}\u{2}".to_owned(), + "s\u{1}\u{2}".to_owned() + ) + ); + // A one-HASH GSI on the two-HASH table: pk replaced, base_pk rebuilt. + let row: (String, String) = sqlx::query_as("SELECT pk, base_pk FROM \"_ddb_i3\"") + .fetch_one(&s.db) + .await + .expect("read _ddb_i3"); + assert_eq!(row, ("g\u{1}\u{2}".to_owned(), expected.clone())); + // backup_items: the backup of the two-HASH table is rebuilt, the + // other replaced. + assert_eq!( + texts(&s.db, "SELECT pk FROM backup_items ORDER BY backup_arn").await, + vec!["p\u{1}\u{2}".to_owned(), expected] + ); + s.cleanup().await; +} + +fn context() -> PendingApplyContext { + PendingApplyContext::Gsi(GsiApplyContext { + base_key_schema: vec![element("pk", KeyType::Hash)], + attribute_definitions: vec![AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }], + index: GsiIndexDef { + index_id: "i1".to_owned(), + key_schema: vec![element("g", KeyType::Hash)], + projection: Projection { + projection_type: ProjectionType::All, + non_key_attributes: None, + }, + }, + }) +} + +/// The partition a build without the escape gave a row for `item`: the +/// hash of the raw key text. +fn legacy_partition(item: &Item) -> i32 { + let raw = extenddb_storage::util::composite_pk_to_text(item, &[element("pk", KeyType::Hash)]) + .expect("raw key text"); + partition_for(&raw) +} + +#[tokio::test] +async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { + if base_conn().is_none() { + skip("recomputes_the_worker_partition_of_rows_queued_before_the_upgrade"); + return; + } + let ctx = context(); + // A key holding U+0001 whose raw and escaped texts hash to different + // workers, so the test sees the move. + let item = [ + "a\u{1}b", + "b\u{1}", + "\u{1}c", + "key\u{1}1", + "key\u{1}2", + "key\u{1}3", + ] + .into_iter() + .map(|k| { + let mut item = Item::new(); + item.insert("pk".to_owned(), text(k)); + item.insert("g".to_owned(), text("v")); + item + }) + .find(|item| { + legacy_partition(item) != worker_partition(None, Some(item), &ctx).expect("partition") + }) + .expect("a key whose partition moves"); + let current = worker_partition(None, Some(&item), &ctx).expect("partition"); + let legacy = legacy_partition(&item); + + // A key without U+0001 and a non-key string with it: same text both ways. + let mut plain = Item::new(); + plain.insert("pk".to_owned(), text("plain")); + plain.insert("note".to_owned(), text("n\u{1}")); + let plain_partition = legacy_partition(&plain); + + let s = scratch().await; + let raw_ctx = serde_json::to_value(&ctx).expect("context json"); + let raw = |i: &Item| serde_json::to_value(i).expect("item json"); + for (old_item, new_item, partition) in [ + (None, Some(raw(&item)), legacy), + (Some(raw(&item)), None, legacy), + (None, Some(raw(&plain)), plain_partition), + ] { + sqlx::query( + "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ + index_context) VALUES ('t1', $1, $2, $3, $4)", + ) + .bind(partition) + .bind(old_item) + .bind(new_item) + .bind(&raw_ctx) + .execute(&s.db) + .await + .expect("seed a queued row"); + } + + run_pool(&s.db).await.expect("run the data code migrations"); + + let partitions: Vec = + sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id") + .fetch_all(&s.db) + .await + .expect("read gsi_pending"); + assert_eq!(partitions, vec![current, current, plain_partition]); + + // The next write of the item is queued on the same worker. + let mut tx = s.db.begin().await.expect("begin"); + enqueue_gsi_pending(&mut tx, "t1", None, Some(&item), 1, &ctx) + .await + .expect("enqueue the next write"); + tx.commit().await.expect("commit"); + let next: i32 = + sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id DESC LIMIT 1") + .fetch_one(&s.db) + .await + .expect("read the new row"); + assert_eq!(next, current); + s.cleanup().await; +} + +mod unit { + use super::super::m0006_escape_control_chars::has_composite_partition_key; + use serde_json::json; + + #[test] + fn only_a_key_schema_with_two_or_more_hash_attributes_is_composite() { + let one = json!([ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let two = json!([ + {"AttributeName": "h1", "KeyType": "HASH"}, + {"AttributeName": "h2", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let ranges = json!([ + {"AttributeName": "h", "KeyType": "HASH"}, + {"AttributeName": "r1", "KeyType": "RANGE"}, + {"AttributeName": "r2", "KeyType": "RANGE"} + ]); + assert!(!has_composite_partition_key(&one)); + assert!(has_composite_partition_key(&two)); + assert!(!has_composite_partition_key(&ranges)); + assert!(!has_composite_partition_key(&json!({}))); + } +} diff --git a/crates/storage-postgres/src/migrations/m0006_order_tests.rs b/crates/storage-postgres/src/migrations/m0006_order_tests.rs new file mode 100644 index 000000000..e6c6691a4 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_order_tests.rs @@ -0,0 +1,389 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 6's ordered key rewrite, with the scratch database +//! and the skip convention of `m0006_tests`. The tables are created by the DDL +//! `CreateTable` runs, so their primary keys are the production ones. Each +//! test stores legacy keys that differ only by a U+0002 after a U+0001, the +//! shorter one first in the heap, the order a one-statement rewrite fails on. +//! `item_data` is `{}`: the tests check the key columns. + +//! Live checks with the scratch database and the skip convention of +//! `migrations::live_reencode`. The tables are created by the DDL +//! `CreateTable` runs, so their primary keys are the production ones. Each +//! test stores legacy keys that differ only by a U+0002 after a U+0001, +//! the shorter one first in the heap, the order a one-statement rewrite +//! fails on. `item_data` is `{}`: the tests check the key columns. + +use extenddb_core::types::{AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType}; +use extenddb_storage::util::escape_control; +use sqlx::PgPool; + +use super::m0006_escape_control_chars::{BATCH, rewrite_longest_first}; +use super::m0006_tests::{base_conn, run_pool, scratch, skip}; +use crate::PostgresEngine; +use crate::data::key_text::reescape_legacy_composite; + +fn key(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +fn string_attributes(key_schema: &[KeySchemaElement]) -> Vec { + key_schema + .iter() + .map(|k| AttributeDefinition { + attribute_name: k.attribute_name.clone(), + attribute_type: ScalarAttributeType::S, + }) + .collect() +} + +fn json(value: &T) -> serde_json::Value { + serde_json::to_value(value).expect("json") +} + +/// The account, the `tables` row and the data table of table `id`. +async fn table(db: &PgPool, id: &str, key_schema: &[KeySchemaElement]) { + let attributes = string_attributes(key_schema); + sqlx::query( + "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'order') \ + ON CONFLICT DO NOTHING", + ) + .execute(db) + .await + .expect("seed the account"); + sqlx::query( + "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ + table_status, table_arn, table_id) VALUES ('111122223333', $1, $2, $3, 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/' || $1, $1)", + ) + .bind(id) + .bind(json(&key_schema)) + .bind(json(&attributes)) + .execute(db) + .await + .expect("seed the tables row"); + let mut tx = db.begin().await.expect("begin"); + PostgresEngine::create_data_table(&mut tx, id, key_schema, &attributes) + .await + .expect("create the data table"); + tx.commit().await.expect("commit"); +} + +/// The `indexes` row and the data table of GSI `id` on table `table_id`. +async fn index( + db: &PgPool, + table_id: &str, + base_key_schema: &[KeySchemaElement], + id: &str, + key_schema: &[KeySchemaElement], +) { + sqlx::query( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ + projection) VALUES ($1, $2, $2, 'GSI', $3, '{\"ProjectionType\": \"ALL\"}')", + ) + .bind(table_id) + .bind(id) + .bind(json(&key_schema)) + .execute(db) + .await + .expect("seed the indexes row"); + let mut tx = db.begin().await.expect("begin"); + PostgresEngine::create_index_data_table( + &mut tx, + id, + key_schema, + &string_attributes(key_schema), + base_key_schema, + &string_attributes(base_key_schema), + ) + .await + .expect("create the index data table"); + tx.commit().await.expect("commit"); +} + +/// Insert rows into `_ddb_` one at a time, in the order given, which +/// is their heap order in a new table. +async fn insert(db: &PgPool, id: &str, columns: &[&str], rows: &[Vec]) { + let names: Vec = columns.iter().map(|c| format!("\"{c}\"")).collect(); + let params: Vec = (1..=columns.len()).map(|i| format!("${i}")).collect(); + let sql = format!( + "INSERT INTO \"_ddb_{id}\" ({}, item_data) VALUES ({}, '{{}}')", + names.join(", "), + params.join(", ") + ); + for row in rows { + let mut q = sqlx::query(&sql); + for value in row { + q = q.bind(value); + } + q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); + } +} + +fn row(values: &[&str]) -> Vec { + values.iter().map(|v| (*v).to_owned()).collect() +} + +/// Every value of `col` in `_ddb_`, sorted. +async fn column(db: &PgPool, id: &str, col: &str) -> Vec { + let sql = format!("SELECT \"{col}\" FROM \"_ddb_{id}\""); + let mut values: Vec = sqlx::query_scalar(&sql) + .fetch_all(db) + .await + .unwrap_or_else(|e| panic!("{sql}: {e}")); + values.sort(); + values +} + +/// The escape of each legacy text, sorted: what 004 must leave. +fn escaped>(legacy: &[S]) -> Vec { + let mut values: Vec = legacy + .iter() + .map(|t| escape_control(t.as_ref()).into_owned()) + .collect(); + values.sort(); + values +} + +fn rebuilt>(legacy: &[S]) -> Vec { + let mut values: Vec = legacy + .iter() + .map(|t| reescape_legacy_composite(t.as_ref()).expect("a netstring")) + .collect(); + values.sort(); + values +} + +async fn migrate(db: &PgPool) { + run_pool(db).await.expect("004 completes"); +} + +#[tokio::test] +async fn rewrites_a_partition_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_a_partition_key_pair_longest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "tp", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["a\u{1}", "a\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tp", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "tp", "pk").await, escaped(&legacy)); + s.cleanup().await; +} + +#[tokio::test] +async fn rewrites_a_sort_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_a_sort_key_pair_longest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "ts", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["s\u{1}", "s\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|sk| row(&["p", sk])).collect(); + insert(&s.db, "ts", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "ts", "sk_s").await, escaped(&legacy)); + assert_eq!(column(&s.db, "ts", "pk").await, vec!["p", "p"]); + s.cleanup().await; +} + +#[tokio::test] +async fn rebuilds_a_composite_partition_key_pair_longest_first() { + if base_conn().is_none() { + skip("rebuilds_a_composite_partition_key_pair_longest_first"); + return; + } + let s = scratch().await; + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tc", &ks).await; + // h1 = "a\x01" and h1 = "a\x01\x02", h2 = "b": the first one's rebuilt + // text is the second one's legacy text. + let legacy = ["2:a\u{1},1:b,", "3:a\u{1}\u{2},1:b,"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tc", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + let expected = rebuilt(&legacy); + assert_eq!( + expected, + vec!["3:a\u{1}\u{2},1:b,", "4:a\u{1}\u{2}\u{2},1:b,"] + ); + assert_eq!(column(&s.db, "tc", "pk").await, expected); + s.cleanup().await; +} + +#[tokio::test] +async fn rewrites_an_index_base_key_pair_longest_first() { + if base_conn().is_none() { + skip("rewrites_an_index_base_key_pair_longest_first"); + return; + } + let s = scratch().await; + let base = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + table(&s.db, "tb", &base).await; + index(&s.db, "tb", &base, "ib", &[key("g", KeyType::Hash)]).await; + // Two base items with the same index key and base sort key. The base + // table's own pair is the partition key case above; it is left empty + // here so the index table is the one that is checked. + let legacy = ["p\u{1}", "p\u{1}\u{2}"]; + let rows: Vec> = legacy.iter().map(|p| row(&["g", p, "s"])).collect(); + insert(&s.db, "ib", &["pk", "base_pk", "base_sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "ib", "base_pk").await, escaped(&legacy)); + s.cleanup().await; +} + +/// More rows than one batch on both paths: a single-attribute column whose +/// one-statement rewrite fails, and a composite partition key column. The +/// pair of each table is three U+0001 long, so the rows between its two +/// lengths put the longer one in the first batch and the shorter one in the +/// second. Every final text is the escape of its legacy text; a row +/// rewritten twice would hold a longer one. +#[tokio::test] +async fn rewrites_each_row_once_across_batches() { + if base_conn().is_none() { + skip("rewrites_each_row_once_across_batches"); + return; + } + let fillers = 600; + assert!(fillers > BATCH); + let s = scratch().await; + + table( + &s.db, + "tf", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let short = "a\u{1}\u{1}\u{1}"; + let long = "a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2}"; + assert_eq!(escape_control(short), long); + let mut legacy = vec![short.to_owned()]; + legacy.extend((0..fillers).map(|i| format!("k\u{1}{i:04}"))); + legacy.push(long.to_owned()); + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tf", &["pk", "sk_s"], &rows).await; + + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tk", &ks).await; + let short = "4:a\u{1}\u{1}\u{1},1:b,"; + let long = "7:a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2},1:b,"; + assert_eq!(reescape_legacy_composite(short).as_deref(), Some(long)); + let mut composite = vec![short.to_owned()]; + composite.extend((0..fillers).map(|i| format!("5:k\u{1}{i:03},1:b,"))); + composite.push(long.to_owned()); + let rows: Vec> = composite.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tk", &["pk", "sk_s"], &rows).await; + + migrate(&s.db).await; + assert_eq!(column(&s.db, "tf", "pk").await, escaped(&legacy)); + assert_eq!(column(&s.db, "tk", "pk").await, rebuilt(&composite)); + s.cleanup().await; +} + +/// A pair whose byte order is the reverse of its length order: the escape +/// of `a\x01b` is `a\x01\x02b`, which sorts below it, so an order by the +/// text itself, highest first, would rewrite the shorter key first. +#[tokio::test] +async fn rewrites_a_pair_whose_byte_order_is_shortest_first() { + if base_conn().is_none() { + skip("rewrites_a_pair_whose_byte_order_is_shortest_first"); + return; + } + let s = scratch().await; + table( + &s.db, + "tv", + &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], + ) + .await; + let legacy = ["a\u{1}b", "a\u{1}\u{2}b"]; + let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); + insert(&s.db, "tv", &["pk", "sk_s"], &rows).await; + migrate(&s.db).await; + assert_eq!(column(&s.db, "tv", "pk").await, escaped(&legacy)); + s.cleanup().await; +} + +/// An error from a rewrite names the DynamoDB table of the physical table: +/// here a two-HASH table whose `pk` is not a netstring. +#[tokio::test] +async fn an_error_names_the_dynamodb_table() { + if base_conn().is_none() { + skip("an_error_names_the_dynamodb_table"); + return; + } + let s = scratch().await; + let ks = [ + key("h1", KeyType::Hash), + key("h2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + table(&s.db, "tn", &ks).await; + insert(&s.db, "tn", &["pk", "sk_s"], &[row(&["x\u{1}", "s"])]).await; + let err = run_pool(&s.db) + .await + .expect_err("a composite key that is not a netstring"); + let text = err.to_string(); + assert!( + text.contains("_ddb_tn.pk (table \"tn\" of account 111122223333)"), + "{text}" + ); + s.cleanup().await; +} + +#[tokio::test] +async fn a_duplicate_that_remains_is_reported_with_its_key() { + if base_conn().is_none() { + skip("a_duplicate_that_remains_is_reported_with_its_key"); + return; + } + let s = scratch().await; + sqlx::raw_sql( + r#"CREATE TABLE "dup" (pk TEXT COLLATE "C" PRIMARY KEY); + INSERT INTO "dup" VALUES (E'x\x01'), (E'y\x01');"#, + ) + .execute(&s.db) + .await + .expect("seed"); + let mut tx = s.db.begin().await.expect("begin"); + // A rewrite that gives every row one text: the second update fails. + let err = rewrite_longest_first(&mut tx, "\"dup\"", "pk", "TRUE", "dup.pk (t)", |_| { + Ok("z\u{1}".to_owned()) + }) + .await + .expect_err("a duplicate"); + let text = err.to_string(); + assert!(text.starts_with("re-encode dup.pk (t): "), "{text}"); + assert!( + text.contains("(DETAIL: \"Key (pk)=(z\\u{1}) already exists.\")"), + "{text}" + ); + tx.rollback().await.expect("rollback"); + s.cleanup().await; +} diff --git a/crates/storage-postgres/src/migrations/m0006_tests.rs b/crates/storage-postgres/src/migrations/m0006_tests.rs new file mode 100644 index 000000000..cecc77753 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0006_tests.rs @@ -0,0 +1,493 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 6's rewrites against a scratch database. +//! +//! Each test needs `EXTENDDB_TEST_PG_CONNECTION_STRING` (a base URL with no +//! database name, for example `postgresql://postgres@127.0.0.1:5432`), builds +//! a throwaway database, and drops it when it passes. Without the variable +//! every test reports a skip and passes. One database serves as both catalog +//! and data, created by the file bodies of every migration in id order, as +//! `apply_all_migrations` creates the one-database layout; the bodies' +//! rewrites ([`escape_catalog`], [`escape_data`]) then run in one +//! transaction, as the runner runs each body in its store's transaction. The +//! runner, the ledger and the sessions check over two databases are covered +//! by `tests/migrations_golden.rs`. + +use extenddb_storage::migrations::{Body, MigrationError, MigrationId}; +use serde_json::json; +use sqlx::PgPool; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; + +use super::connect::RUNNER_APPLICATION_PREFIX; +use super::m0006_escape_control_chars::{escape_catalog, escape_data}; + +/// The `application_name` of the scratch pools: a runner's, so the sessions +/// check of migration 6 treats them as the migration's own. +pub(crate) fn test_application() -> String { + format!("{RUNNER_APPLICATION_PREFIX}test") +} + +pub(crate) struct Scratch { + pub(crate) db: PgPool, + pub(crate) admin: PgPool, + pub(crate) db_name: String, +} + +impl Scratch { + pub(crate) async fn cleanup(self) { + let Scratch { db, admin, db_name } = self; + db.close().await; + sqlx::query(&format!( + "DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)" + )) + .execute(&admin) + .await + .expect("drop the scratch database"); + admin.close().await; + } +} + +pub(crate) fn base_conn() -> Option { + let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").ok()?; + (!conn.trim().is_empty()).then(|| conn.trim_end_matches('/').to_owned()) +} + +pub(crate) fn skip(test: &str) { + eprintln!( + "SKIP {test}: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is no \ + PostgreSQL to build a scratch database in." + ); +} + +/// A scratch database holding the catalog and the data tables, with the file +/// bodies of every migration applied. +pub(crate) async fn scratch() -> Scratch { + let base = base_conn().expect("caller checks base_conn() first"); + let db_name = format!("eddb_esc_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); + let admin = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/postgres")) + .await + .expect("connect to the postgres maintenance database"); + sqlx::query(&format!("CREATE DATABASE \"{db_name}\"")) + .execute(&admin) + .await + .expect("create the scratch database"); + let db = PgPoolOptions::new() + .max_connections(2) + .connect_with( + format!("{base}/{db_name}") + .parse::() + .expect("scratch connection string") + .application_name(&test_application()), + ) + .await + .expect("connect to the scratch database"); + for id in MigrationId::ALL { + for body in super::migration(id).bodies() { + if let Body::File { name, text } = &body.body { + sqlx::raw_sql(text) + .execute(&db) + .await + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + } + Scratch { db, admin, db_name } +} + +/// Run the catalog body's and the data body's rewrites on the connection of +/// `one` (a pool of one connection to the scratch database), in one +/// transaction that commits when both succeed, reading the catalog through +/// `catalog`; the notes of both, catalog first. +pub(crate) async fn run_on(catalog: &PgPool, one: &PgPool) -> Result, MigrationError> { + let mut conn = one.acquire().await.expect("acquire the connection"); + sqlx::raw_sql("BEGIN") + .execute(&mut *conn) + .await + .expect("BEGIN"); + let result = async { + let mut notes = escape_catalog(&mut conn).await?; + notes.extend(escape_data(catalog, &mut conn).await?); + Ok(notes) + } + .await; + let end = if result.is_ok() { "COMMIT" } else { "ROLLBACK" }; + sqlx::raw_sql(end).execute(&mut *conn).await.expect(end); + result +} + +/// [`run_on`] through a connection of its own to the database `db` reaches. +pub(crate) async fn run_pool(db: &PgPool) -> Result, MigrationError> { + let one = PgPoolOptions::new() + .max_connections(1) + .connect_with((*db.connect_options()).clone()) + .await + .expect("connect a second session"); + let result = run_on(db, &one).await; + one.close().await; + result +} + +/// [`run_pool`] on the scratch database. +pub(crate) async fn run(s: &Scratch) -> Result, MigrationError> { + run_pool(&s.db).await +} + +/// Seed a data table, an index table, `gsi_pending`, `stream_records`, and +/// `backup_items` with three row kinds: raw U+0001 in key columns and +/// inside jsonb strings and object keys, the literal six-character text +/// backslash-u-0001 inside a jsonb string, and plain rows. +pub(crate) async fn seed(db: &PgPool) { + let ks = json!([ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ]); + let ad = json!([ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"} + ]); + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES ($1, $2)") + .bind("111122223333") + .bind("esc-check") + .execute(db) + .await + .expect("seed the account row"); + sqlx::query( + "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ + table_status, table_arn, table_id) \ + VALUES ($1, 't', $2, $3, 'ACTIVE', \ + 'arn:aws:dynamodb:us-east-1:111122223333:table/t', 't1')", + ) + .bind("111122223333") + .bind(&ks) + .bind(&ad) + .execute(db) + .await + .expect("seed the tables row"); + sqlx::query( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ + projection) VALUES ('t1', 'i1', 'gsi1', 'GSI', $1, $2)", + ) + .bind(json!([{"AttributeName": "gpk", "KeyType": "HASH"}])) + .bind(json!({"ProjectionType": "ALL"})) + .execute(db) + .await + .expect("seed the indexes row"); + + sqlx::raw_sql( + r#"CREATE TABLE "_ddb_t1" ( + pk TEXT COLLATE "C" NOT NULL, + sk_s TEXT COLLATE "C", + sk_n NUMERIC, + sk_b BYTEA, + item_data JSONB NOT NULL, + PRIMARY KEY (pk, sk_s) + ); + CREATE TABLE "_ddb_i1" ( + pk TEXT COLLATE "C" NOT NULL, + sk_s TEXT COLLATE "C", + sk_n NUMERIC, + sk_b BYTEA, + base_pk TEXT COLLATE "C" NOT NULL, + base_sk_s TEXT COLLATE "C", + base_sk_n NUMERIC, + base_sk_b BYTEA, + item_data JSONB NOT NULL, + PRIMARY KEY (pk, base_pk, base_sk_s) + );"#, + ) + .execute(db) + .await + .expect("create the physical data and index tables"); + + for (pk, sk, item) in [ + ( + "a\u{1}b", + "s\u{1}", + json!({"pk": {"S": "a\u{1}b"}, "k\u{1}": {"S": "v\u{1}"}}), + ), + ("lit", "s", json!({"note": {"S": "x\\u0001y"}})), + ("plain", "s", json!({"pk": {"S": "plain"}})), + ] { + sqlx::query("INSERT INTO \"_ddb_t1\" (pk, sk_s, item_data) VALUES ($1, $2, $3)") + .bind(pk) + .bind(sk) + .bind(item) + .execute(db) + .await + .expect("seed a data table row"); + } + for (pk, sk, base_pk, base_sk, item) in [ + ( + "g\u{1}", + "gs\u{1}", + "a\u{1}b", + "s\u{1}", + json!({"gpk": {"S": "g\u{1}"}}), + ), + ("zz", "zs", "plain", "s", json!({"gpk": {"S": "zz"}})), + ] { + sqlx::query( + "INSERT INTO \"_ddb_i1\" (pk, sk_s, base_pk, base_sk_s, item_data) \ + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(pk) + .bind(sk) + .bind(base_pk) + .bind(base_sk) + .bind(item) + .execute(db) + .await + .expect("seed an index table row"); + } + + for (new_item, context) in [ + (json!({"pk": {"S": "a\u{1}b"}}), json!({"k\u{1}": 1})), + (json!({"pk": {"S": "p"}}), json!({"k": 1})), + ] { + sqlx::query( + "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ + index_context) VALUES ('t1', 0, NULL, $1, $2)", + ) + .bind(new_item) + .bind(context) + .execute(db) + .await + .expect("seed a gsi_pending row"); + } + + sqlx::query( + "INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \ + VALUES ('shard-1', 't1', '1')", + ) + .execute(db) + .await + .expect("seed the stream shard"); + for (seq, record) in [ + ("1", json!({"Keys": {"pk": {"S": "a\u{1}b"}}})), + ("2", json!({"Keys": {"pk": {"S": "p"}}})), + ] { + sqlx::query( + "INSERT INTO stream_records (shard_id, sequence_number, table_id, event_name, \ + record_data) VALUES ('shard-1', $1, 't1', 'INSERT', $2)", + ) + .bind(seq) + .bind(record) + .execute(db) + .await + .expect("seed a stream record"); + } + + sqlx::query( + "INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, \ + key_schema, attribute_definitions) \ + VALUES ('arn:aws:dynamodb:us-east-1:111122223333:table/t/backup/b1', 'b1', 't1', \ + 't', '111122223333', $1, $2)", + ) + .bind(&ks) + .bind(&ad) + .execute(db) + .await + .expect("seed the backups row"); + for (pk, sk, item) in [ + ("p\u{1}", Some("s\u{1}"), json!({"pk": {"S": "p\u{1}"}})), + ("plain", None, json!({"pk": {"S": "plain"}})), + ] { + sqlx::query( + "INSERT INTO backup_items (backup_arn, pk, sk, item_data) \ + VALUES ('arn:aws:dynamodb:us-east-1:111122223333:table/t/backup/b1', $1, $2, $3)", + ) + .bind(pk) + .bind(sk) + .bind(item) + .execute(db) + .await + .expect("seed a backup item"); + } +} + +#[tokio::test] +async fn reencodes_legacy_rows() { + if base_conn().is_none() { + skip("reencodes_legacy_rows"); + return; + } + let s = scratch().await; + seed(&s.db).await; + + let notes = run(&s).await.expect("run migration 6"); + assert_eq!( + notes, + vec![ + "backup_items: 3 row update(s)", + "_ddb_t1 (table \"t\" of account 111122223333): 3 row update(s)", + "_ddb_i1 (index \"gsi1\" of table \"t\" of account 111122223333): 5 row update(s)", + "gsi_pending: 2 row update(s)", + "stream_records: 1 row update(s)", + ] + ); + + // Data table: raw U+0001 became U+0001 U+0002 in the key columns and + // inside every jsonb string and object key; the literal-backslash row + // and the plain row are byte-identical. + let rows: Vec<(String, String, serde_json::Value)> = + sqlx::query_as("SELECT pk, sk_s, item_data FROM \"_ddb_t1\" ORDER BY pk") + .fetch_all(&s.db) + .await + .expect("read the data table"); + assert_eq!( + rows, + vec![ + ( + "a\u{1}\u{2}b".to_owned(), + "s\u{1}\u{2}".to_owned(), + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), + ), + ( + "lit".to_owned(), + "s".to_owned(), + json!({"note": {"S": "x\\u0001y"}}), + ), + ( + "plain".to_owned(), + "s".to_owned(), + json!({"pk": {"S": "plain"}}), + ), + ] + ); + + // Index table: pk, sk_s, base_pk, base_sk_s and item_data all re-encoded. + let rows: Vec<(String, String, String, String, serde_json::Value)> = sqlx::query_as( + "SELECT pk, sk_s, base_pk, base_sk_s, item_data FROM \"_ddb_i1\" ORDER BY pk", + ) + .fetch_all(&s.db) + .await + .expect("read the index table"); + assert_eq!( + rows, + vec![ + ( + "g\u{1}\u{2}".to_owned(), + "gs\u{1}\u{2}".to_owned(), + "a\u{1}\u{2}b".to_owned(), + "s\u{1}\u{2}".to_owned(), + json!({"gpk": {"S": "g\u{1}\u{2}"}}), + ), + ( + "zz".to_owned(), + "zs".to_owned(), + "plain".to_owned(), + "s".to_owned(), + json!({"gpk": {"S": "zz"}}), + ), + ] + ); + + // gsi_pending: NULL old_item stays NULL, the raw row is re-encoded in + // both jsonb columns, the plain row is untouched. + let rows: Vec<( + Option, + serde_json::Value, + serde_json::Value, + )> = sqlx::query_as("SELECT old_item, new_item, index_context FROM gsi_pending ORDER BY id") + .fetch_all(&s.db) + .await + .expect("read gsi_pending"); + assert_eq!( + rows, + vec![ + ( + None, + json!({"pk": {"S": "a\u{1}\u{2}b"}}), + json!({"k\u{1}\u{2}": 1}), + ), + (None, json!({"pk": {"S": "p"}}), json!({"k": 1})), + ] + ); + + // stream_records. + let rows: Vec<(serde_json::Value,)> = + sqlx::query_as("SELECT record_data FROM stream_records ORDER BY sequence_number") + .fetch_all(&s.db) + .await + .expect("read stream_records"); + assert_eq!( + rows, + vec![ + (json!({"Keys": {"pk": {"S": "a\u{1}\u{2}b"}}}),), + (json!({"Keys": {"pk": {"S": "p"}}}),), + ] + ); + + // backup_items, including the NULL sk row. + let rows: Vec<(String, Option, serde_json::Value)> = + sqlx::query_as("SELECT pk, sk, item_data FROM backup_items ORDER BY pk") + .fetch_all(&s.db) + .await + .expect("read backup_items"); + assert_eq!( + rows, + vec![ + ( + "p\u{1}\u{2}".to_owned(), + Some("s\u{1}\u{2}".to_owned()), + json!({"pk": {"S": "p\u{1}\u{2}"}}), + ), + ("plain".to_owned(), None, json!({"pk": {"S": "plain"}}),), + ] + ); + + s.cleanup().await; +} + +/// The jsonb candidate predicate must not depend on the session's +/// standard_conforming_strings: with it off, a plain '\u0001' literal is a +/// single 0x01 byte that never appears in jsonb text and matches nothing, +/// so every jsonb row would be skipped while the migration recorded itself. +#[tokio::test] +async fn reencodes_jsonb_rows_with_standard_conforming_strings_off() { + if base_conn().is_none() { + skip("reencodes_jsonb_rows_with_standard_conforming_strings_off"); + return; + } + let s = scratch().await; + seed(&s.db).await; + + let base = base_conn().unwrap(); + let scs_off = PgPoolOptions::new() + .max_connections(1) + .after_connect(|conn, _| { + Box::pin(async move { + sqlx::Executor::execute(&mut *conn, "SET standard_conforming_strings = off") + .await?; + Ok(()) + }) + }) + .connect_with( + format!("{base}/{}", s.db_name) + .parse::() + .unwrap() + .application_name(&test_application()), + ) + .await + .expect("connect with standard_conforming_strings off"); + + run_on(&s.db, &scs_off).await.expect("run migration 6"); + + let (pk, sk, item): (String, String, serde_json::Value) = + sqlx::query_as("SELECT pk, sk_s, item_data FROM \"_ddb_t1\" WHERE pk LIKE 'a%'") + .fetch_one(&s.db) + .await + .unwrap(); + assert_eq!(pk, "a\u{1}\u{2}b"); + assert_eq!(sk, "s\u{1}\u{2}"); + assert_eq!( + item, + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), + "jsonb rows must be re-encoded whatever the session setting" + ); + scs_off.close().await; + s.cleanup().await; +} diff --git a/crates/storage-postgres/src/migrations/mod.rs b/crates/storage-postgres/src/migrations/mod.rs index 740c3469a..c1bafcfa5 100644 --- a/crates/storage-postgres/src/migrations/mod.rs +++ b/crates/storage-postgres/src/migrations/mod.rs @@ -35,6 +35,9 @@ mod m0003_sort_key_definitions; #[rustfmt::skip] #[allow(clippy::all, deprecated)] mod m0004_index_table_base_key; +#[rustfmt::skip] +#[allow(clippy::all, deprecated)] +mod m0006_escape_control_chars; mod postcheck; mod registrar; mod rows; @@ -127,6 +130,24 @@ pub fn migration(id: MigrationId) -> Migration { "0005_drop_continuous_backups.sql" )], }, + MigrationId::EscapeControlChars => Migration::Applies { + kind: Kind::Breaking, + // The escape is not idempotent: running the bodies again would + // escape the strings written through the API since they ran. + convergent: false, + bodies: vec![ + StoreBody::code( + StoreKind::Catalog, + &m0006_escape_control_chars::EscapeBackupItems, + m0006_escape_control_chars::SOURCE, + ), + StoreBody::code( + StoreKind::Data, + &m0006_escape_control_chars::EscapeDataRows, + m0006_escape_control_chars::SOURCE, + ), + ], + }, } } @@ -148,7 +169,8 @@ pub(crate) const fn runs_in(id: MigrationId) -> RunsIn { MigrationId::Baseline | MigrationId::ResourceTagConditionKeys | MigrationId::SortKeyDefinitions - | MigrationId::DropContinuousBackups => RunsIn::Transaction, + | MigrationId::DropContinuousBackups + | MigrationId::EscapeControlChars => RunsIn::Transaction, MigrationId::IndexTableBaseKey => RunsIn::Autocommit, } } @@ -174,6 +196,9 @@ pub struct PostgresTarget { pub data_connection_row: Option, /// Timeout for each connection attempt. pub(crate) connect_timeout: Duration, + /// Whether a run leaves out migration 6's check for other sessions + /// ([`PostgresTarget::with_other_sessions_allowed`]). + pub(crate) other_sessions_allowed: bool, } impl PostgresTarget { @@ -187,9 +212,21 @@ impl PostgresTarget { data_database_given: false, data_connection_row: None, connect_timeout: Duration::from_secs(10), + other_sessions_allowed: false, } } + /// Leave out migration 6's check for other sessions on the databases it + /// rewrites, for a test harness whose own sessions hold its scratch + /// databases (lock holders, observers). Every path an operator runs keeps + /// the check, apart from `EXTENDDB_MIGRATE_IGNORE_CONNECTIONS`. + #[cfg(any(feature = "test-util", feature = "test-hooks"))] + #[must_use] + pub fn with_other_sessions_allowed(mut self) -> Self { + self.other_sessions_allowed = true; + self + } + /// Mark the data database as given on the command line. #[must_use] pub fn with_given_data_database(mut self) -> Self { @@ -351,8 +388,9 @@ pub async fn apply_all_migrations( return Ok(()); } let data_database = data_options.get_database().unwrap_or("postgres").to_owned(); + // The harness's own pools hold the scratch databases. migrate( - &PostgresTarget::new(catalog_options, data_database), + &PostgresTarget::new(catalog_options, data_database).with_other_sessions_allowed(), "test", Duration::ZERO, ) @@ -361,5 +399,13 @@ pub async fn apply_all_migrations( .map_err(|e| format!("{e:?}")) } +#[cfg(test)] +mod m0006_guard_tests; +#[cfg(test)] +mod m0006_keys_tests; +#[cfg(test)] +mod m0006_order_tests; +#[cfg(test)] +mod m0006_tests; #[cfg(test)] mod tests; diff --git a/crates/storage-postgres/tests/fixtures/golden/0006_escape_control_chars.txt b/crates/storage-postgres/tests/fixtures/golden/0006_escape_control_chars.txt new file mode 100644 index 000000000..fafe378b2 --- /dev/null +++ b/crates/storage-postgres/tests/fixtures/golden/0006_escape_control_chars.txt @@ -0,0 +1,66 @@ +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +catalog notes: +backup_items: 20 row update(s) +data notes: +_ddb_T:seed_tbl (table "seed_tbl" of account 123456789012): 30 row update(s) +_ddb_I:seed_tbl/lsi1 (index "lsi1" of table "seed_tbl" of account 123456789012): 40 row update(s) +_ddb_I:seed_tbl/gsi1 (index "gsi1" of table "seed_tbl" of account 123456789012): 50 row update(s) diff --git a/crates/storage-postgres/tests/migrations_golden.rs b/crates/storage-postgres/tests/migrations_golden.rs index 47d36bb25..73f6e9b21 100644 --- a/crates/storage-postgres/tests/migrations_golden.rs +++ b/crates/storage-postgres/tests/migrations_golden.rs @@ -12,7 +12,7 @@ use std::fmt::Write as _; use std::time::Duration; use extenddb_storage::migrations::{CatalogStatus, MigrationError, MigrationId, Runner}; -use extenddb_storage_postgres::migrations::{PostgresMigrations, migrate}; +use extenddb_storage_postgres::migrations::{PostgresMigrations, PostgresTarget, migrate}; use migrations_support::{ACCOUNT, LATEST, Scratch, base_conn, id_names, skip}; use sqlx::PgPool; @@ -422,3 +422,217 @@ async fn migration_4_adds_the_base_key_index_and_skips_what_it_cannot_reach() { catalog.close().await; data.close().await; } + +/// The physical tables of `seed_tbl` and their text key columns. +async fn seed_tbl_tables(catalog: &PgPool) -> Vec<(String, &'static [&'static str])> { + let table: String = + sqlx::query_scalar("SELECT table_id FROM tables WHERE table_name = 'seed_tbl'") + .fetch_one(catalog) + .await + .unwrap(); + let indexes: Vec = + sqlx::query_scalar("SELECT index_id FROM indexes WHERE table_id = $1 ORDER BY index_name") + .bind(&table) + .fetch_all(catalog) + .await + .unwrap(); + let mut tables: Vec<(String, &'static [&'static str])> = + vec![(format!("_ddb_{table}"), &["pk", "sk_s"])]; + for index in indexes { + tables.push(( + format!("_ddb_{index}"), + &["pk", "sk_s", "base_pk", "base_sk_s"], + )); + } + tables +} + +/// The attribute every legacy row gets: a name and a value holding U+0001 +/// as an earlier release stored it, the value followed by U+0002. +const LEGACY_NOTE: &str = "item_data || jsonb_build_object('note' || chr(1), \ + jsonb_build_object('S', 'v' || chr(1) || chr(2)))"; + +/// Each row of `table` as `
pk=.. sk=.. `, with the +/// strings in Rust's escaped form, so a control character is visible. +async fn rows_of(pool: &PgPool, table: &str, label: &str, key: [&str; 2]) -> Vec { + let rows: Vec<(String, Option, Option)> = sqlx::query_as(&format!( + "SELECT {}, {}, (SELECT string_agg(key || '=' || (value->>'S'), ',' ORDER BY key) \ + FROM jsonb_each(item_data) WHERE key LIKE 'note%') FROM \"{table}\"", + key[0], key[1] + )) + .fetch_all(pool) + .await + .unwrap(); + rows.into_iter() + .map(|(pk, sk, note)| format!("{label} pk={pk:?} sk={sk:?} {note:?}")) + .collect() +} + +/// Migration 6 on the 0.1.14 fixture whose strings an earlier release +/// stored with a raw U+0001: in the key columns of `seed_tbl`'s table, GSI +/// and LSI, in their documents, and in the backup's `backup_items`. +#[tokio::test] +async fn migration_6_escapes_the_strings_an_earlier_release_stored() { + let Some(base) = base_conn() else { + return skip("golden 6"); + }; + let s = Scratch::new(&base, "pgm_g6").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::DropContinuousBackups).await; + let catalog = s.catalog().await; + let data = s.data().await; + let tables = seed_tbl_tables(&catalog).await; + for (table, columns) in &tables { + let keys: Vec = columns + .iter() + .map(|c| format!("{c} = {c} || chr(1)")) + .collect(); + sqlx::query(&format!( + "UPDATE \"{table}\" SET {}, item_data = {LEGACY_NOTE}", + keys.join(", ") + )) + .execute(&data) + .await + .unwrap(); + } + sqlx::query(&format!( + "UPDATE backup_items SET pk = pk || chr(1), sk = sk || chr(1), item_data = {LEGACY_NOTE}" + )) + .execute(&catalog) + .await + .unwrap(); + // A status read does not look for other sessions: this test's own are + // open. + assert_eq!(s.status().await.label(), "Behind"); + catalog.close().await; + data.close().await; + s.migrate_through(MigrationId::EscapeControlChars).await; + assert_eq!(s.status().await, CatalogStatus::Current { version: LATEST }); + + let catalog = s.catalog().await; + let data = s.data().await; + let names = id_names(&catalog).await; + let mut lines = Vec::new(); + for (table, columns) in &tables { + let mut label = table.clone(); + for (id, name) in &names { + label = label.replace(id.as_str(), name); + } + let mut rows = rows_of(&data, table, &label, [columns[0], columns[1]]).await; + if columns.len() > 2 { + // An index row also names its base item. + rows = rows_of( + &data, + table, + &format!("{label} base"), + ["base_pk", "base_sk_s"], + ) + .await + .into_iter() + .chain(rows) + .collect(); + } + lines.extend(rows); + } + lines.extend(rows_of(&catalog, "backup_items", "backup_items", ["pk", "sk"]).await); + lines.sort(); + let mut out = lines.join("\n"); + for (pool, store) in [(&catalog, "catalog"), (&data, "data")] { + let mut note = notes(pool, 6).await; + for (id, name) in &names { + note = note.replace(id.as_str(), name); + } + write!(out, "\n{store} notes:\n{note}").unwrap(); + } + out.push('\n'); + golden("0006_escape_control_chars.txt", &out); + catalog.close().await; + data.close().await; +} + +/// The id-6 rows of the ledger of the database `pool` reaches. +async fn ledger_rows_of_6(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM extenddb_migrations WHERE id = 6") + .fetch_one(pool) + .await + .unwrap() +} + +/// While another session holds the data database of a store with tables, +/// `migrate --yes` stops with exit 5 before its first write, naming the +/// session, and migrates once the session is gone. +#[tokio::test] +async fn migration_6_stops_before_any_write_while_another_session_holds_the_data() { + let Some(base) = base_conn() else { + return skip("migration 6 sessions check"); + }; + let s = Scratch::new(&base, "pgm_g6s").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::DropContinuousBackups).await; + // A server of an earlier release, still connected. + let server = migrations_support::pool(&s.data_url(), 1).await; + sqlx::query("SELECT 1").execute(&server).await.unwrap(); + // The preview runs beside it. + assert_eq!(s.status().await.label(), "Behind"); + let err = migrate( + &s.target_checking_sessions(), + "test", + Duration::from_secs(5), + ) + .await + .expect_err("refused"); + assert_eq!(err.exit_code(), 5, "{err:?}"); + let text = format!("{err:?}"); + assert!( + text.contains(&format!( + "1 other session(s) hold the data database {}", + s.data_name + )), + "{text}" + ); + let catalog = s.catalog().await; + let data = s.data().await; + assert_eq!( + ledger_rows_of_6(&catalog).await, + 0, + "the refused run wrote the catalog ledger" + ); + assert_eq!( + ledger_rows_of_6(&data).await, + 0, + "the refused run wrote the data ledger" + ); + catalog.close().await; + data.close().await; + server.close().await; + // Connection strings that name an application, as an operator's can: the + // runner names its own sessions over them, so the check does not count + // them. + let catalog = s.catalog().await; + sqlx::query("UPDATE settings SET value = $1 WHERE key = 'data_database_connection_string'") + .bind(format!("{}?application_name=psql", s.data_url())) + .execute(&catalog) + .await + .unwrap(); + catalog.close().await; + let named = || { + PostgresTarget::new( + format!("{}?application_name=psql", s.catalog_url()) + .parse() + .unwrap(), + &s.data_name, + ) + }; + // PostgreSQL removes a closed session from pg_stat_activity a moment + // after the close returns. + let mut result = migrate(&named(), "test", Duration::from_secs(5)).await; + for _ in 0..50 { + if result.is_ok() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + result = migrate(&named(), "test", Duration::from_secs(5)).await; + } + result.expect("migrate once the session is gone"); + assert_eq!(s.status().await, CatalogStatus::Current { version: LATEST }); +} diff --git a/crates/storage-postgres/tests/migrations_support/mod.rs b/crates/storage-postgres/tests/migrations_support/mod.rs index 31646f90e..752ab2c85 100644 --- a/crates/storage-postgres/tests/migrations_support/mod.rs +++ b/crates/storage-postgres/tests/migrations_support/mod.rs @@ -214,7 +214,17 @@ impl Scratch { } /// The runner's target, which writes the data connection rows as `init`. + /// The tests hold sessions of their own on the scratch databases (lock + /// holders, observers), so the target leaves out migration 6's check for + /// other sessions; [`Scratch::target_checking_sessions`] keeps it. pub fn target(&self) -> PostgresTarget { + self.target_checking_sessions() + .with_other_sessions_allowed() + } + + /// [`Scratch::target`] with migration 6's check for other sessions, as + /// `extenddb migrate --yes` runs it. + pub fn target_checking_sessions(&self) -> PostgresTarget { PostgresTarget::new(self.options(), &self.data_name) .with_data_connection_row(self.data_url()) } diff --git a/crates/storage-sqlite/src/migrations/mod.rs b/crates/storage-sqlite/src/migrations/mod.rs index 06647fbb4..245e28ccc 100644 --- a/crates/storage-sqlite/src/migrations/mod.rs +++ b/crates/storage-sqlite/src/migrations/mod.rs @@ -106,6 +106,10 @@ pub fn migration(id: MigrationId) -> Migration { "0005_drop_continuous_backups.sql" )], }, + MigrationId::EscapeControlChars => Migration::NotApplicable( + "SQLite stores U+0000 in strings as written, so its stored form of strings does not \ + change", + ), } } diff --git a/crates/storage/src/migrations/registry.rs b/crates/storage/src/migrations/registry.rs index dc426fd18..fc70c947f 100644 --- a/crates/storage/src/migrations/registry.rs +++ b/crates/storage/src/migrations/registry.rs @@ -67,6 +67,10 @@ migration_ids! { /// it. DropContinuousBackups = 5, "drop_continuous_backups", "drop the continuous_backups table, which no request reads or writes since #335"; + /// Re-encodes the strings a PostgreSQL store holds from an earlier + /// release into the escape that stores U+0000 (#364). + EscapeControlChars = 6, "escape_control_chars", + "re-encode the strings PostgreSQL stores so that they can hold U+0000"; } /// Highest id that has shipped in a release. Bodies at or below it are frozen: diff --git a/crates/storage/src/util/control_chars.rs b/crates/storage/src/util/control_chars.rs index 07db91310..e1d708d9c 100644 --- a/crates/storage/src/util/control_chars.rs +++ b/crates/storage/src/util/control_chars.rs @@ -35,8 +35,9 @@ //! it is returned as a literal U+0001. Rows written before this escape existed //! can hold such a character, and a lenient decoder reads them unchanged. A //! legacy string that contained U+0001 immediately followed by U+0001 or U+0002 -//! would decode differently; the operator migration `004_escape_control_chars` -//! re-encodes such rows so that case cannot arise after it has run. +//! would decode differently; on PostgreSQL, catalog migration 6, +//! `escape_control_chars`, re-encodes such rows so that case cannot arise after +//! it has run. use std::borrow::Cow; diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index 4236e76d5..d8d59976b 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -422,8 +422,8 @@ The PostgreSQL backend uses two categories of tables: index and sweep, vector search filters) uses the escaped name. The MongoDB backend applies the same escape to BSON field names only, since BSON string values are length-prefixed and hold the byte as is. Rows written before the - escape existed are re-encoded once by the operator migration - `004_escape_control_chars` (see the upgrade manual). + escape existed are re-encoded once on PostgreSQL by catalog migration 6, + `escape_control_chars` (see the upgrade manual). - **GSI tables**: GSI tables include base table primary key columns (`base_pk`, `base_sk_*`) as actual SQL columns (not just inside `item_data` JSONB). This diff --git a/docs/getting-started.md b/docs/getting-started.md index 09d382c2f..8d4154351 100755 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -269,7 +269,7 @@ Config: extenddb.toml Catalog database: extenddb_catalog --- Checking catalog migrations... - OK: Current: the catalog is at migration 5 + OK: Current: the catalog is at migration 6 --- Checking catalog connection... OK: Connected to catalog. --- Checking data database... @@ -287,7 +287,7 @@ extenddb runs as a daemon (background process) and logs to syslog. On startup it ```bash ./target/release/extenddb serve --config extenddb.toml -# extenddb 0.1.14 (catalog migration 5) starting on 127.0.0.1:18443 +# extenddb 0.1.14 (catalog migration 6) starting on 127.0.0.1:18443 # storage: postgres (postgresql://extenddb:***@localhost:5432/extenddb_catalog) ``` @@ -1366,7 +1366,7 @@ Each runner requires its tools to be installed. The runner checks prerequisites ```bash ./target/release/extenddb version # extenddb 0.1.14 -# catalog migration 5 (postgres) +# catalog migration 6 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z ``` diff --git a/docs/manuals/04-quickstart-setup-guide.md b/docs/manuals/04-quickstart-setup-guide.md index 6e8339c6b..08333d9dd 100755 --- a/docs/manuals/04-quickstart-setup-guide.md +++ b/docs/manuals/04-quickstart-setup-guide.md @@ -130,7 +130,7 @@ Check the version: ```bash ./target/release/extenddb version # extenddb 0.1.14 -# catalog migration 5 (postgres) +# catalog migration 6 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z ``` @@ -172,7 +172,7 @@ Config: extenddb.toml Catalog database: extenddb_catalog --- Checking catalog migrations... - OK: Current: the catalog is at migration 5 + OK: Current: the catalog is at migration 6 --- Checking catalog connection... OK: Connected to catalog. --- Checking data database... diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 04e3111a6..95424ba58 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -4,7 +4,7 @@ ## Current Status -This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 5, which `extenddb migrate --list` prints. **Every deployment created by a 0.1.x release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every 0.1.x release to the v1.0 schema, and migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)). +This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 6, which `extenddb migrate --list` prints. **Every deployment created by a 0.1.x release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every 0.1.x release to the v1.0 schema, and migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)). On PostgreSQL, migration 6 re-encodes the strings an earlier release stored and runs only with every server of an earlier release stopped (see [U+0000 in strings on PostgreSQL and MongoDB](#u0000-in-strings-on-postgresql-and-mongodb-catalog-migration-6)). A backup that a 0.1.x release took can restore without its global and local secondary indexes: a SQLite backup taken by 0.1.14 records only the table's key schema and attribute definitions, and its restore creates the table with its items and no index. Take a new backup of each table after upgrading to v1.0, and keep the 0.1.x backups for their items only. @@ -39,7 +39,7 @@ Exit status 6 means the migration lock, or a running server, was still held when `verify` also checks the connection to the data database. When that check fails, `verify` exits 1 on a Behind catalog instead of 3, because `migrate --yes` cannot apply the pending migrations while the data database cannot be reached. It still exits 4 or 5 for the statuses that need a person. -A migration is additive when the previous release serves the catalog correctly with it applied, and breaking otherwise. Migrations 1 to 5 are breaking: do not run a 0.1.x server against a migrated catalog. A 0.1.x binary that writes to a migrated catalog (its `migrate --yes`, or a SQLite dev server) leaves it WrittenByOlderRelease. `migrate --yes --reconverge` repairs it by running the convergent migrations again. Migration 2, which rewrites stored policies, is not convergent: the repair skips it and prints a line that says so (see the v0.1.14 notes below). +A migration is additive when the previous release serves the catalog correctly with it applied, and breaking otherwise. Migrations 1 to 6 are breaking: do not run a 0.1.x server against a migrated catalog. A 0.1.x binary that writes to a migrated catalog (its `migrate --yes`, or a SQLite dev server) leaves it WrittenByOlderRelease. `migrate --yes --reconverge` repairs it by running the convergent migrations again. Migration 2, which rewrites stored policies, and migration 6, which re-encodes stored strings on PostgreSQL, are not convergent: the repair skips them and prints a line for each that says so (see the v0.1.14 notes below). ## Writing a New Migration @@ -311,6 +311,24 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### U+0000 in strings on PostgreSQL and MongoDB (catalog migration 6) + +DynamoDB accepts U+0000 anywhere a string appears. The PostgreSQL backend now stores every string through an order-preserving escape: U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002, and every other character as it is, so a string that holds neither character is stored as before. The MongoDB backend applies the same escape to BSON field names (attribute names and map keys); BSON string values already held U+0000. SQLite and Cassandra store the character as written, and their stored data does not change. + +**Migration 6, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 6 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), `gsi_pending` and `stream_records`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. + +Upgrade in this order: + +1. Stop every ExtendDB server that uses the deployment, including the servers of earlier releases. +2. Run `extenddb migrate --yes` with the new binary. +3. Start the new servers. + +The migration cannot tell a row a running server writes from a legacy row, so it runs only while no server writes. `migrate --yes` waits for the servers that hold the serving key, and a server of a 0.1.x release does not hold it. While the catalog lists a table or `gsi_pending` or `stream_records` holds a row, migration 6 therefore stops the run before its first write when any other session is connected to the data database, and while `backup_items` holds a row it does the same for the catalog database: `migrate` names each such session by role, client address and application name, and exits 5. The migrator's own sessions and read-only status sessions are not counted. Stop those sessions and run again. If the only other sessions are idle connections that a connection pooler holds, set `EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1` to skip the check. The preview, `extenddb migrate` without `--yes`, does not look for sessions, so it runs beside a server and reports migration 6 as pending. + +A server of this release refuses a deployment where migration 6 is pending, and `extenddb init` applies it to a new deployment, which has nothing to rewrite. The migration is breaking and not convergent: a server of an earlier release refuses the migrated catalog, `migrate --yes --reconverge` skips migration 6, and going back to an earlier release means restoring both databases from the backups taken before the upgrade. A 0.1.x binary given a restored catalog and a migrated data database would read escaped strings as data. + +**MongoDB.** The MongoDB backend has no migration for this change; its ledger records migration 6 as not applicable. Field names an earlier release wrote are stored raw. A name that holds a lone U+0001 reads back unchanged, as do all string values and all key strings; a name that holds U+0001 immediately followed by U+0001 or U+0002 reads back with that pair decoded as U+0000 or U+0001. Deployments whose attribute names never contain U+0001 are not affected. + ### v0.1.15: Point-in-time recovery is reported as unsupported (catalog migration required) **What changed.** `UpdateContinuousBackups` no longer accepts an enable request, and `DescribeContinuousBackups` no longer reports point-in-time recovery `ENABLED` with a 35-day window. Point-in-time recovery is reported as unsupported: describe answers `PointInTimeRecoveryStatus: DISABLED`, an enable request returns `ContinuousBackupsUnavailableException`, and `RestoreTableToPointInTime` checks the source table and then returns `PointInTimeRecoveryUnavailableException`. A table that does not exist is `TableNotFoundException` on all three operations, where `DescribeContinuousBackups` and `UpdateContinuousBackups` answered `ResourceNotFoundException`, and `UpdateContinuousBackups` without `PointInTimeRecoverySpecification` is a `ValidationException`, where it was taken as disabling. See [Differences from DynamoDB](../differences-from-dynamodb.md) for the full surface. The catalog migration removes the storage of a per-table enable flag that only the description read. diff --git a/docs/manuals/08-install-linux.md b/docs/manuals/08-install-linux.md index 928ba957d..2b868522e 100755 --- a/docs/manuals/08-install-linux.md +++ b/docs/manuals/08-install-linux.md @@ -118,7 +118,7 @@ Expected: ``` === extenddb verify === ... - OK: Current: the catalog is at migration 5 + OK: Current: the catalog is at migration 6 ... === HEALTHY: All checks passed === ``` diff --git a/docs/manuals/09-install-macos.md b/docs/manuals/09-install-macos.md index 85ba0f1e8..b1ca6de2d 100755 --- a/docs/manuals/09-install-macos.md +++ b/docs/manuals/09-install-macos.md @@ -96,7 +96,7 @@ Expected: ``` === extenddb verify === ... - OK: Current: the catalog is at migration 5 + OK: Current: the catalog is at migration 6 ... === HEALTHY: All checks passed === ``` From 636d6242aae90e6e520a01b354c732e938eea876 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:49:34 +0000 Subject: [PATCH 10/30] test(storage): count migration 6 in the SQLite and MongoDB migration tests The SQLite tests counted every migration as applied on SQLite and every convergent migration as run again by --reconverge; migration 6 is the first that SQLite records as not applicable, so both counts now take the migrations that apply on SQLite. The MongoDB tests named migration 5 as the latest and used id 6 for a later binary's ledger row; they now name 6 as the latest, list it among the steps of a fresh run, and use id 7 for the later binary. --- .../storage-mongodb/tests/migrations_fresh.rs | 30 ++++++++++--------- .../tests/migrations_guards.rs | 4 +-- .../tests/migrations_holders.rs | 4 +-- .../storage-mongodb/tests/migrations_locks.rs | 6 ++-- .../tests/migrations_released.rs | 8 ++--- .../src/migrations/released_tests.rs | 9 ++++-- crates/storage-sqlite/src/migrations/tests.rs | 10 ++++++- 7 files changed, 42 insertions(+), 29 deletions(-) diff --git a/crates/storage-mongodb/tests/migrations_fresh.rs b/crates/storage-mongodb/tests/migrations_fresh.rs index 12cf1838e..ea0859cdf 100644 --- a/crates/storage-mongodb/tests/migrations_fresh.rs +++ b/crates/storage-mongodb/tests/migrations_fresh.rs @@ -303,7 +303,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { let Some(uri) = server() else { return }; let d = Deployment::new(&uri, "fresh").await; let report = d.create().await; - assert_eq!((report.from, report.to), (None, Some(5))); + assert_eq!((report.from, report.to), (None, Some(6))); let applied: Vec<(u32, String)> = report .applied .iter() @@ -318,6 +318,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { (3, d.target.catalog.clone()), (4, d.target.catalog.clone()), (5, d.target.catalog.clone()), + (6, d.target.catalog.clone()), ] ); let not_applicable: Vec = report @@ -326,8 +327,8 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { .filter(|s| s.outcome == Outcome::NotApplicable) .map(|s| s.id) .collect(); - assert_eq!(not_applicable, [3, 4], "{report:?}"); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(not_applicable, [3, 4, 6], "{report:?}"); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); let rows = d.catalog_ledger().await; let outcomes: Vec<(u32, Outcome)> = rows.iter().map(|r| (r.id, r.outcome)).collect(); assert_eq!( @@ -338,6 +339,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { (3, Outcome::NotApplicable), (4, Outcome::NotApplicable), (5, Outcome::Applied), + (6, Outcome::NotApplicable), ] ); assert!( @@ -347,7 +349,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { let data_rows = Deployment::documents(&d.data(), "extenddb_migrations").await; assert_eq!(data_rows.len(), 1); assert_eq!(data_rows[0].get_i64("_id"), Ok(1)); - assert_eq!(d.setting("catalog_version").await.as_deref(), Some("5")); + assert_eq!(d.setting("catalog_version").await.as_deref(), Some("6")); assert_eq!(d.setting("resource_tag_migration").await, None); let history = Deployment::documents(&d.catalog(), "schema_history").await; assert_eq!(history.len(), 1); @@ -389,7 +391,7 @@ async fn a_second_run_applies_nothing_and_reconverge_keeps_the_rows() { let before = d.catalog_ledger().await; let again = d.migrate().await.expect("migrate"); assert!(again.applied.is_empty()); - assert_eq!((again.from, again.to), (Some(5), Some(5))); + assert_eq!((again.from, again.to), (Some(6), Some(6))); let reconverged = d.reconverge().await.expect("reconverge"); // Migration 1's steps in the catalog and the data database, and migration @@ -421,7 +423,7 @@ async fn a_second_run_applies_nothing_and_reconverge_keeps_the_rows() { before, "reconverge leaves the rows as they are" ); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); d.drop_databases().await; } @@ -456,7 +458,7 @@ async fn forget_clears_an_unreleased_id_and_migrate_applies_it_again() { assert_eq!(pending.iter().map(|p| p.id).collect::>(), [1, 1]); let report = d.migrate().await.expect("migrate"); assert_eq!(report.applied.len(), 2); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); d.drop_databases().await; } @@ -473,19 +475,19 @@ async fn a_changed_checksum_a_newer_catalog_and_an_older_release_are_reported() doc! { "_id": id, "name": "later", "kind": kind, "checksum": "c", "outcome": "applied", "notes": "", "applied_at": bson::DateTime::now(), "applied_by": "9.9.9" } }; - ledger.insert_one(row(6, "breaking")).await.expect("insert"); + ledger.insert_one(row(7, "breaking")).await.expect("insert"); let status = d.status().await; assert_eq!(status.label(), "AheadIncompatible"); assert_eq!(status.exit_code(), exit::AHEAD_INCOMPATIBLE); ledger - .delete_one(doc! { "_id": 6_i64 }) + .delete_one(doc! { "_id": 7_i64 }) .await .expect("delete"); - ledger.insert_one(row(6, "additive")).await.expect("insert"); + ledger.insert_one(row(7, "additive")).await.expect("insert"); assert_eq!(d.status().await.label(), "AheadCompatible"); assert!(d.migrate().await.expect("migrate").applied.is_empty()); ledger - .delete_one(doc! { "_id": 6_i64 }) + .delete_one(doc! { "_id": 7_i64 }) .await .expect("delete"); @@ -500,7 +502,7 @@ async fn a_changed_checksum_a_newer_catalog_and_an_older_release_are_reported() assert_eq!(refused.exit_code(), exit::ATTENTION); d.reconverge().await.expect("reconverge"); assert_eq!(d.setting("resource_tag_migration").await, None); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); settings .update_one( doc! { "_id": "catalog_version" }, @@ -510,7 +512,7 @@ async fn a_changed_checksum_a_newer_catalog_and_an_older_release_are_reported() .expect("version"); assert_eq!(d.status().await.label(), "WrittenByOlderRelease"); d.reconverge().await.expect("reconverge"); - assert_eq!(d.setting("catalog_version").await.as_deref(), Some("5")); + assert_eq!(d.setting("catalog_version").await.as_deref(), Some("6")); // A recorded checksum this binary's body does not have. ledger @@ -558,6 +560,6 @@ async fn a_ledger_document_this_binary_cannot_read_stops_the_status() { .expect_err("an error"); migrations.close().await; assert!(error.to_string().contains("\"sideways\""), "{error}"); - assert_eq!(MigrationId::LATEST.number(), 5); + assert_eq!(MigrationId::LATEST.number(), 6); d.drop_databases().await; } diff --git a/crates/storage-mongodb/tests/migrations_guards.rs b/crates/storage-mongodb/tests/migrations_guards.rs index 793f65361..55284c96f 100644 --- a/crates/storage-mongodb/tests/migrations_guards.rs +++ b/crates/storage-mongodb/tests/migrations_guards.rs @@ -207,7 +207,7 @@ async fn migrate_creates_the_indexes_a_deployment_lacks() { .await .contains(&"table_id_1".to_owned()) ); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); assert_fresh_definitions(&d).await; d.drop_databases().await; } @@ -232,7 +232,7 @@ async fn stop_at_every_request(uri: &str, state: Option<&str>) -> usize { } assert_eq!( d.status().await, - CatalogStatus::Current { version: 5 }, + CatalogStatus::Current { version: 6 }, "{requests}" ); assert_fresh_definitions(&d).await; diff --git a/crates/storage-mongodb/tests/migrations_holders.rs b/crates/storage-mongodb/tests/migrations_holders.rs index ed0cd866c..5eba917e5 100644 --- a/crates/storage-mongodb/tests/migrations_holders.rs +++ b/crates/storage-mongodb/tests/migrations_holders.rs @@ -113,7 +113,7 @@ async fn migration_2_keeps_the_lock_through_a_scan_longer_than_the_idle_limit() applied.expect("every migration applies"); // A shorter run would apply without the progress the scan records. assert!(took > timing.idle_limit * 4, "the run took {took:?}"); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); assert!(d.catalog_ledger().await.iter().any(|row| row.id == 2)); d.drop_databases().await; } @@ -151,7 +151,7 @@ async fn the_status_read_under_the_lock_keeps_it_through_a_long_scan() { "the status read took {took:?}" ); applied.expect("every migration applies"); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); d.drop_databases().await; } diff --git a/crates/storage-mongodb/tests/migrations_locks.rs b/crates/storage-mongodb/tests/migrations_locks.rs index 84727523a..3f249d638 100644 --- a/crates/storage-mongodb/tests/migrations_locks.rs +++ b/crates/storage-mongodb/tests/migrations_locks.rs @@ -53,10 +53,10 @@ async fn two_migrators_started_together_apply_once_and_the_other_finds_nothing() applied.sort_unstable(); assert_eq!( applied, - [0, 6], + [0, 7], "one applies every step and the other finds nothing" ); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); d.drop_databases().await; } @@ -204,7 +204,7 @@ async fn migrate_waits_for_a_running_server_and_a_server_refuses_while_a_migrati .is_none() ); // The preview and verify read the status beside the server. - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); serving.release().await; let (held, _) = lock(&d.target, false, Duration::from_secs(2), Timing::PRODUCTION) .await diff --git a/crates/storage-mongodb/tests/migrations_released.rs b/crates/storage-mongodb/tests/migrations_released.rs index c636de7a9..19db70d96 100644 --- a/crates/storage-mongodb/tests/migrations_released.rs +++ b/crates/storage-mongodb/tests/migrations_released.rs @@ -164,12 +164,12 @@ async fn every_released_catalog_upgrades_to_the_definitions_of_a_fresh_install() panic!("{state} is not behind"); }; assert_eq!(version, None, "{state} has no ledger"); - assert_eq!(pending.len(), 6, "{state}"); + assert_eq!(pending.len(), 7, "{state}"); let report = d.migrate().await.expect("migrate"); - assert_eq!((report.from, report.to), (None, Some(5)), "{state}"); + assert_eq!((report.from, report.to), (None, Some(6)), "{state}"); assert_eq!( d.status().await, - CatalogStatus::Current { version: 5 }, + CatalogStatus::Current { version: 6 }, "{state}" ); @@ -401,7 +401,7 @@ async fn a_reconverge_leaves_policies_written_after_migration_2_as_they_are() { .any(|n| n.starts_with("Skipped 2 resource_tag_condition_keys:")), "{report:?}" ); - assert_eq!(d.status().await, CatalogStatus::Current { version: 5 }); + assert_eq!(d.status().await, CatalogStatus::Current { version: 6 }); assert_eq!( documents(Deployment::documents(&d.catalog(), "iam_policies").await), before diff --git a/crates/storage-sqlite/src/migrations/released_tests.rs b/crates/storage-sqlite/src/migrations/released_tests.rs index 71dcee691..9e3959272 100644 --- a/crates/storage-sqlite/src/migrations/released_tests.rs +++ b/crates/storage-sqlite/src/migrations/released_tests.rs @@ -390,11 +390,14 @@ async fn a_catalog_an_older_release_wrote_to_is_reported_and_reconverged() { next_second().await; let report = reconverge(&db).await.expect("reconverge"); - // Every convergent migration ran again; migration 2, which is not - // convergent, is named as skipped. + // Every convergent migration that applies on SQLite ran again; + // migration 2, which is not convergent, is named as skipped. let convergent = MigrationId::ALL .into_iter() - .filter(|id| super::migration(*id).convergent()) + .filter(|id| { + let m = super::migration(*id); + m.convergent() && !m.bodies().is_empty() + }) .count(); assert_eq!(report.applied.len(), convergent, "{trace}: {report:?}"); let skipped = format!("Skipped {}:", MigrationId::ResourceTagConditionKeys); diff --git a/crates/storage-sqlite/src/migrations/tests.rs b/crates/storage-sqlite/src/migrations/tests.rs index a837e802e..564a2f6bb 100644 --- a/crates/storage-sqlite/src/migrations/tests.rs +++ b/crates/storage-sqlite/src/migrations/tests.rs @@ -270,7 +270,15 @@ async fn a_fresh_database_is_current_after_one_run_and_seeds_nothing() { "SELECT COUNT(*) FROM extenddb_migrations WHERE outcome = 'applied'" ) .await, - i64::from(LATEST) + // One row for each migration that applies on SQLite; the others are + // recorded as not applicable. + i64::try_from( + MigrationId::ALL + .into_iter() + .filter(|id| !super::migration(*id).bodies().is_empty()) + .count() + ) + .unwrap() ); assert_eq!(version_row(&db).await, Some(LATEST.to_string())); assert_eq!( From d83f4ba06ff6830bcb25d9cf0412f5d1687400ce Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:58:31 +0000 Subject: [PATCH 11/30] docs(contributing): renumber the worked migration example to 7 Migration 6 is now escape_control_chars, so the worked example in CONTRIBUTING.md's "Adding a catalog migration", table_note, becomes migration 7, with its file names, fingerprint, test name and the pending listing on a catalog at migration 6. --- CONTRIBUTING.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b0d641a98..421a28e08 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -341,7 +341,7 @@ SQLite, PostgreSQL, Cassandra and MongoDB migrate through this framework. ### Example: a nullable column on `tables` -Migration 6, `table_note`, adds a nullable `note TEXT` column to the catalog's +Migration 7, `table_note`, adds a nullable `note TEXT` column to the catalog's `tables` table on SQLite and PostgreSQL. In `crates/storage/src/migrations/registry.rs`, at the end of the @@ -349,18 +349,18 @@ In `crates/storage/src/migrations/registry.rs`, at the end of the ```rust /// Adds a nullable `note` column to the `tables` catalog table. - TableNote = 6, "table_note", + TableNote = 7, "table_note", "add a nullable note column to the tables catalog"; ``` PostgreSQL has `ADD COLUMN IF NOT EXISTS`, so its body is a file, -`crates/storage-postgres/migrations/0006_table_note.sql`: +`crates/storage-postgres/migrations/0007_table_note.sql`: ```sql -- Copyright 2026 ExtendDB contributors -- SPDX-License-Identifier: Apache-2.0 -- --- Migration 6, table_note, PostgreSQL catalog database: a nullable note +-- Migration 7, table_note, PostgreSQL catalog database: a nullable note -- column on tables. IF NOT EXISTS makes a second run change nothing. ALTER TABLE tables ADD COLUMN IF NOT EXISTS note TEXT; @@ -375,7 +375,7 @@ In `crates/storage-postgres/src/migrations/mod.rs`, the arm in `migration()`: bodies: vec![file_body!( StoreKind::Catalog, "migrations", - "0006_table_note.sql" + "0007_table_note.sql" )], }, ``` @@ -393,13 +393,13 @@ and the id in the transactional arm of `runs_in()`: SQLite has no `ADD COLUMN IF NOT EXISTS`, and a file with a plain `ADD COLUMN` fails when it runs a second time, so the SQLite body is code that checks for the column first. -`crates/storage-sqlite/src/migrations/m0006_table_note.rs`: +`crates/storage-sqlite/src/migrations/m0007_table_note.rs`: ```rust // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Migration 6, `table_note`, SQLite: a nullable `note` column on `tables`. +//! Migration 7, `table_note`, SQLite: a nullable `note` column on `tables`. //! //! SQLite has no `ADD COLUMN IF NOT EXISTS`, so the body reads the table's //! columns first and adds the column only when it is missing. A second run @@ -411,10 +411,10 @@ use extenddb_storage::migrations::{CodeBody, Done, MigrationError}; use super::SqliteStores; /// This file, whose SHA-256 the checksum test pins. -pub(crate) const SOURCE: &str = include_str!("m0006_table_note.rs"); +pub(crate) const SOURCE: &str = include_str!("m0007_table_note.rs"); /// Recorded as this migration's checksum. Changes only with a new migration. -const FINGERPRINT: &str = "0006_table_note/sqlite/1"; +const FINGERPRINT: &str = "0007_table_note/sqlite/1"; pub(crate) struct TableNote; @@ -453,7 +453,7 @@ beside the others: ```rust #[rustfmt::skip] #[allow(clippy::all, deprecated)] -mod m0006_table_note; +mod m0007_table_note; ``` and the arm in `migration()`: @@ -464,8 +464,8 @@ and the arm in `migration()`: convergent: true, bodies: vec![StoreBody::code( StoreKind::Catalog, - &m0006_table_note::TableNote, - m0006_table_note::SOURCE, + &m0007_table_note::TableNote, + m0007_table_note::SOURCE, )], }, ``` @@ -477,8 +477,8 @@ rows of `tables`: ```rust #[tokio::test] -async fn migration_6_adds_the_note_column_to_tables() { - let db = temp_db("m6"); +async fn migration_7_adds_the_note_column_to_tables() { + let db = temp_db("m7"); load_dump(&db, DEV_0_1_14).await; run(&db).await.expect("migrate"); let mut text = dump( @@ -488,12 +488,12 @@ async fn migration_6_adds_the_note_column_to_tables() { ) .await; text.push_str(&dump(&db, "SELECT table_name, note FROM tables ORDER BY table_name").await); - golden("0006_table_note", &text); + golden("0007_table_note", &text); } ``` -`EXTENDDB_BLESS_EXPECTED=1 cargo test -p extenddb-storage-sqlite --lib migration_6` -writes `crates/storage-sqlite/tests/fixtures/golden/0006_table_note.txt`, one +`EXTENDDB_BLESS_EXPECTED=1 cargo test -p extenddb-storage-sqlite --lib migration_7` +writes `crates/storage-sqlite/tests/fixtures/golden/0007_table_note.txt`, one tab-separated line per row under each query: ``` @@ -508,15 +508,15 @@ The PostgreSQL body is a file, so it has no golden test. The example declares `Kind::Breaking`. A nullable column can be additive by the rule in step 4, but declaring it additive needs the old-binary job, which this example does not add. As a breaking migration it makes a 1.x binary -without migration 6 refuse a catalog that has it, and a rollback restores the +without migration 7 refuse a catalog that has it, and a rollback restores the backup. The same PR changes the code that reads and writes `tables.note` in each backend's catalog store, and commits the `docs/schema/sqlite.txt` and `docs/schema/postgres.txt` that the integration jobs regenerate. It changes no per-table DDL, because `tables` is a catalog table, and adds no `RELEASED` -entry. `extenddb migrate --list` then shows migration 6, and on a catalog at -migration 5 `extenddb migrate` lists migration 6 as pending and exits 3. +entry. `extenddb migrate --list` then shows migration 7, and on a catalog at +migration 6 `extenddb migrate` lists migration 7 as pending and exits 3. ### Running the migration tests From c3a229f6986c454e44eba0d03066e2befbb6568c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:11:38 +0000 Subject: [PATCH 12/30] test(cli): run migration 6 through migrate --yes beside its own sessions The merge took main's side of tests/test_cli_vector_catalog_migration.py, which dropped the earlier revision's CLI test of the string re-encode, the only test that ran `extenddb migrate --yes` with the re-encode pending. The new test makes a deployment with this binary's init, creates a table, an item and a backup through the server, then takes migration 6 out of both ledgers and sets the catalog version back to 5. The preview lists both bodies and exits 3. With another session on the catalog database, `migrate --yes` exits 5, names that database and records migration 6 in neither ledger. Once the session closes, the run exits 0 and applies migration 6 in both stores. With the migrate command's lock session counted as another session, the last run exits 5 and the test fails. --- tests/test_cli_vector_catalog_migration.py | 144 ++++++++++++++++++++- 1 file changed, 143 insertions(+), 1 deletion(-) diff --git a/tests/test_cli_vector_catalog_migration.py b/tests/test_cli_vector_catalog_migration.py index f5c4b4ad4..f24b23337 100644 --- a/tests/test_cli_vector_catalog_migration.py +++ b/tests/test_cli_vector_catalog_migration.py @@ -9,7 +9,9 @@ `continuous_backups` table. These tests load a deployment of a release from before the vector index schema, from its committed fixture, and check that the binary refuses to serve it, that `extenddb migrate` upgrades it, and that -the upgraded deployment then serves. They also check that +the upgraded deployment then serves. They also check that `migrate --yes` +applies migration 6 to a deployment holding a table and a backup and stops +while another session holds the catalog, that `--reconverge` runs every convergent migration again on a current catalog, and that a catalog ledger row for a migration this binary does not carry makes `serve` refuse. @@ -176,6 +178,76 @@ def _init(cli_env): assert result.returncode == 0, result.stdout + result.stderr +def _seed_table_and_backup(cli_env): + """Create a table, an item and a backup through the running server, so + that both bodies of migration 6 check for other sessions: the data body + while the catalog lists a table, the catalog body while `backup_items` + holds a row.""" + import uuid + + import boto3 + from conftest import wait_for_active + from management_helpers import ManagementClient + + endpoint = f"https://127.0.0.1:{cli_env['port']}" + mgmt = ManagementClient( + endpoint, os.environ.get("EXTENDDB_ADMIN_USER") or "admin", "TestPass1!" + ) + account_id = f"{uuid.uuid4().int % 10**12:012d}" + assert mgmt.create_account(account_id, "escape").status_code == 201 + assert mgmt.create_user(account_id, "seed", "TestPass123!").status_code == 201 + keys = mgmt.create_access_key(account_id, "seed").json() + assert mgmt.put_user_policy( + account_id, "seed", "full", + {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}]}, + ).status_code == 204 + client = boto3.client( + "dynamodb", + endpoint_url=endpoint, + aws_access_key_id=keys["access_key_id"], + aws_secret_access_key=keys["secret_access_key"], + region_name="us-east-1", + verify=False, + ) + client.create_table( + TableName="escape", + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + ) + wait_for_active(client, "escape") + client.put_item(TableName="escape", Item={"pk": {"S": "a"}, "v": {"S": "b"}}) + arn = client.create_backup(TableName="escape", BackupName="escape")["BackupDetails"][ + "BackupArn" + ] + deadline = time.monotonic() + 30 + while True: + details = client.describe_backup(BackupArn=arn)["BackupDescription"]["BackupDetails"] + if details["BackupStatus"] == "AVAILABLE": + return + assert time.monotonic() < deadline, details + time.sleep(0.5) + + +def _forget_migration_6(cli_env): + """Take migration 6 out of both ledgers and set the catalog version back + to 5, as a deployment of the release before it holds them. The rows this + build wrote hold no U+0001, so the migration rewrites none of them when it + runs again.""" + for database in (cli_env["db_name"], _data_db(cli_env)): + conn = _conn(database) + try: + with conn.cursor() as cur: + cur.execute("DELETE FROM extenddb_migrations WHERE id = 6") + if database == cli_env["db_name"]: + cur.execute( + "UPDATE settings SET value = '5' WHERE key = 'catalog_version'" + ) + finally: + conn.close() + + def _serve_refused(cli_env): """Run `serve --foreground`; it must exit on its own, and the result is returned. A server that starts serving is stopped and fails the test.""" @@ -340,6 +412,76 @@ def test_migrate_upgrades_a_catalog_a_release_before_1_0_created(self, cli_env): assert again.returncode == 0, again_output assert "up to date" in again_output.lower(), again_output + def test_migrate_applies_migration_6_beside_its_own_sessions(self, cli_env): + """`migrate --yes` applies migration 6 to a deployment holding a table + and a backup, and stops while another session holds the catalog. + + Migration 6 rewrites stored strings, so each body stops the run while a + session other than the migrate command's own holds the database it + rewrites and that database has rows to rewrite. While the check runs, + the command holds sessions of its own: the migration lock's session on + the catalog database and the runner's sessions on both databases. The + check leaves them out by their application_name; if it counted them, + it would refuse every upgrade. The deployment comes from this binary's + init, with migration 6 then taken out of both ledgers, as an upgrade + from the release before it finds them. + """ + _init(cli_env) + _patch_config_port(cli_env["config_path"], cli_env["port"]) + served = _run_extenddb("serve", config=cli_env["config_path"]) + assert served.returncode == 0, served.stdout + served.stderr + try: + assert _wait_for_server(cli_env["port"]), "the deployment did not serve" + _seed_table_and_backup(cli_env) + finally: + _run_extenddb("stop", config=cli_env["config_path"], check=False) + time.sleep(1) + _forget_migration_6(cli_env) + catalog, data = cli_env["db_name"], _data_db(cli_env) + + pending = _run_extenddb( + "migrate", *_pg_args(), config=cli_env["config_path"], check=False + ) + pending_output = pending.stdout + pending.stderr + assert pending.returncode == 3, pending_output + assert "6 escape_control_chars (catalog, breaking)" in pending_output, pending_output + assert "6 escape_control_chars (data, breaking)" in pending_output, pending_output + + # Another client's session on the catalog database, which holds the + # backup's items: the run stops before any write, in either store. + holder = _conn(catalog) + try: + refused = _run_extenddb( + "migrate", "--yes", *_pg_args(), + config=cli_env["config_path"], + check=False, + timeout=90, + ) + finally: + holder.close() + refused_output = refused.stdout + refused.stderr + assert refused.returncode == 5, refused_output + assert ( + f"other session(s) hold the catalog database {catalog}" in refused_output + ), refused_output + assert 6 not in _ledger_ids(catalog) + assert 6 not in _ledger_ids(data) + + applied = _run_extenddb( + "migrate", "--yes", *_pg_args(), + config=cli_env["config_path"], + check=False, + timeout=90, + ) + output = applied.stdout + applied.stderr + assert applied.returncode == 0, output + assert "other session(s) hold" not in output, output + assert f"Applied 6 escape_control_chars in {catalog}" in output, output + assert f"Applied 6 escape_control_chars in {data}" in output, output + assert 6 in _ledger_ids(catalog) + assert 6 in _ledger_ids(data) + assert _catalog_version(cli_env) == str(_latest()) + def test_reconverge_runs_every_convergent_migration_again_on_a_current_catalog( self, cli_env ): From 7a10917679bf419fba687d199d409c01c1262380 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:39:36 +0000 Subject: [PATCH 13/30] fix(storage-postgres): leave gsi_pending.index_context to migration 11 Migration 11 (#833) escapes gsi_pending.index_context once, with the mapping that migration 13 uses. The data body of migration 13 also rewrote that column. A store upgraded through both migrations then held the context escaped twice, and a name with U+0001 read back as U+0001 U+0002. Migration 13 now rewrites only the item images of gsi_pending, old_item and new_item. Its worker_partition recompute reads the context through from_catalog_json, as the index worker reads it. catalog_json.rs had its own copy of the escape. It now calls escape_json_strings and unescape_json_strings from extenddb_storage::util. Its round trip test over the five-character alphabet goes, because control_chars.rs tests the same alphabet. Migration 11 keeps its frozen copy. The new test migrations_11_and_13_escape_a_queued_index_update_once queues an index update with U+0001 in its names, as a release before migration 11 wrote it. It runs migrations 11 and 13 in one upgrade. Then it checks that the context and the item image each hold the escape once and read back as written. --- crates/storage-postgres/src/catalog_json.rs | 107 +----------------- .../m0013_escape_control_chars/keys.rs | 2 +- .../m0013_escape_control_chars/mod.rs | 21 ++-- .../src/migrations/m0013_tests.rs | 9 +- .../tests/migrations_name_escape.rs | 32 ++++++ docs/manuals/07-upgrade-manual.md | 2 +- 6 files changed, 57 insertions(+), 116 deletions(-) diff --git a/crates/storage-postgres/src/catalog_json.rs b/crates/storage-postgres/src/catalog_json.rs index f19805c2d..fd2743c9b 100644 --- a/crates/storage-postgres/src/catalog_json.rs +++ b/crates/storage-postgres/src/catalog_json.rs @@ -21,7 +21,9 @@ //! character is stored as it was before the escape existed. The escape //! applies to every string and object key of a document, so a string that is //! not an attribute name and holds one of the two characters is stored the -//! same way and reads back as written. +//! same way and reads back as written. It is the escape the item documents +//! use, `extenddb_storage::util::escape_json_strings` and +//! `unescape_json_strings`. //! //! The documents: in the catalog database `tables.key_schema`, //! `tables.attribute_definitions`, `indexes.key_schema`, `indexes.projection`, @@ -43,14 +45,11 @@ //! itself. The encoder never writes one. use extenddb_storage::error::StorageError; +use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::Value; -const ESC: char = '\u{1}'; -const NUL_TAIL: char = '\u{1}'; -const ESC_TAIL: char = '\u{2}'; - /// Serialize `value` into its stored form. pub(crate) fn to_catalog_json(value: &T) -> Result { serde_json::to_value(value) @@ -65,84 +64,13 @@ pub(crate) fn from_catalog_json(v: Value) -> Result Value { - map_strings(v, &escape_str) + escape_json_strings(v) } /// A stored document with the escape reversed, for a caller that reads its /// fields without deserializing it. pub(crate) fn unescape_json(v: Value) -> Value { - map_strings(v, &unescape_str) -} - -fn escape_str(s: &str) -> Option { - if !s.bytes().any(|b| b == 0 || b == 1) { - return None; - } - let mut out = String::with_capacity(s.len() + 8); - for ch in s.chars() { - match ch { - '\u{0}' => { - out.push(ESC); - out.push(NUL_TAIL); - } - '\u{1}' => { - out.push(ESC); - out.push(ESC_TAIL); - } - other => out.push(other), - } - } - Some(out) -} - -fn unescape_str(s: &str) -> Option { - if !s.bytes().any(|b| b == 1) { - return None; - } - let mut out = String::with_capacity(s.len()); - let mut chars = s.chars().peekable(); - while let Some(ch) = chars.next() { - if ch != ESC { - out.push(ch); - continue; - } - match chars.peek() { - Some(&NUL_TAIL) => { - chars.next(); - out.push('\u{0}'); - } - Some(&ESC_TAIL) => { - chars.next(); - out.push('\u{1}'); - } - _ => out.push('\u{1}'), - } - } - Some(out) -} - -/// Apply `f` to every object key and string value of the tree. `f` returns -/// `None` for a string it leaves as it is, so a tree without either character -/// is rebuilt without copying a string. -fn map_strings(v: Value, f: &dyn Fn(&str) -> Option) -> Value { - match v { - Value::String(s) => match f(&s) { - Some(t) => Value::String(t), - None => Value::String(s), - }, - Value::Array(items) => { - Value::Array(items.into_iter().map(|item| map_strings(item, f)).collect()) - } - Value::Object(map) => { - let mut out = serde_json::Map::with_capacity(map.len()); - for (k, val) in map { - let key = f(&k).unwrap_or(k); - out.insert(key, map_strings(val, f)); - } - Value::Object(out) - } - other => other, - } + unescape_json_strings(v) } #[cfg(test)] @@ -212,27 +140,4 @@ mod tests { ); assert_eq!(unescape_json(stored), v); } - - #[test] - fn every_string_of_five_characters_over_the_affected_alphabet_round_trips() { - let alphabet = ['\u{0}', '\u{1}', '\u{2}', 'a']; - let mut frontier = vec![String::new()]; - for _ in 0..5 { - let mut next = Vec::new(); - for s in &frontier { - for ch in alphabet { - let mut t = s.clone(); - t.push(ch); - next.push(t); - } - } - for s in &next { - let stored = escape_str(s).unwrap_or_else(|| s.clone()); - assert!(!stored.contains('\u{0}'), "{s:?}"); - let back = unescape_str(&stored).unwrap_or_else(|| stored.clone()); - assert_eq!(&back, s, "{s:?} stored as {stored:?}"); - } - frontier = next; - } - } } diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs index 5b5dbaf2a..80948d131 100644 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs @@ -81,7 +81,7 @@ fn current_partition( ) -> Option { let old_item = old_item.map(crate::data::json_to_item).transpose().ok()?; let new_item = new_item.map(crate::data::json_to_item).transpose().ok()?; - let context: PendingApplyContext = crate::data::stored_json_to(index_context).ok()?; + let context: PendingApplyContext = crate::catalog_json::from_catalog_json(index_context).ok()?; worker_partition(old_item.as_ref(), new_item.as_ref(), &context).ok() } diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs index 86b8d8f84..3692644e4 100644 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs @@ -17,10 +17,12 @@ //! Two bodies, one per database. The catalog body rewrites `backup_items`, //! which lives in the catalog database; the data body rewrites every data //! table, index table and vector index table (the text key columns and -//! `item_data`), `gsi_pending` and `stream_records`, and recomputes -//! `gsi_pending.worker_partition` for the rows it changes. Tables are listed -//! from the catalog rows; a row whose table is `DELETING`, or whose physical -//! table is missing, is skipped and noted. +//! `item_data`), the item images of `gsi_pending` (`old_item`, `new_item`) +//! and `stream_records`, and recomputes `gsi_pending.worker_partition` for +//! the rows it changes. `gsi_pending.index_context` is not rewritten: catalog +//! migration 11, `attribute_name_escape`, applies the same escape to it once. +//! Tables are listed from the catalog rows; a row whose table is `DELETING`, +//! or whose physical table is missing, is skipped and noted. //! //! The escape is not idempotent: an escaped row also holds U+0001, and a //! legacy U+0001 U+0002 cannot be told from an escaped U+0001. Each body runs @@ -73,8 +75,8 @@ const FINGERPRINT: &str = "0013_escape_control_chars/postgres/1"; /// The catalog body: `backup_items`. pub(crate) struct EscapeBackupItems; -/// The data body: the data, index and vector index tables, `gsi_pending` and -/// `stream_records`. +/// The data body: the data, index and vector index tables, the item images +/// of `gsi_pending`, and `stream_records`. pub(crate) struct EscapeDataRows; #[async_trait] @@ -561,10 +563,11 @@ pub(crate) async fn escape_data( } } - // Fixed tables holding item documents. + // Fixed tables holding item documents. `gsi_pending.index_context` is a + // catalog document, which migration 11 escaped once with the same + // mapping; escaping it again would read a U+0001 back as U+0001 U+0002. if let Some(mut w) = - fixed_table_work(conn, "gsi_pending", &[], &["old_item", "new_item", "index_context"]) - .await? + fixed_table_work(conn, "gsi_pending", &[], &["old_item", "new_item"]).await? { w.recompute_worker_partition = true; work.push(w); diff --git a/crates/storage-postgres/src/migrations/m0013_tests.rs b/crates/storage-postgres/src/migrations/m0013_tests.rs index 4b1fc721b..8a8f9920e 100644 --- a/crates/storage-postgres/src/migrations/m0013_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_tests.rs @@ -324,7 +324,7 @@ async fn reencodes_legacy_rows() { "backup_items: 3 row update(s)", "_ddb_t1 (table \"t\" of account 111122223333): 3 row update(s)", "_ddb_i1 (index \"gsi1\" of table \"t\" of account 111122223333): 5 row update(s)", - "gsi_pending: 2 row update(s)", + "gsi_pending: 1 row update(s)", "stream_records: 1 row update(s)", ] ); @@ -385,8 +385,9 @@ async fn reencodes_legacy_rows() { ] ); - // gsi_pending: NULL old_item stays NULL, the raw row is re-encoded in - // both jsonb columns, the plain row is untouched. + // gsi_pending: NULL old_item stays NULL, the raw row's item image is + // re-encoded, and its index context is left as it is: migration 11 + // escapes `index_context`. The plain row is untouched. let rows: Vec<( Option, serde_json::Value, @@ -401,7 +402,7 @@ async fn reencodes_legacy_rows() { ( None, json!({"pk": {"S": "a\u{1}\u{2}b"}}), - json!({"k\u{1}\u{2}": 1}), + json!({"k\u{1}": 1}), ), (None, json!({"pk": {"S": "p"}}), json!({"k": 1})), ] diff --git a/crates/storage-postgres/tests/migrations_name_escape.rs b/crates/storage-postgres/tests/migrations_name_escape.rs index 5efcdac70..174a02867 100644 --- a/crates/storage-postgres/tests/migrations_name_escape.rs +++ b/crates/storage-postgres/tests/migrations_name_escape.rs @@ -15,6 +15,7 @@ use std::fmt::Write as _; use extenddb_core::backup_format::BackupArn; use extenddb_core::types::{CreateTableInput, DescribeTableInput}; use extenddb_storage::migrations::{CatalogStatus, MigrationId, Runner}; +use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; use extenddb_storage::{BackupCatalog, LegacyBackupReader, TableEngine}; use extenddb_storage_postgres::migrations::PostgresMigrations; use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; @@ -336,6 +337,37 @@ async fn migration_11_rewrites_the_raw_names_of_every_document_that_carries_them data.close().await; } +/// Migrations 11 and 13 in one run on the queued index update that a release +/// before them wrote, with U+0001 in the names of its index context and of +/// its item image: migration 11 escapes the context and migration 13 the +/// image, each once, so both read back as that release wrote them. +#[tokio::test] +async fn migrations_11_and_13_escape_a_queued_index_update_once() { + let Some(base) = base_conn() else { + return skip("migrations 11 and 13 on a queued index update"); + }; + let s = Scratch::new(&base, "pgm_g1113").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::DropContinuousBackups).await; + let (catalog, data) = (s.catalog().await, s.data().await); + seed_raw_names(&catalog, &data).await; + let queued = "SELECT new_item, index_context FROM gsi_pending"; + let (raw_item, raw_context): (serde_json::Value, serde_json::Value) = + sqlx::query_as(queued).fetch_one(&data).await.unwrap(); + catalog.close().await; + data.close().await; + s.migrate_through(MigrationId::EscapeControlChars).await; + + let data = s.data().await; + let (item, context): (serde_json::Value, serde_json::Value) = + sqlx::query_as(queued).fetch_one(&data).await.unwrap(); + assert_eq!(context, escape_json_strings(raw_context.clone())); + assert_eq!(item, escape_json_strings(raw_item.clone())); + assert_eq!(unescape_json_strings(context), raw_context); + assert_eq!(unescape_json_strings(item), raw_item); + data.close().await; +} + /// Migration 11 is not convergent: a reconverge leaves the documents this /// release wrote after it, through the escape, as they are, and the names /// still read back as written. diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 63a5d8e27..54a7f510b 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -394,7 +394,7 @@ deployment, even when no catalog migration is required. DynamoDB accepts U+0000 anywhere a string appears. The PostgreSQL backend now stores every string through an order-preserving escape: U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002, and every other character as it is, so a string that holds neither character is stored as before. The MongoDB backend applies the same escape to BSON field names (attribute names and map keys); BSON string values already held U+0000. SQLite and Cassandra store the character as written, and their stored data does not change. -**Migration 13, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), `gsi_pending` and `stream_records`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. +**Migration 13, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), the item images of `gsi_pending` (`old_item` and `new_item`; migration 11 escapes `index_context`) and `stream_records`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. Upgrade in this order: From a7b027777dc75b7d07f467ed371d52225efea310 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:40:59 +0000 Subject: [PATCH 14/30] fix(storage-postgres): re-encode stream_pending records in migration 13 Since #819, a write stores its stream record in stream_pending (migration 7), and the numbering moves the record to stream_records after the write commits. A server of 0.1.15 or 1.0.0 that stops before the numbering leaves raw records in stream_pending. This release reads stream records through the escape. A raw U+0001 followed by U+0001 or U+0002 in such a record would then read back as another string. The data body of migration 13 now re-encodes stream_pending.record_data as it re-encodes stream_records.record_data. record_bytes keeps the length that the write sent, since the numbering uses it only to size a batch. The sessions check of the data body also counts a row in stream_pending. reencodes_legacy_rows seeds two pending records, one with U+0001, and checks that the migration re-encodes only that one. --- .../m0013_escape_control_chars/guard.rs | 6 ++- .../m0013_escape_control_chars/mod.rs | 25 +++++++----- .../src/migrations/m0013_tests.rs | 38 +++++++++++++++++-- docs/manuals/07-upgrade-manual.md | 4 +- 4 files changed, 56 insertions(+), 17 deletions(-) diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs index 0a4673eee..f5ef208a5 100644 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs @@ -63,14 +63,16 @@ pub(crate) async fn catalog_has_rows(catalog: &PgPool) -> Result Result { if std::env::var_os(IGNORE_CONNECTIONS_ENV).is_some() { return Ok(false); } Ok(has_row(catalog, "tables").await? || has_row(data, "gsi_pending").await? - || has_row(data, "stream_records").await?) + || has_row(data, "stream_records").await? + || has_row(data, "stream_pending").await?) } /// One item naming the other sessions on the database `pool` reaches, or none; diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs index 3692644e4..6b3f3335a 100644 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs @@ -18,11 +18,12 @@ //! which lives in the catalog database; the data body rewrites every data //! table, index table and vector index table (the text key columns and //! `item_data`), the item images of `gsi_pending` (`old_item`, `new_item`) -//! and `stream_records`, and recomputes `gsi_pending.worker_partition` for -//! the rows it changes. `gsi_pending.index_context` is not rewritten: catalog -//! migration 11, `attribute_name_escape`, applies the same escape to it once. -//! Tables are listed from the catalog rows; a row whose table is `DELETING`, -//! or whose physical table is missing, is skipped and noted. +//! and the stream records of `stream_records` and `stream_pending`, and +//! recomputes `gsi_pending.worker_partition` for the rows it changes. +//! `gsi_pending.index_context` is not rewritten: catalog migration 11, +//! `attribute_name_escape`, applies the same escape to it once. Tables are +//! listed from the catalog rows; a row whose table is `DELETING`, or whose +//! physical table is missing, is skipped and noted. //! //! The escape is not idempotent: an escaped row also holds U+0001, and a //! legacy U+0001 U+0002 cannot be told from an escaped U+0001. Each body runs @@ -76,7 +77,7 @@ const FINGERPRINT: &str = "0013_escape_control_chars/postgres/1"; pub(crate) struct EscapeBackupItems; /// The data body: the data, index and vector index tables, the item images -/// of `gsi_pending`, and `stream_records`. +/// of `gsi_pending`, `stream_records` and `stream_pending`. pub(crate) struct EscapeDataRows; #[async_trait] @@ -111,7 +112,7 @@ impl CodeBody for EscapeDataRows { } /// Another session on the data database, while the catalog lists a table - /// or `gsi_pending` or `stream_records` holds a row. + /// or `gsi_pending`, `stream_records` or `stream_pending` holds a row. async fn detect(&self, stores: &PostgresStores) -> Result, MigrationError> { if !stores.checks_sessions || !guard::data_has_rows(&stores.catalog, &stores.data).await? { return Ok(Vec::new()); @@ -572,8 +573,14 @@ pub(crate) async fn escape_data( w.recompute_worker_partition = true; work.push(w); } - if let Some(w) = fixed_table_work(conn, "stream_records", &[], &["record_data"]).await? { - work.push(w); + // A stream record waits in `stream_pending` until the numbering moves it + // to `stream_records` (migration 7), so both hold item documents. + // `record_bytes`, the numbering's estimate of a batch's size, keeps the + // length the write sent. + for table in ["stream_records", "stream_pending"] { + if let Some(w) = fixed_table_work(conn, table, &[], &["record_data"]).await? { + work.push(w); + } } escape_all(conn, &work, &mut notes).await?; diff --git a/crates/storage-postgres/src/migrations/m0013_tests.rs b/crates/storage-postgres/src/migrations/m0013_tests.rs index 8a8f9920e..24cac406b 100644 --- a/crates/storage-postgres/src/migrations/m0013_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_tests.rs @@ -135,10 +135,10 @@ pub(crate) async fn run(s: &Scratch) -> Result, MigrationError> { run_pool(&s.db).await } -/// Seed a data table, an index table, `gsi_pending`, `stream_records`, and -/// `backup_items` with three row kinds: raw U+0001 in key columns and -/// inside jsonb strings and object keys, the literal six-character text -/// backslash-u-0001 inside a jsonb string, and plain rows. +/// Seed a data table, an index table, `gsi_pending`, `stream_records`, +/// `stream_pending` and `backup_items` with three row kinds: raw U+0001 in +/// key columns and inside jsonb strings and object keys, the literal +/// six-character text backslash-u-0001 inside a jsonb string, and plain rows. pub(crate) async fn seed(db: &PgPool) { let ks = json!([ {"AttributeName": "pk", "KeyType": "HASH"}, @@ -279,6 +279,20 @@ pub(crate) async fn seed(db: &PgPool) { .await .expect("seed a stream record"); } + for (record_bytes, record) in [ + (40_i64, json!({"Keys": {"pk": {"S": "q\u{1}"}}})), + (30_i64, json!({"Keys": {"pk": {"S": "q"}}})), + ] { + sqlx::query( + "INSERT INTO stream_pending (shard_id, table_id, event_name, record_data, \ + record_bytes, created_at) VALUES ('shard-1', 't1', 'INSERT', $1, $2, now())", + ) + .bind(record) + .bind(record_bytes) + .execute(db) + .await + .expect("seed a pending stream record"); + } sqlx::query( "INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, \ @@ -326,6 +340,7 @@ async fn reencodes_legacy_rows() { "_ddb_i1 (index \"gsi1\" of table \"t\" of account 111122223333): 5 row update(s)", "gsi_pending: 1 row update(s)", "stream_records: 1 row update(s)", + "stream_pending: 1 row update(s)", ] ); @@ -422,6 +437,21 @@ async fn reencodes_legacy_rows() { ] ); + // stream_pending: the record waiting for its number is re-encoded, and + // its record_bytes is left as the write sent it. + let rows: Vec<(serde_json::Value, i64)> = + sqlx::query_as("SELECT record_data, record_bytes FROM stream_pending ORDER BY id") + .fetch_all(&s.db) + .await + .expect("read stream_pending"); + assert_eq!( + rows, + vec![ + (json!({"Keys": {"pk": {"S": "q\u{1}\u{2}"}}}), 40), + (json!({"Keys": {"pk": {"S": "q"}}}), 30), + ] + ); + // backup_items, including the NULL sk row. let rows: Vec<(String, Option, serde_json::Value)> = sqlx::query_as("SELECT pk, sk, item_data FROM backup_items ORDER BY pk") diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 54a7f510b..8c4d5f7ff 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -394,7 +394,7 @@ deployment, even when no catalog migration is required. DynamoDB accepts U+0000 anywhere a string appears. The PostgreSQL backend now stores every string through an order-preserving escape: U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002, and every other character as it is, so a string that holds neither character is stored as before. The MongoDB backend applies the same escape to BSON field names (attribute names and map keys); BSON string values already held U+0000. SQLite and Cassandra store the character as written, and their stored data does not change. -**Migration 13, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), the item images of `gsi_pending` (`old_item` and `new_item`; migration 11 escapes `index_context`) and `stream_records`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. +**Migration 13, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), the item images of `gsi_pending` (`old_item` and `new_item`; migration 11 escapes `index_context`), `stream_records` and `stream_pending`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. Upgrade in this order: @@ -402,7 +402,7 @@ Upgrade in this order: 2. Run `extenddb migrate --yes` with the new binary. 3. Start the new servers. -The migration cannot tell a row a running server writes from a legacy row, so it runs only while no server writes. `migrate --yes` waits for the servers that hold the serving key, and a server of 0.1.14 or an earlier release does not hold it. While the catalog lists a table or `gsi_pending` or `stream_records` holds a row, migration 13 therefore stops the run before its first write when any other session is connected to the data database, and while `backup_items` holds a row it does the same for the catalog database: `migrate` names each such session by role, client address and application name, and exits 5. The migrator's own sessions and read-only status sessions are not counted. Stop those sessions and run again. If the only other sessions are idle connections that a connection pooler holds, set `EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1` to skip the check. The preview, `extenddb migrate` without `--yes`, does not look for sessions, so it runs beside a server and reports migration 13 as pending. +The migration cannot tell a row a running server writes from a legacy row, so it runs only while no server writes. `migrate --yes` waits for the servers that hold the serving key, and a server of 0.1.14 or an earlier release does not hold it. While the catalog lists a table or `gsi_pending`, `stream_records` or `stream_pending` holds a row, migration 13 therefore stops the run before its first write when any other session is connected to the data database, and while `backup_items` holds a row it does the same for the catalog database: `migrate` names each such session by role, client address and application name, and exits 5. The migrator's own sessions and read-only status sessions are not counted. Stop those sessions and run again. If the only other sessions are idle connections that a connection pooler holds, set `EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1` to skip the check. The preview, `extenddb migrate` without `--yes`, does not look for sessions, so it runs beside a server and reports migration 13 as pending. A server of this release refuses a deployment where migration 13 is pending, and `extenddb init` applies it to a new deployment, which has nothing to rewrite. The migration is breaking and not convergent: a server of an earlier release refuses the migrated catalog, `migrate --yes --reconverge` skips migration 13, and going back to an earlier release means restoring both databases from the backups taken before the upgrade. A binary of an earlier release given a restored catalog and a migrated data database would read escaped strings as data. From 96a6376a5d568ffa89827f5ce28a558d89c586ce Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:27:51 +0000 Subject: [PATCH 15/30] test(storage-postgres): check the escape on the restore and legacy reader paths The merge gave two paths from main the escape of the item documents. The store-backed restore writes item_data through item_to_json, and the legacy backup reader decodes backup_items through json_to_item. These tests cover both paths. bulk_load_stores_control_characters_through_the_escape loads an item with U+0000 and U+0001 in its key, its names and its values into a restore target. It checks that the stored item_data holds the escape once. restore_keeps_control_characters_in_keys_indexes_and_items now also reads its backup through the legacy reader and compares the items with the items it wrote. The restore_job test is in tests/restore_job/control_chars.rs, so that tests/restore_job.rs only declares the module. The import that the merge added to restore_engine.rs moves to the order that rustfmt gives. --- crates/storage-postgres/src/restore_engine.rs | 2 +- .../tests/backup_restore/control_chars.rs | 30 +++++++++-- crates/storage-postgres/tests/restore_job.rs | 5 ++ .../tests/restore_job/control_chars.rs | 50 +++++++++++++++++++ 4 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 crates/storage-postgres/tests/restore_job/control_chars.rs diff --git a/crates/storage-postgres/src/restore_engine.rs b/crates/storage-postgres/src/restore_engine.rs index 5e3c6d852..d208baea8 100644 --- a/crates/storage-postgres/src/restore_engine.rs +++ b/crates/storage-postgres/src/restore_engine.rs @@ -46,8 +46,8 @@ use futures::stream::BoxStream; use crate::PostgresEngine; use crate::backup_engine::{RestoreTarget, RowInsertError, insert_restore_rows}; use crate::catalog_json::from_catalog_json; -use crate::data::{data_table_name, item_to_json}; use crate::data::vector_index::{VectorInsertPlan, fetch_vector_indexes_for_table}; +use crate::data::{data_table_name, item_to_json}; fn db_err(e: sqlx::Error) -> StorageError { StorageError::Internal(format!("Database error: {e}")) diff --git a/crates/storage-postgres/tests/backup_restore/control_chars.rs b/crates/storage-postgres/tests/backup_restore/control_chars.rs index 3ec13916d..c3b50757a 100644 --- a/crates/storage-postgres/tests/backup_restore/control_chars.rs +++ b/crates/storage-postgres/tests/backup_restore/control_chars.rs @@ -1,6 +1,8 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +use futures::StreamExt; + use super::*; /// Every stored row of one physical table, each as the JSON text of the @@ -18,10 +20,11 @@ async fn stored_rows(s: &Scratch, physical_id: &str) -> Vec { /// Items holding U+0000 and U+0001 in key values, index key values, nested /// values, and attribute names are stored through the control-character -/// escape. A restore copies `backup_items` text into the target as it is and -/// derives the key columns and index rows from it, so those must come out in -/// the same stored form as the source's (escaped once, not twice), and the -/// restored items must read back equal to what was written. +/// escape. The legacy reader decodes the backup's items, and a restore +/// copies `backup_items` text into the target as it is and derives the key +/// columns and index rows from it, so those must come out in the same stored +/// form as the source's (escaped once, not twice), and the restored items +/// must read back equal to what was written. #[tokio::test] async fn restore_keeps_control_characters_in_keys_indexes_and_items() { if base_conn().is_none() { @@ -87,6 +90,25 @@ async fn restore_keeps_control_characters_in_keys_indexes_and_items() { .create(ACCOUNT, "nul_src", "b", JobPermit::detached()) .await .expect("backup"); + + // The legacy reader, which carries an in-catalog backup into a store, + // reads the items back as written. + let text = |item: &Item| serde_json::to_string(item).expect("item text"); + let mut written: Vec = items.iter().map(text).collect(); + written.sort(); + let opened = s + .engine + .items(ACCOUNT, &backup.backup_arn) + .await + .expect("open the legacy reader"); + let mut read: Vec = opened + .items + .map(|item| text(&item.expect("an item"))) + .collect() + .await; + read.sort(); + assert_eq!(read, written); + let desc = restore(&s, "nul_dst", &backup.backup_arn) .await .expect("restore"); diff --git a/crates/storage-postgres/tests/restore_job.rs b/crates/storage-postgres/tests/restore_job.rs index 5470b6048..f60297883 100644 --- a/crates/storage-postgres/tests/restore_job.rs +++ b/crates/storage-postgres/tests/restore_job.rs @@ -1795,3 +1795,8 @@ async fn sweep_keeps_a_progress_row_registered_between_the_two_reads() { drop(claim); s.cleanup().await; } + +// --- U+0000 and U+0001 in loaded items ----------------------------------------- + +#[path = "restore_job/control_chars.rs"] +mod control_chars; diff --git a/crates/storage-postgres/tests/restore_job/control_chars.rs b/crates/storage-postgres/tests/restore_job/control_chars.rs new file mode 100644 index 000000000..907ecea2e --- /dev/null +++ b/crates/storage-postgres/tests/restore_job/control_chars.rs @@ -0,0 +1,50 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; + +use super::*; + +/// `bulk_load` writes each item's `item_data` in the stored form that the +/// write path gives it (`data::item_to_json`): an item with U+0000 and U+0001 +/// in its key, its names and its values loads, and its row holds the escape +/// once. +#[tokio::test] +async fn bulk_load_stores_control_characters_through_the_escape() { + if !pg_available("bulk_load_stores_control_characters_through_the_escape") { + return; + } + let s = scratch().await; + let row = available_backup(&s, "Music").await; + let (_desc, key, claim) = register(&s, &row, "Loaded", None).await; + let written = serde_json::json!({ + "pk": {"S": "p\u{0}a"}, + "sk": {"N": "1"}, + "g": {"S": "g\u{1}"}, + "n\u{0}ame": {"M": {"k\u{1}": {"S": "\u{0}\u{1}\u{2}"}}} + }); + let item: Item = serde_json::from_value(written.clone()).expect("item"); + let applied = s + .engine + .bulk_load( + &key, + &*claim, + BulkLoadFile { + file_index: 0, + start_at: 0, + reapplying: false, + }, + stream(vec![item]), + ) + .await + .expect("load the file"); + assert_eq!(applied, 1); + let stored: serde_json::Value = + sqlx::query_scalar(&format!("SELECT item_data FROM \"_ddb_{}\"", key.table_id)) + .fetch_one(&s.db) + .await + .expect("read the base row"); + assert_eq!(stored, escape_json_strings(written.clone())); + assert_eq!(unescape_json_strings(stored), written); + s.cleanup().await; +} From a922142c1458b869bf3595cc6bc03ecf17c7f8c5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:19:06 +0000 Subject: [PATCH 16/30] test(storage-postgres): read the index rows of catalog_nul_index_writes through the escape Main's catalog_nul_index_writes compares the attribute names of each index row with the names of the items that it writes. It read the names directly from item_data. On this branch item_data holds the stored form, in which the escape writes each U+0001 as U+0001 U+0002, so two of its three tests failed. index_rows now reads each row through unescape_json_strings, as json_to_item reads an item. The module comments of catalog_nul_index_writes.rs and catalog_nul_backup_jobs.rs said that the PostgreSQL item columns cannot hold a name with U+0000. They now say that the item columns store such a name through the escape. --- .../storage-postgres/tests/catalog_nul_backup_jobs.rs | 11 ++++++----- .../tests/catalog_nul_index_writes.rs | 7 ++++--- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/storage-postgres/tests/catalog_nul_backup_jobs.rs b/crates/storage-postgres/tests/catalog_nul_backup_jobs.rs index ba70558f1..866630b2f 100644 --- a/crates/storage-postgres/tests/catalog_nul_backup_jobs.rs +++ b/crates/storage-postgres/tests/catalog_nul_backup_jobs.rs @@ -14,11 +14,12 @@ //! compare the names that `DescribeBackup` and `DescribeTable` return with //! the names of the source table, byte for byte. //! -//! An item attribute name that holds U+0000 is item data, which the -//! PostgreSQL item columns cannot hold yet. So the table whose key schema -//! holds U+0000 has no items, and the items of the other table carry names -//! that hold U+0001 only. See `catalog_nul_support` for the database these -//! tests need. +//! The item columns store an attribute name that holds U+0000 through the +//! escape of `extenddb_storage::util`, and `restore_job/control_chars.rs` +//! loads such an item. These tests check the catalog documents: the table +//! whose key schema holds U+0000 has no items, and the items of the other +//! table carry names that hold U+0001 only. See `catalog_nul_support` for the +//! database these tests need. mod catalog_nul_support; diff --git a/crates/storage-postgres/tests/catalog_nul_index_writes.rs b/crates/storage-postgres/tests/catalog_nul_index_writes.rs index beafcd2e8..0d7791d33 100644 --- a/crates/storage-postgres/tests/catalog_nul_index_writes.rs +++ b/crates/storage-postgres/tests/catalog_nul_index_writes.rs @@ -11,8 +11,8 @@ //! the name would find no such attribute on the items, and the index would //! stay empty. A second GSI is keyed on a U+0000 name that the items do not //! carry, so every write with a delay stores a context that holds U+0000. -//! An item attribute name that holds U+0000 is item data, which the PostgreSQL -//! item columns cannot hold yet, so no item here carries one. +//! The item columns store `item_data` through the same escape, so the test +//! reads the names of each index row through `unescape_json_strings`. //! //! See `catalog_nul_support` for the database these tests need. @@ -113,8 +113,9 @@ async fn index_rows(s: &Scratch, index_id: &str) -> Vec> { .await .expect("read an index table"); let mut out: Vec> = rows - .iter() + .into_iter() .map(|row| { + let row = extenddb_storage::util::unescape_json_strings(row); let mut names: Vec = row.as_object().expect("an item").keys().cloned().collect(); names.sort(); From a4ec2aa2aa3f44419b9dbbe335ceb69fedb86f55 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:19:06 +0000 Subject: [PATCH 17/30] fix(storage-mongodb): decode in-catalog backup items as the data path does With no [backup.store], CreateBackup on MongoDB takes an in-catalog backup, a $out copy of the table's collection. On this branch the field names of item_data in that collection go through the escape, so the copy holds the escaped names too. LegacyBackupReader::items, which backup migrate-legacy reads, decoded each document with a copy of the decode from before the escape. It returned the stored names: c U+0001 came back as c U+0001 U+0002, and n U+0000 as n U+0001 U+0001. items now decodes each document with document_to_item, the decode of the data path. This change removes the copy of the decode. The new live test live_legacy_items_return_names_that_hold_u0000_and_u0001_as_written writes an item with the names c U+0001 and n U+0000. It takes an in-catalog backup and reads the backup through items. It is in backup_live_tests_control_chars.rs, a child module of the live backup tests, so that backup_live_tests.rs only declares it. --- crates/storage-mongodb/src/backup_engine.rs | 33 +++----- .../storage-mongodb/src/backup_live_tests.rs | 3 + .../src/backup_live_tests_control_chars.rs | 77 +++++++++++++++++++ 3 files changed, 90 insertions(+), 23 deletions(-) create mode 100644 crates/storage-mongodb/src/backup_live_tests_control_chars.rs diff --git a/crates/storage-mongodb/src/backup_engine.rs b/crates/storage-mongodb/src/backup_engine.rs index 149adcd15..ac6eb880b 100644 --- a/crates/storage-mongodb/src/backup_engine.rs +++ b/crates/storage-mongodb/src/backup_engine.rs @@ -16,7 +16,7 @@ //! appears in a collection name. //! //! `extenddb backup migrate-legacy` reads a backup through `items`, a cursor -//! over that collection with a frozen copy of the decode, and ends with +//! over that collection, decoded as the data path decodes it, and ends with //! `replace_with_index_row`: one session transaction that takes the lock //! below, inserts the catalog index document and writes DELETING marked //! `migrated_to_store`, then the delete's drop and DELETED. DeleteBackup @@ -101,7 +101,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use extenddb_core::types::{ - AttributeDefinition, BackupDescription, BackupDetails, BackupSummary, GsiInput, Item, + AttributeDefinition, BackupDescription, BackupDetails, BackupSummary, GsiInput, KeySchemaElement, LsiInput, Projection, ProvisionedThroughput, SourceTableDetails, StreamSpecification, TableDescription, TimeToLiveDescription, TimeToLiveStatus, }; @@ -123,7 +123,7 @@ use crate::backup_catalog::{ RESTORE_JOB_GENERATION, RESTORE_JOB_HEARTBEAT, RESTORE_JOB_STATUS, backup_in_use, generation_field, unowned_insert, }; -use crate::data::data_collection_name; +use crate::data::{data_collection_name, document_to_item}; use crate::data_engine::{ CommitOutcome, TRANSIENT_RETRY_ATTEMPTS, TxErr, backoff_sleep, is_duplicate_key, }; @@ -1984,11 +1984,12 @@ impl LegacyBackupReader for MongoEngine { /// The AVAILABLE backup document (its source as `restore_source` reads /// it), then a cursor over its `_backup_` collection in - /// batches of [`paging::DEFAULT_FETCH_BATCH`] documents, each decoded as - /// the data path decoded `item_data` when the backup was taken - /// ([`legacy_item_from_document`]). The collection is immutable while the - /// backup is AVAILABLE, so no snapshot is held; a DeleteBackup's drop - /// ends the cursor with an error. + /// batches of [`paging::DEFAULT_FETCH_BATCH`] documents. The collection + /// is a copy of the table's documents in their stored form, field names + /// escaped included, so each is decoded as the data path decodes a + /// stored document ([`document_to_item`]). The collection is immutable + /// while the backup is AVAILABLE, so no snapshot is held; a + /// DeleteBackup's drop ends the cursor with an error. fn items( &self, account_id: &str, @@ -2028,7 +2029,7 @@ impl LegacyBackupReader for MongoEngine { let mut cursor = cursor?; match cursor.try_next().await { Ok(Some(doc)) => { - let item = legacy_item_from_document(&doc); + let item = document_to_item(&doc); let next = item.is_ok().then_some(cursor); Some((item, next)) } @@ -2077,20 +2078,6 @@ impl LegacyBackupReader for MongoEngine { /// the frozen DeleteBackup must not finish the deletion and answer DELETED. const MIGRATED_TO_STORE: &str = "migrated_to_store"; -/// A frozen copy of the data path's decode of a stored document -/// (`crate::data::document_to_item`) as it was when the in-catalog `$out` -/// copies were taken, so the data path can change without changing what a -/// legacy backup reads as. -fn legacy_item_from_document(doc: &Document) -> Result { - let item_data = doc - .get("item_data") - .ok_or_else(|| StorageError::Internal("Document missing item_data field".to_string()))?; - let json_value: serde_json::Value = bson::from_bson(item_data.clone()) - .map_err(|e| StorageError::Internal(format!("BSON to JSON conversion error: {e}")))?; - serde_json::from_value(json_value) - .map_err(|e| StorageError::Internal(format!("JSON to Item conversion error: {e}"))) -} - /// A backup document as a [`LegacyBackupKey`]; a document without its /// `_id`, `account_id` or `backup_status`, or with a status no release /// writes, is an error. diff --git a/crates/storage-mongodb/src/backup_live_tests.rs b/crates/storage-mongodb/src/backup_live_tests.rs index 7ca23a7b7..b5d699d44 100644 --- a/crates/storage-mongodb/src/backup_live_tests.rs +++ b/crates/storage-mongodb/src/backup_live_tests.rs @@ -53,6 +53,9 @@ use crate::data::{data_collection_name, document_to_item, item_to_document}; use crate::migrations::{MongoTarget, run_backup_catalog_index}; use crate::restore_engine::INSERT_MANY_DOCUMENTS; +#[path = "backup_live_tests_control_chars.rs"] +mod control_chars; + const ACCOUNT: &str = "123456789012"; const OTHER_ACCOUNT: &str = "210987654321"; const REGION: &str = "us-east-1"; diff --git a/crates/storage-mongodb/src/backup_live_tests_control_chars.rs b/crates/storage-mongodb/src/backup_live_tests_control_chars.rs new file mode 100644 index 000000000..c4f3710ff --- /dev/null +++ b/crates/storage-mongodb/src/backup_live_tests_control_chars.rs @@ -0,0 +1,77 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live MongoDB test of an in-catalog backup of an item whose attribute names +//! hold U+0000 and U+0001. +//! +//! The data path stores each field name of `item_data` through the escape of +//! `extenddb_storage::util::escape_json_keys`, and an in-catalog backup is a +//! `$out` copy of the table's collection, so the copy holds the escaped +//! names. `items`, which `extenddb backup migrate-legacy` reads, must return +//! the names as written. The test reads the replica set URI from +//! `EXTENDDB_TEST_MONGODB_URI` and is `#[ignore]`d, like the tests in the +//! parent module. + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::types::{ + AttributeValue, BillingMode, CreateTableInput, Item, KeyType, ScalarAttributeType, +}; +use extenddb_storage::{DataEngine, JobPermit, LegacyBackupReader, TableEngine}; +use futures::{FutureExt, StreamExt}; + +use super::{ACCOUNT, Fixture, attr, key}; + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs a MongoDB replica set in EXTENDDB_TEST_MONGODB_URI"] +async fn live_legacy_items_return_names_that_hold_u0000_and_u0001_as_written() { + let fixture = Fixture::new().await; + let outcome = std::panic::AssertUnwindSafe(async { + let fx = &fixture; + fx.engine + .create_table( + ACCOUNT, + CreateTableInput { + table_name: "names".to_owned(), + key_schema: vec![key("pk", KeyType::Hash)], + attribute_definitions: vec![attr("pk", ScalarAttributeType::S)], + billing_mode: Some(BillingMode::PayPerRequest), + ..Default::default() + }, + ) + .await + .expect("create the table"); + let key_info = fx + .engine + .table_key_info(ACCOUNT, "names") + .await + .expect("key info"); + let written: Item = [("pk", "p"), ("c\u{1}", "one"), ("n\u{0}", "two")] + .into_iter() + .map(|(name, value)| (name.to_owned(), AttributeValue::S(value.to_owned()))) + .collect(); + let maps = ExpressionMaps::default(); + fx.engine + .put_item(&key_info, written.clone(), false, None, &maps, None) + .await + .expect("put"); + let arn = fx + .engine + .create(ACCOUNT, "names", "b", JobPermit::detached()) + .await + .expect("backup") + .backup_arn; + let read: Vec = fx + .engine + .items(ACCOUNT, &arn) + .await + .expect("items") + .items + .map(|item| item.expect("an item")) + .collect() + .await; + assert_eq!(read, vec![written]); + }) + .catch_unwind() + .await; + fixture.finish_after(outcome).await; +} From 8e7bb759f49342f51ea0266a572cc0e8c1fa9f11 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:19:06 +0000 Subject: [PATCH 18/30] test(storage-postgres): test the context decode and stream_pending check of migration 13 recomputes_the_worker_partition_of_rows_queued_before_the_upgrade queued its rows with a context whose names held no U+0001. The test passed when the recompute decoded the context without the escape. The base key attribute of the context is now named pk U+0001. The test stores the context through to_catalog_json, as a release with migration 11 stores it. A decode without the escape finds no key on the item and leaves the old partition, so the test fails. only_a_store_with_rows_is_checked seeded every table at once. It passed when data_has_rows did not count stream_pending. It now checks first a store whose only row is in stream_pending. --- .../src/migrations/m0013_guard_tests.rs | 10 ++++++++ .../src/migrations/m0013_keys_tests.rs | 24 ++++++++++++------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs index 91d634d25..2dee0a756 100644 --- a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs @@ -179,6 +179,7 @@ async fn another_roles_session_counts_from_a_non_superuser_pool() { /// A store with nothing to rewrite needs no check: a fresh store, such as the /// one `init` creates, has no table, no backup and no queued or stream row. +/// One row in `stream_pending` is enough to need it. #[tokio::test] async fn only_a_store_with_rows_is_checked() { if base_conn().is_none() { @@ -188,6 +189,15 @@ async fn only_a_store_with_rows_is_checked() { let s = scratch().await; assert!(!catalog_has_rows(&s.db).await.unwrap()); assert!(!data_has_rows(&s.db, &s.db).await.unwrap()); + // A store whose only row is a stream record waiting for its number. + sqlx::query( + "INSERT INTO stream_pending (shard_id, table_id, event_name, record_data, \ + record_bytes, created_at) VALUES ('shard-1', 't1', 'INSERT', '{}', 2, now())", + ) + .execute(&s.db) + .await + .expect("seed a pending stream record"); + assert!(data_has_rows(&s.db, &s.db).await.unwrap()); seed(&s.db).await; assert!(catalog_has_rows(&s.db).await.unwrap()); assert!(data_has_rows(&s.db, &s.db).await.unwrap()); diff --git a/crates/storage-postgres/src/migrations/m0013_keys_tests.rs b/crates/storage-postgres/src/migrations/m0013_keys_tests.rs index 6efaf1d6b..05326d4bf 100644 --- a/crates/storage-postgres/src/migrations/m0013_keys_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_keys_tests.rs @@ -196,11 +196,15 @@ async fn rebuilds_composite_partition_keys_part_by_part() { s.cleanup().await; } +/// The base key attribute of [`context`]. Its name holds U+0001, so a decode +/// that read the stored context raw would not find the key on the item. +const PK: &str = "pk\u{1}"; + fn context() -> PendingApplyContext { PendingApplyContext::Gsi(GsiApplyContext { - base_key_schema: vec![element("pk", KeyType::Hash)], + base_key_schema: vec![element(PK, KeyType::Hash)], attribute_definitions: vec![AttributeDefinition { - attribute_name: "pk".to_owned(), + attribute_name: PK.to_owned(), attribute_type: ScalarAttributeType::S, }], index: GsiIndexDef { @@ -217,7 +221,7 @@ fn context() -> PendingApplyContext { /// The partition a build without the escape gave a row for `item`: the /// hash of the raw key text. fn legacy_partition(item: &Item) -> i32 { - let raw = extenddb_storage::util::composite_pk_to_text(item, &[element("pk", KeyType::Hash)]) + let raw = extenddb_storage::util::composite_pk_to_text(item, &[element(PK, KeyType::Hash)]) .expect("raw key text"); partition_for(&raw) } @@ -242,7 +246,7 @@ async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { .into_iter() .map(|k| { let mut item = Item::new(); - item.insert("pk".to_owned(), text(k)); + item.insert(PK.to_owned(), text(k)); item.insert("g".to_owned(), text("v")); item }) @@ -253,14 +257,18 @@ async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { let current = worker_partition(None, Some(&item), &ctx).expect("partition"); let legacy = legacy_partition(&item); - // A key without U+0001 and a non-key string with it: same text both ways. + // A key value without U+0001 and a non-key string with it: same text + // both ways. let mut plain = Item::new(); - plain.insert("pk".to_owned(), text("plain")); + plain.insert(PK.to_owned(), text("plain")); plain.insert("note".to_owned(), text("n\u{1}")); let plain_partition = legacy_partition(&plain); let s = scratch().await; - let raw_ctx = serde_json::to_value(&ctx).expect("context json"); + // The images as a release without the escape stored them, and the + // context through the catalog escape, as a release with migration 11 + // stores it. + let stored_ctx = crate::catalog_json::to_catalog_json(&ctx).expect("context json"); let raw = |i: &Item| serde_json::to_value(i).expect("item json"); for (old_item, new_item, partition) in [ (None, Some(raw(&item)), legacy), @@ -274,7 +282,7 @@ async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { .bind(partition) .bind(old_item) .bind(new_item) - .bind(&raw_ctx) + .bind(&stored_ctx) .execute(&s.db) .await .expect("seed a queued row"); From 9e1cfc74455f4e5c61bdae8f36548a5bd9928884 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:19:06 +0000 Subject: [PATCH 19/30] refactor(storage-postgres): remove the second copy of the stored JSON helpers to_stored_json and stored_json_to in data/mod.rs did what catalog_json::to_catalog_json and from_catalog_json do: serde_json::to_value and then escape_json_strings, and unescape_json_strings and then serde_json::from_value. The stream record write in tx_helpers.rs and the stream record read in stream_engine.rs now call the catalog_json functions, and this change removes the copy. json_to_item and item_to_json also call the catalog_json functions, and a vector search encodes its filter values with to_catalog_json. So the stored form of every document comes from one escape. The module comment of catalog_json.rs now names the item and stream documents. --- crates/storage-postgres/src/catalog_json.rs | 6 +++- crates/storage-postgres/src/data/mod.rs | 29 +++---------------- .../storage-postgres/src/data/tx_helpers.rs | 8 ++--- crates/storage-postgres/src/stream_engine.rs | 2 +- crates/storage-postgres/src/vector_search.rs | 5 +--- 5 files changed, 15 insertions(+), 35 deletions(-) diff --git a/crates/storage-postgres/src/catalog_json.rs b/crates/storage-postgres/src/catalog_json.rs index fd2743c9b..4af184ce2 100644 --- a/crates/storage-postgres/src/catalog_json.rs +++ b/crates/storage-postgres/src/catalog_json.rs @@ -39,7 +39,11 @@ //! once (`migrations/m0011_attribute_name_escape.rs`). //! //! The item documents (`item_data`, the stream record images, the images in -//! `gsi_pending`) are not written through this module. +//! `gsi_pending`) are stored through the same escape: `data::item_to_json` +//! and `data::json_to_item` call these functions, and the records in +//! `stream_pending` and `stream_records` are written and read through them. +//! Migration 11 leaves those documents as they are; migration 13 +//! (`escape_control_chars`) rewrites them. //! //! Decoding reads a U+0001 that is not followed by U+0001 or U+0002 as //! itself. The encoder never writes one. diff --git a/crates/storage-postgres/src/data/mod.rs b/crates/storage-postgres/src/data/mod.rs index c8b2fdcf9..f53f23dcd 100755 --- a/crates/storage-postgres/src/data/mod.rs +++ b/crates/storage-postgres/src/data/mod.rs @@ -9,7 +9,8 @@ use extenddb_core::types::{AttributeDefinition, Item, KeySchemaElement, ScalarAttributeType}; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; + +use crate::catalog_json::{from_catalog_json, to_catalog_json}; /// SQL table name for a Virtual `DynamoDB` table. /// @@ -69,8 +70,7 @@ pub(crate) fn all_sort_key_info<'a>( /// before deserialization, so an item written with U+0000 anywhere in it comes /// back byte-identical. pub(crate) fn json_to_item(v: serde_json::Value) -> Result { - serde_json::from_value(unescape_json_strings(v)) - .map_err(|e| StorageError::Internal(e.to_string())) + from_catalog_json(v) } /// Serialize an `Item` for an `item_data` JSONB column. @@ -80,28 +80,7 @@ pub(crate) fn json_to_item(v: serde_json::Value) -> Result { /// escape from `extenddb_storage::util` before it reaches the column. Items /// without U+0000 or U+0001 serialize to exactly what they did before. pub(crate) fn item_to_json(item: &Item) -> Result { - serde_json::to_value(item) - .map(escape_json_strings) - .map_err(|e| StorageError::Internal(e.to_string())) -} - -/// Serialize any value for a JSONB column that may carry item strings (stream -/// records, queued index updates, index contexts). Same escape as -/// [`item_to_json`]; the inverse is [`stored_json_to`]. -pub(crate) fn to_stored_json( - value: &T, -) -> Result { - serde_json::to_value(value) - .map(escape_json_strings) - .map_err(|e| StorageError::Internal(e.to_string())) -} - -/// Deserialize a JSONB value written by [`to_stored_json`]. -pub(crate) fn stored_json_to( - v: serde_json::Value, -) -> Result { - serde_json::from_value(unescape_json_strings(v)) - .map_err(|e| StorageError::Internal(e.to_string())) + to_catalog_json(item) } /// Bind a `SortKeyValue` to a positional parameter in a sqlx query and execute it. diff --git a/crates/storage-postgres/src/data/tx_helpers.rs b/crates/storage-postgres/src/data/tx_helpers.rs index 57d7fd9a1..9380c70ef 100755 --- a/crates/storage-postgres/src/data/tx_helpers.rs +++ b/crates/storage-postgres/src/data/tx_helpers.rs @@ -16,7 +16,7 @@ use extenddb_storage::util::{SortKeyValue, sk_column, sk_info}; use super::index::db_error; use super::key_text::{parse_sk, pk_to_text}; -use super::{data_table_name, item_to_json, json_to_item, to_stored_json}; +use super::{data_table_name, item_to_json, json_to_item}; /// Fetch a single item within an existing transaction. pub(super) async fn fetch_item_in_tx( @@ -442,9 +442,9 @@ pub(super) async fn write_stream_record_to_shard_in_tx( // It is the record's size before TOAST compresses it, which is what the // numbering copies and rewrites; `pg_column_size` would give the // compressed size. The text is that of the stored form - // ([`to_stored_json`]), since jsonb refuses the `\u0000` escape, so the - // length counts the escaped strings. - let record_text = to_stored_json(&record)?.to_string(); + // (`catalog_json::to_catalog_json`), since jsonb refuses the `\u0000` + // escape, so the length counts the escaped strings. + let record_text = crate::catalog_json::to_catalog_json(&record)?.to_string(); let record_bytes = i64::try_from(record_text.len()).unwrap_or(i64::MAX); // The record waits in stream_pending, with no sequence number, until this diff --git a/crates/storage-postgres/src/stream_engine.rs b/crates/storage-postgres/src/stream_engine.rs index 61eb132b5..865c027a5 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -521,7 +521,7 @@ impl StreamEngine for PostgresEngine { let records: Vec = rows .into_iter() .filter_map(|(_, data)| data) - .map(crate::data::stored_json_to) + .map(crate::catalog_json::from_catalog_json) .collect::, _>>()?; let last_seq = records.last().map(|r| r.dynamodb.sequence_number.clone()); diff --git a/crates/storage-postgres/src/vector_search.rs b/crates/storage-postgres/src/vector_search.rs index d09d41a69..406f93f34 100644 --- a/crates/storage-postgres/src/vector_search.rs +++ b/crates/storage-postgres/src/vector_search.rs @@ -281,10 +281,7 @@ impl VectorSearchEngine for PostgresEngine { // column, so the filter's attribute name and value must be compared // in stored form. for (name, value) in &filters { - let value_json = serde_json::to_value(value) - .map(extenddb_storage::util::escape_json_strings) - .map_err(|e| StorageError::Internal(format!("filter value: {e}")))? - .to_string(); + let value_json = crate::catalog_json::to_catalog_json(value)?.to_string(); query = query .bind(extenddb_storage::util::escape_control(name).into_owned()) .bind(value_json); From 8ef0cfb9036a4e11dc40091ee2513ed5a4c5ce09 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:19:06 +0000 Subject: [PATCH 20/30] docs: list migration 11 as not convergent and stream_pending as escaped The upgrade manual's paragraph on --reconverge named migrations 2 and 13 as the migrations that the repair skips. Migration 11 is not convergent either. Its registry entry has convergent: false, and the section of the same manual on migration 11 says that --reconverge skips it. The storage design doc lists the documents that go through the escape. The list now names stream_pending, where a stream record waits for its sequence number. --- docs/design/04-component-storage.md | 2 +- docs/manuals/07-upgrade-manual.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index cd00d89f4..ef10680eb 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -424,7 +424,7 @@ The PostgreSQL backend uses two categories of tables: 0x00 and is a different key from the six-character text `\u0000`). PostgreSQL `TEXT` rejects the byte and `jsonb` rejects the `\u0000` escape, so every string that reaches a key column or an `item_data`, `gsi_pending`, - `stream_records`, or `backup_items` document goes through the escape in + `stream_pending`, `stream_records`, or `backup_items` document goes through the escape in `extenddb_storage::util::escape_control`: U+0000 is stored as U+0001 U+0001 and U+0001 as U+0001 U+0002; every other character is unchanged, so ordinary data is stored exactly as before. The mapping preserves UTF-8 byte order and diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 8c4d5f7ff..a2800dfc5 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -78,7 +78,7 @@ Exit status 6 means the migration lock, or a running server, was still held when `verify` also checks the connection to the data database. When that check fails, `verify` exits 1 on a Behind catalog instead of 3, because `migrate --yes` cannot apply the pending migrations while the data database cannot be reached. It still exits 4 or 5 for the statuses that need a person. -A migration is additive when the previous release serves the catalog correctly with it applied, and breaking otherwise. Migrations 1 to 7 and 9 to 13 are breaking. Migration 8 creates a table in the PostgreSQL data database that the previous release never reads; on PostgreSQL it is declared breaking only because the job that proves an additive declaration against the old binary does not yet exist (CONTRIBUTING, step 4 of adding a migration), and on SQLite, MongoDB and Cassandra it does not apply (`migrate --list` prints it as not applicable, and `migrate` counts it as additive). Do not run a server of 0.1.14 or an earlier release against a migrated catalog. A binary of those releases that writes to a migrated catalog (its `migrate --yes`, or a SQLite dev server) leaves it WrittenByOlderRelease. `migrate --yes --reconverge` repairs it by running the convergent migrations again. Migration 2, which rewrites stored policies, and migration 13, which re-encodes stored strings on PostgreSQL, are not convergent: the repair skips them and prints a line for each that says so (see the v0.1.14 notes below). +A migration is additive when the previous release serves the catalog correctly with it applied, and breaking otherwise. Migrations 1 to 7 and 9 to 13 are breaking. Migration 8 creates a table in the PostgreSQL data database that the previous release never reads; on PostgreSQL it is declared breaking only because the job that proves an additive declaration against the old binary does not yet exist (CONTRIBUTING, step 4 of adding a migration), and on SQLite, MongoDB and Cassandra it does not apply (`migrate --list` prints it as not applicable, and `migrate` counts it as additive). Do not run a server of 0.1.14 or an earlier release against a migrated catalog. A binary of those releases that writes to a migrated catalog (its `migrate --yes`, or a SQLite dev server) leaves it WrittenByOlderRelease. `migrate --yes --reconverge` repairs it by running the convergent migrations again. Migration 2, which rewrites stored policies, migration 11, which rewrites stored attribute names on PostgreSQL, and migration 13, which re-encodes stored strings on PostgreSQL, are not convergent: the repair skips them and prints a line for each that says so (see the v0.1.14 notes below). ### Migration 6: the backup catalog index From f24c51bf95893d50f19771abe31c99bff7986267 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:28:33 +0000 Subject: [PATCH 21/30] test(storage-postgres): give the stream_pending row of the guard test a shard The stream_pending row that only_a_store_with_rows_is_checked adds failed the foreign key on stream_shards. The test now adds the shard row shard-0 first. data_has_rows does not count stream_shards, so stream_pending still holds the only row that the check counts. The seed that follows adds shard-1, so the two shard rows do not collide. --- .../src/migrations/m0013_guard_tests.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs index 2dee0a756..994dbf0fa 100644 --- a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs @@ -189,10 +189,13 @@ async fn only_a_store_with_rows_is_checked() { let s = scratch().await; assert!(!catalog_has_rows(&s.db).await.unwrap()); assert!(!data_has_rows(&s.db, &s.db).await.unwrap()); - // A store whose only row is a stream record waiting for its number. - sqlx::query( - "INSERT INTO stream_pending (shard_id, table_id, event_name, record_data, \ - record_bytes, created_at) VALUES ('shard-1', 't1', 'INSERT', '{}', 2, now())", + // A store whose only counted row is a stream record waiting for its + // number. Its shard row is not one that the check counts. + sqlx::raw_sql( + "INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \ + VALUES ('shard-0', 't0', '1'); \ + INSERT INTO stream_pending (shard_id, table_id, event_name, record_data, \ + record_bytes, created_at) VALUES ('shard-0', 't0', 'INSERT', '{}', 2, now())", ) .execute(&s.db) .await From 8dc809103d8a5fbc3aa5adbf5116a18101c01705 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:44:11 +0000 Subject: [PATCH 22/30] test(storage-postgres): give the guard test the data database's stream_shards The scratch database of the migration 13 tests holds the catalog and the data tables in one database. Its stream_shards is the catalog's, whose table_id references tables, so the shard row that only_a_store_with_rows_is_checked adds needs a tables row. A tables row makes data_has_rows true by itself, and the check of stream_pending is then not tested. The data database's stream_shards has no such key (docs/schema/postgres.txt). So the test drops the key in its scratch, and then it adds the shard row and the stream_pending row. --- crates/storage-postgres/src/migrations/m0013_guard_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs index 994dbf0fa..9fbab36f6 100644 --- a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs @@ -190,9 +190,11 @@ async fn only_a_store_with_rows_is_checked() { assert!(!catalog_has_rows(&s.db).await.unwrap()); assert!(!data_has_rows(&s.db, &s.db).await.unwrap()); // A store whose only counted row is a stream record waiting for its - // number. Its shard row is not one that the check counts. + // number. This scratch holds the catalog's stream_shards, whose table_id + // references tables; the data database's has no such key. sqlx::raw_sql( - "INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \ + "ALTER TABLE stream_shards DROP CONSTRAINT stream_shards_table_id_fkey; \ + INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \ VALUES ('shard-0', 't0', '1'); \ INSERT INTO stream_pending (shard_id, table_id, event_name, record_data, \ record_bytes, created_at) VALUES ('shard-0', 't0', 'INSERT', '{}', 2, now())", From a3b5dcf242bd740785582da5e8a7da006f345776 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:53:07 +0000 Subject: [PATCH 23/30] docs(storage): say that the in-catalog item decode follows the data path The LegacyBackupReader doc called the item decode of the in-catalog paths frozen. Since the merge, PostgreSQL decodes those items with json_to_item. Since a4ec2aa2a, MongoDB decodes them with document_to_item. Both are the data path's decode, so the trait doc now lists the item decode among the parts that are not frozen. The MongoDB items doc says what a backup taken before the escape reads back. The catalog_json module doc names backup_items among the escaped item documents. --- crates/storage-mongodb/src/backup_engine.rs | 9 ++++++--- crates/storage-postgres/src/catalog_json.rs | 4 ++-- crates/storage/src/backup_catalog.rs | 10 +++++++--- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/storage-mongodb/src/backup_engine.rs b/crates/storage-mongodb/src/backup_engine.rs index ac6eb880b..22edadf80 100644 --- a/crates/storage-mongodb/src/backup_engine.rs +++ b/crates/storage-mongodb/src/backup_engine.rs @@ -1985,9 +1985,12 @@ impl LegacyBackupReader for MongoEngine { /// The AVAILABLE backup document (its source as `restore_source` reads /// it), then a cursor over its `_backup_` collection in /// batches of [`paging::DEFAULT_FETCH_BATCH`] documents. The collection - /// is a copy of the table's documents in their stored form, field names - /// escaped included, so each is decoded as the data path decodes a - /// stored document ([`document_to_item`]). The collection is immutable + /// is a copy of the table's documents in their stored form, with the + /// field names as the release that took it stored them, so each is + /// decoded as the data path decodes a stored document + /// ([`document_to_item`]). A backup taken before the escape holds raw + /// names, which read back as the data path reads that release's + /// documents (see `item_data_to_json`). The collection is immutable /// while the backup is AVAILABLE, so no snapshot is held; a /// DeleteBackup's drop ends the cursor with an error. fn items( diff --git a/crates/storage-postgres/src/catalog_json.rs b/crates/storage-postgres/src/catalog_json.rs index 4af184ce2..27727d56e 100644 --- a/crates/storage-postgres/src/catalog_json.rs +++ b/crates/storage-postgres/src/catalog_json.rs @@ -38,8 +38,8 @@ //! name, so migration 11 rewrites every stored document through the escape //! once (`migrations/m0011_attribute_name_escape.rs`). //! -//! The item documents (`item_data`, the stream record images, the images in -//! `gsi_pending`) are stored through the same escape: `data::item_to_json` +//! The item documents (`item_data`, `backup_items`, the stream record +//! images, the images in `gsi_pending`) are stored through the same escape: `data::item_to_json` //! and `data::json_to_item` call these functions, and the records in //! `stream_pending` and `stream_records` are written and read through them. //! Migration 11 leaves those documents as they are; migration 13 diff --git a/crates/storage/src/backup_catalog.rs b/crates/storage/src/backup_catalog.rs index 972aacfdd..ca05e5725 100644 --- a/crates/storage/src/backup_catalog.rs +++ b/crates/storage/src/backup_catalog.rs @@ -1752,11 +1752,15 @@ pub trait JobClaim: Send + Sync { /// deleted ones through [`Self::list_deleted`]), and ends with /// [`Self::replace_with_index_row`]. /// -/// Two parts are not frozen. A restore registers through the restore job +/// Three parts are not frozen. A restore registers through the restore job /// fields (`kind = legacy`, the claim), so the reconciler finds a restore -/// whose owner died as it finds any other. And +/// whose owner died as it finds any other. /// [`Self::replace_with_index_row`] writes a catalog index row in the step -/// that removes the in-catalog backup. +/// that removes the in-catalog backup. And [`Self::items`] and the +/// in-catalog restore decode each item through the backend's data path +/// decode (`json_to_item` on PostgreSQL, `document_to_item` on MongoDB), so +/// a stored name reads back through the escape of the release that reads +/// it. pub trait LegacyBackupReader: Send + Sync { /// Create an in-catalog backup of a table, snapshotting all items. The /// permit is the job's slot, released when the create ends. From c62aa6e841da70f666e14cf4df9a4c76886c8420 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:44:25 +0000 Subject: [PATCH 24/30] fix(storage-postgres): keep key text as main stores it and refuse U+0000 in a key The escape of U+0000 and U+0001 made a stored key one byte longer for each of those characters. A 2046-byte partition key with 682 U+0001, which DynamoDB and main store, became 2728 bytes, over the btree entry limit of 2704. Its PutItem answered 500. The queue held a GSI key of that shape and never indexed it. Migration 13 stopped on such a row after the catalog body committed. The key columns now hold the key text that main stores. Every site that produces key text calls the key_text wrappers. They refuse a string key value that holds U+0000 with a ValidationException naming the PostgreSQL limitation. Writes check index keys too. PutItem, UpdateItem and the TransactWriteItems pre-pass refuse a write whose key for one of the table's indexes holds U+0000, before its first statement. A transacted Update that computes such a key cancels with a ValidationError reason. gsi_build::indexable leaves such an item out of an index, as it leaves out an item whose key has another type. The queue, the backfill and a restore skip it. Migration 13 rewrites the item documents alone. The key column rewrite, its row-by-row order (order.rs), the composite key rebuild (keys.rs) and the recompute of gsi_pending.worker_partition are gone. gsi_queue goes back to main's partition code. The migration keeps its own copy of the escape (escape.rs), so that its checksum covers what it writes. transactions.rs takes pk_to_text from key_text. Tests: - test_nul_strings.py: the tests that put U+0000 in a key skip on PostgreSQL. test_postgresql_refuses_nul_in_a_key_value checks the refusal on 13 request shapes and on a transacted Update. test_a_long_key_holding_u0001_is_stored stores the two 2046-byte shapes. - migration_13_applies_over_a_long_key_holding_u0001 requires migration 13 in both ledgers over such a key. - reencodes_legacy_rows adds a vector index table, a DELETING table with an index and a table with no physical table, and checks their notes. - the_catalog_body_stops_a_run_while_another_session_holds_the_catalog calls the catalog body's detect. - The restore test adds an item with U+0000 in its GSI key, which the restore leaves out of the index. --- crates/storage-postgres/src/backup_engine.rs | 8 +- .../storage-postgres/src/data/data_engine.rs | 6 +- crates/storage-postgres/src/data/gsi_build.rs | 18 +- crates/storage-postgres/src/data/key_text.rs | 321 ++++++------- crates/storage-postgres/src/data/put_item.rs | 3 +- .../storage-postgres/src/data/transactions.rs | 36 +- .../storage-postgres/src/data/update_item.rs | 3 +- crates/storage-postgres/src/gsi_queue.rs | 29 +- .../src/migrations/backend.rs | 17 + .../m0013_escape_control_chars/escape.rs | 49 ++ .../m0013_escape_control_chars/keys.rs | 135 ------ .../m0013_escape_control_chars/mod.rs | 415 +++++------------ .../m0013_escape_control_chars/order.rs | 119 ----- .../src/migrations/m0013_guard_tests.rs | 61 ++- .../src/migrations/m0013_keys_tests.rs | 340 -------------- .../src/migrations/m0013_order_tests.rs | 389 ---------------- .../src/migrations/m0013_tests.rs | 138 +++++- crates/storage-postgres/src/migrations/mod.rs | 4 - .../tests/backup_restore/control_chars.rs | 42 +- .../golden/0013_escape_control_chars.txt | 128 +++--- .../tests/migrations_golden.rs | 66 ++- .../tests/restore_job/control_chars.rs | 8 +- crates/storage/src/util/key.rs | 4 +- tests/test_nul_strings.py | 422 +++++++++++++----- 24 files changed, 1035 insertions(+), 1726 deletions(-) create mode 100644 crates/storage-postgres/src/migrations/m0013_escape_control_chars/escape.rs delete mode 100644 crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs delete mode 100644 crates/storage-postgres/src/migrations/m0013_escape_control_chars/order.rs delete mode 100644 crates/storage-postgres/src/migrations/m0013_keys_tests.rs delete mode 100644 crates/storage-postgres/src/migrations/m0013_order_tests.rs diff --git a/crates/storage-postgres/src/backup_engine.rs b/crates/storage-postgres/src/backup_engine.rs index 11131e480..0a33b8f4b 100755 --- a/crates/storage-postgres/src/backup_engine.rs +++ b/crates/storage-postgres/src/backup_engine.rs @@ -39,7 +39,7 @@ use futures::future::BoxFuture; use crate::PostgresEngine; use crate::catalog_json::{escape_json, from_catalog_json, to_catalog_json, unescape_json}; use crate::create_table::{RestoreRegistration, RestoreSource}; -use crate::data::key_text::{composite_pk_to_text, parse_sk}; +use crate::data::key_text::{composite_pk_to_text, holds_nul_key, parse_sk}; use crate::data::{ all_sort_key_info, data_table_name, index_table_name, insert_index_rows_multi, item_has_index_keys, json_to_item, project_item_for_index, table_storage_relations, @@ -242,9 +242,13 @@ pub(crate) async fn insert_restore_rows( for idx in indexes { let idx_sks = all_sort_key_info(&idx.key_schema, attribute_definitions); + // An item whose key for the index holds U+0000 is left out of it, as + // the backfill leaves it out (`gsi_build::indexable`). let projected: Vec<(&Item, Item)> = batch .iter() - .filter(|(item, _)| item_has_index_keys(item, &idx.key_schema)) + .filter(|(item, _)| { + item_has_index_keys(item, &idx.key_schema) && !holds_nul_key(item, &idx.key_schema) + }) .map(|(item, _)| { ( item, diff --git a/crates/storage-postgres/src/data/data_engine.rs b/crates/storage-postgres/src/data/data_engine.rs index de71c0f2b..c698c37a1 100755 --- a/crates/storage-postgres/src/data/data_engine.rs +++ b/crates/storage-postgres/src/data/data_engine.rs @@ -201,10 +201,8 @@ impl DataEngine for PostgresEngine { // ((hashtext(pk)::bigint & 2147483647) % total = seg), evaluated for // the candidate key. `key_info` is scan-shaped, so `key_schema[0]` is // the pk of whichever table (data or index) the scan targets, matching - // the `pk` column the predicate hashes, so the key text is the stored - // (escaped) form, as `pk_to_text` from `key_text` gives it. Bigint - // bitmask instead of abs() per CB-20 / SP-SCN-002 (hashtext() == - // i32::MIN). + // the `pk` column the predicate hashes. Bigint bitmask instead of + // abs() per CB-20 / SP-SCN-002 (hashtext() == i32::MIN). let pk_name = key_info.key_schema[0].attribute_name.clone(); let key = key.clone(); Box::pin(async move { diff --git a/crates/storage-postgres/src/data/gsi_build.rs b/crates/storage-postgres/src/data/gsi_build.rs index 0c89f1ab1..4368f2ac6 100644 --- a/crates/storage-postgres/src/data/gsi_build.rs +++ b/crates/storage-postgres/src/data/gsi_build.rs @@ -282,12 +282,15 @@ fn params(start: usize, n: usize) -> String { } /// Whether an item belongs in the index: every key attribute present, of the -/// declared type, and not empty. +/// declared type, and not empty, and no string key holding U+0000, which the +/// key columns cannot hold. /// /// An item that fails is left out of the index rather than failing the build or /// stalling a queue partition. It can only be an item written before the index /// existed, or by a writer that had not yet seen the index's attribute -/// definitions; the service skips such items in a backfill too. +/// definitions; the service skips such items in a backfill too. A write that +/// sees the index refuses an item whose key for it holds U+0000 +/// (`key_text::refuse_nul_index_keys`). pub(crate) fn indexable( item: &Item, index_ks: &[KeySchemaElement], @@ -302,7 +305,9 @@ pub(crate) fn indexable( .find(|ad| ad.attribute_name == ks.attribute_name) .map(|ad| ad.attribute_type); match (declared, value) { - (Some(ScalarAttributeType::S), AttributeValue::S(s)) => !s.is_empty(), + (Some(ScalarAttributeType::S), AttributeValue::S(s)) => { + !s.is_empty() && !s.contains('\0') + } (Some(ScalarAttributeType::N), AttributeValue::N(n)) => { n.parse::().is_ok() } @@ -1430,6 +1435,13 @@ mod tests { assert!(indexable(&item, &index_ks, &defs)); item.insert("g".into(), AttributeValue::S(String::new())); assert!(!indexable(&item, &index_ks, &defs), "empty string key"); + item.insert("g".into(), AttributeValue::S("a\u{0}".into())); + assert!( + !indexable(&item, &index_ks, &defs), + "U+0000 in a string key" + ); + item.insert("g".into(), AttributeValue::S("a\u{1}".into())); + assert!(indexable(&item, &index_ks, &defs), "U+0001 in a string key"); } #[test] diff --git a/crates/storage-postgres/src/data/key_text.rs b/crates/storage-postgres/src/data/key_text.rs index eec5cb946..b37fe3884 100644 --- a/crates/storage-postgres/src/data/key_text.rs +++ b/crates/storage-postgres/src/data/key_text.rs @@ -5,243 +5,190 @@ //! The shared helpers in `extenddb_storage::util` turn key attribute values into //! the text the SQL backends bind against `pk`, `sk_s`, `base_pk`, and the other //! string key columns. `PostgreSQL` `TEXT` cannot hold the byte 0x00, which -//! DynamoDB allows anywhere in a string key, so this module wraps those helpers -//! and passes every string component through the order-preserving escape from -//! `extenddb_storage::util::escape_control`. Numbers and base64 binaries contain -//! neither U+0000 nor U+0001 and are unchanged. The escape preserves byte order -//! and prefixes, so the `COLLATE "C"` comparisons, `BETWEEN`, `begins_with`, -//! and row-comparison cursors that run on these columns return the same rows -//! they would on the raw text. +//! DynamoDB allows anywhere in a string key. The key columns hold the text the +//! shared helpers give, as every earlier release stored it, and these wrappers +//! refuse a string key value that holds U+0000 with a `ValidationException` +//! ([`NUL_IN_KEY`]) instead of a statement that fails. Numbers and base64 +//! binaries never hold U+0000. The item documents in `item_data` hold U+0000 +//! through the escape of `data::item_to_json`; the key columns are not escaped, +//! so a key keeps the bytes and the length an earlier release stored for it. //! //! Every site in this crate that produces key column text imports these three -//! functions instead of the shared ones, so the write path, the read path, index -//! rows, cursors, and the propagation queue all agree on the stored form. +//! functions instead of the shared ones, so a write, a read, an index row and a +//! cursor refuse the same keys. A write also refuses an item whose key for one +//! of the table's indexes holds U+0000 ([`refuse_nul_index_keys`]), before its +//! first statement, because the queue writes an asynchronous index's rows after +//! the write commits. use std::borrow::Cow; -use extenddb_core::types::{AttributeValue, Item, KeySchemaElement, KeyType, ScalarAttributeType}; +use extenddb_core::types::{AttributeValue, Item, KeySchemaElement, ScalarAttributeType}; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{self, SortKeyValue, encode_netstring_composite, escape_control}; +use extenddb_storage::util::{self, SortKeyValue}; -/// Partition key attribute value as escaped column text. +use super::index::{IndexMeta, item_has_index_keys}; + +/// The answer to a key value that holds U+0000. +pub(crate) const NUL_IN_KEY: &str = "Key attribute values cannot contain the character \ + U+0000 on the PostgreSQL storage backend, whose text columns cannot hold the byte 0x00. \ + Remove the character from the key value, or use another storage backend."; + +/// Refuse key text that holds U+0000 ([`NUL_IN_KEY`]). +fn refuse_nul(text: &str) -> Result<(), StorageError> { + if text.as_bytes().contains(&0) { + return Err(StorageError::Validation(NUL_IN_KEY.to_owned())); + } + Ok(()) +} + +/// Partition key attribute value as column text. pub(crate) fn pk_to_text(value: &AttributeValue) -> Result, StorageError> { - Ok(match util::pk_to_text(value)? { - Cow::Borrowed(s) => escape_control(s), - Cow::Owned(s) => Cow::Owned(escape_control(&s).into_owned()), - }) + let text = util::pk_to_text(value)?; + refuse_nul(&text)?; + Ok(text) } -/// Composite partition key as escaped column text. -/// -/// Mirrors `extenddb_storage::util::composite_pk_to_text`: a single HASH -/// attribute is its own text, several are netstring-joined. Each part is -/// escaped before joining, which is also what `query_scan` does when it builds -/// the same text from a key condition, so the two agree byte for byte. +/// Composite partition key as column text: a single HASH attribute is its own +/// text, several are netstring-joined (`extenddb_storage::util::composite_pk_to_text`). +/// The join holds U+0000 exactly when a part does. pub(crate) fn composite_pk_to_text( item: &Item, key_schema: &[KeySchemaElement], ) -> Result { - let hash_elements: Vec<_> = key_schema - .iter() - .filter(|ks| ks.key_type == KeyType::Hash) - .collect(); - if hash_elements.len() == 1 { - let val = item - .get(&hash_elements[0].attribute_name) - .ok_or_else(|| StorageError::Internal("missing partition key".to_owned()))?; - return Ok(pk_to_text(val)?.into_owned()); - } - let mut parts = Vec::with_capacity(hash_elements.len()); - for ks in &hash_elements { - let val = item.get(&ks.attribute_name).ok_or_else(|| { - StorageError::Internal(format!( - "missing partition key attribute {}", - ks.attribute_name - )) - })?; - parts.push(util::pk_to_text(val)?); - } - Ok(join_escaped_parts(&parts)) + let text = util::composite_pk_to_text(item, key_schema)?; + refuse_nul(&text)?; + Ok(text) } -/// The stored text of a composite partition key whose parts, as -/// `extenddb_storage::util::pk_to_text` renders each HASH attribute, are -/// `raw_parts`: each part escaped, then netstring-joined. The netstring length -/// is that of the escaped part. -/// -/// [`composite_pk_to_text`] builds every composite key column through this -/// function, and catalog migration 13, `escape_control_chars`, rebuilds legacy -/// composite key columns through it ([`reescape_legacy_composite`]). -pub(crate) fn join_escaped_parts>(raw_parts: &[S]) -> String { - let parts: Vec = raw_parts - .iter() - .map(|p| escape_control(p.as_ref()).into_owned()) - .collect(); - encode_netstring_composite(&parts) +/// Sort key attribute value as a typed bind value. +pub(crate) fn parse_sk( + value: &AttributeValue, + sk_type: ScalarAttributeType, +) -> Result { + let sk = util::parse_sk(value, sk_type)?; + if let SortKeyValue::S(s) = &sk { + refuse_nul(s)?; + } + Ok(sk) } -/// Split a netstring-joined composite key (`:,` per part, `len` -/// the part's length in bytes) into its parts. `None` when `text` is not a -/// sequence of well-formed netstrings. -pub(crate) fn split_netstring_composite(text: &str) -> Option> { - let mut parts = Vec::new(); - let mut rest = text; - while !rest.is_empty() { - let colon = rest.find(':')?; - let digits = &rest[..colon]; - if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - let len: usize = digits.parse().ok()?; - let start = colon + 1; - let end = start.checked_add(len)?; - let part = rest.get(start..end)?; - if rest.as_bytes().get(end) != Some(&b',') { - return None; - } - parts.push(part); - rest = &rest[end + 1..]; - } - (!parts.is_empty()).then_some(parts) +/// Whether one of the attributes of `key_schema` that `item` holds is a string +/// with U+0000. +pub(crate) fn holds_nul_key(item: &Item, key_schema: &[KeySchemaElement]) -> bool { + key_schema.iter().any( + |ks| matches!(item.get(&ks.attribute_name), Some(AttributeValue::S(s)) if s.contains('\0')), + ) } -/// The stored form of a composite key column that a build without the escape -/// wrote: its netstring parts hold raw text, so each is escaped and the parts -/// are joined again with the new lengths, as [`composite_pk_to_text`] writes the -/// same key. Escaping the whole text instead would leave every length prefix -/// counting the raw part. `None` when `legacy` is not a netstring. -pub(crate) fn reescape_legacy_composite(legacy: &str) -> Option { - split_netstring_composite(legacy).map(|parts| join_escaped_parts(&parts)) +/// Refuse `item` when its key under `key_schema` holds U+0000, with the error +/// the key text functions return. +pub(crate) fn refuse_nul_key( + item: &Item, + key_schema: &[KeySchemaElement], +) -> Result<(), StorageError> { + if holds_nul_key(item, key_schema) { + return Err(StorageError::Validation(NUL_IN_KEY.to_owned())); + } + Ok(()) } -/// Sort key attribute value as a typed bind value, string keys escaped. -pub(crate) fn parse_sk( - value: &AttributeValue, - sk_type: ScalarAttributeType, -) -> Result { - Ok(match util::parse_sk(value, sk_type)? { - SortKeyValue::S(s) => SortKeyValue::S(escape_control(&s).into_owned()), - other => other, - }) +/// Refuse a written item that holds every key attribute of one of `indexes` +/// and whose key for that index holds U+0000. An index row that the queue or +/// a backfill writes later leaves such an item out (`gsi_build::indexable`), +/// as it leaves out an item written before the index existed. +pub(crate) fn refuse_nul_index_keys( + item: &Item, + indexes: &[IndexMeta], +) -> Result<(), StorageError> { + for idx in indexes { + if item_has_index_keys(item, &idx.key_schema) { + refuse_nul_key(item, &idx.key_schema)?; + } + } + Ok(()) } #[cfg(test)] mod tests { + use extenddb_core::types::KeyType; + use super::*; - fn ks(name: &str) -> KeySchemaElement { + fn ks(name: &str, key_type: KeyType) -> KeySchemaElement { KeySchemaElement { attribute_name: name.to_owned(), - key_type: KeyType::Hash, + key_type, + } + } + + fn refused(result: Result) -> String { + match result { + Err(StorageError::Validation(message)) => message, + Err(other) => panic!("expected the refusal, got {other:?}"), + Ok(_) => panic!("expected the refusal, got a key text"), } } + const MESSAGE: &str = "Key attribute values cannot contain the character U+0000 on the \ + PostgreSQL storage backend, whose text columns cannot hold the byte 0x00. Remove the \ + character from the key value, or use another storage backend."; + #[test] - fn string_keys_are_escaped_and_other_types_are_not() { - assert_eq!( - pk_to_text(&AttributeValue::S("a\u{0}b".into())).unwrap(), - "a\u{1}\u{1}b" - ); + fn a_string_key_with_u0000_is_refused() { assert_eq!( - pk_to_text(&AttributeValue::S("plain".into())).unwrap(), - "plain" + refused(pk_to_text(&AttributeValue::S("a\u{0}b".into()))), + MESSAGE ); assert_eq!( - pk_to_text(&AttributeValue::N("12.5".into())).unwrap(), - "12.5" + refused(parse_sk( + &AttributeValue::S("\u{0}".into()), + ScalarAttributeType::S + )), + MESSAGE ); - assert_eq!( - pk_to_text(&AttributeValue::B(vec![0, 1, 2])).unwrap(), - util::pk_to_text(&AttributeValue::B(vec![0, 1, 2])).unwrap() - ); - match parse_sk(&AttributeValue::S("\u{1}".into()), ScalarAttributeType::S).unwrap() { - SortKeyValue::S(s) => assert_eq!(s, "\u{1}\u{2}"), - _ => panic!("string sort key"), - } - match parse_sk(&AttributeValue::B(vec![0]), ScalarAttributeType::B).unwrap() { - SortKeyValue::B(b) => assert_eq!(b, vec![0]), - _ => panic!("binary sort key"), - } - } - - #[test] - fn composite_text_escapes_each_part_before_joining() { let mut item = Item::new(); - item.insert("h1".to_owned(), AttributeValue::S("a\u{0}".into())); - item.insert("h2".to_owned(), AttributeValue::S("b".into())); - let text = composite_pk_to_text(&item, &[ks("h1"), ks("h2")]).unwrap(); - // The escaped part is three bytes, and the netstring length says so. - assert_eq!(text, "3:a\u{1}\u{1},1:b,"); - assert!(!text.contains('\u{0}')); - // Single hash attribute: the escaped value itself. - let text = composite_pk_to_text(&item, &[ks("h1")]).unwrap(); - assert_eq!(text, "a\u{1}\u{1}"); + item.insert("h1".to_owned(), AttributeValue::S("a".into())); + item.insert("h2".to_owned(), AttributeValue::S("b\u{0}".into())); + let schema = [ks("h1", KeyType::Hash), ks("h2", KeyType::Hash)]; + assert_eq!(refused(composite_pk_to_text(&item, &schema)), MESSAGE); + assert_eq!(refused(refuse_nul_key(&item, &schema)), MESSAGE); + assert_eq!(refused(composite_pk_to_text(&item, &schema[1..])), MESSAGE); } #[test] - fn netstring_split_inverts_the_join() { - let cases: [&[&str]; 5] = [ - &["a", "b"], - &["", "x"], - &["1:a,", ",:", "z"], - &["a\u{1}\u{2}", "\u{e9}t\u{e9}", "12"], - &["only"], - ]; - for parts in cases { - let owned: Vec = parts.iter().map(|p| (*p).to_owned()).collect(); - let joined = encode_netstring_composite(&owned); + fn other_keys_keep_the_text_of_the_shared_helpers() { + // U+0001 is stored as it is, as every earlier release stored it. + for value in [ + AttributeValue::S("a\u{1}\u{2}b".into()), + AttributeValue::S("plain".into()), + AttributeValue::N("12.5".into()), + AttributeValue::B(vec![0, 1, 2]), + ] { assert_eq!( - split_netstring_composite(&joined).as_deref(), - Some(parts), - "{joined:?}" + pk_to_text(&value).unwrap(), + util::pk_to_text(&value).unwrap(), + "{value:?}" ); } - for bad in [ - "", - "a", - "1:ab,", - "2:a,", - "x:ab,", - "+1:a,", - "1:a", - "1:a,2", - "1:\u{e9},", - ] { - assert_eq!(split_netstring_composite(bad), None, "{bad:?}"); + match parse_sk(&AttributeValue::S("\u{1}".into()), ScalarAttributeType::S).unwrap() { + SortKeyValue::S(s) => assert_eq!(s, "\u{1}"), + _ => panic!("string sort key"), + } + match parse_sk(&AttributeValue::B(vec![0]), ScalarAttributeType::B).unwrap() { + SortKeyValue::B(b) => assert_eq!(b, vec![0]), + _ => panic!("binary sort key"), } - } - - #[test] - fn a_legacy_composite_key_is_rebuilt_as_the_write_path_builds_it() { - // The case from the review: a raw U+0001 in the first of two HASH - // parts. Escaping the whole text would give 2:a\x01\x02,1:b, with a - // length prefix that no longer matches its part. - let legacy = "2:a\u{1},1:b,"; - let rebuilt = reescape_legacy_composite(legacy).expect("a netstring"); - assert_eq!(rebuilt, "3:a\u{1}\u{2},1:b,"); - let mut item = Item::new(); item.insert("h1".to_owned(), AttributeValue::S("a\u{1}".into())); item.insert("h2".to_owned(), AttributeValue::S("b".into())); + item.insert("v".to_owned(), AttributeValue::S("\u{0}".into())); + let schema = [ks("h1", KeyType::Hash), ks("h2", KeyType::Hash)]; assert_eq!( - composite_pk_to_text(&item, &[ks("h1"), ks("h2")]).unwrap(), - rebuilt - ); - - // Parts without U+0001 keep their text and their lengths. - assert_eq!( - reescape_legacy_composite("1:x,2:yz,").as_deref(), - Some("1:x,2:yz,") + composite_pk_to_text(&item, &schema).unwrap(), + "2:a\u{1},1:b," ); - assert_eq!(reescape_legacy_composite("a\u{1}b"), None); - } - - #[test] - fn stored_text_never_contains_nul() { - for raw in ["\u{0}", "a\u{0}b", "\u{0}\u{1}\u{2}", "x\u{1}\u{1}y"] { - let av = AttributeValue::S(raw.into()); - let text = pk_to_text(&av).unwrap(); - assert!(!text.contains('\u{0}'), "{raw:?} -> {text:?}"); - } + // A U+0000 outside the key does not concern the key. + assert!(refuse_nul_key(&item, &schema).is_ok()); + assert!(refuse_nul_key(&item, &[ks("v", KeyType::Range)]).is_err()); } } diff --git a/crates/storage-postgres/src/data/put_item.rs b/crates/storage-postgres/src/data/put_item.rs index 1e06bfd72..3f2518a84 100755 --- a/crates/storage-postgres/src/data/put_item.rs +++ b/crates/storage-postgres/src/data/put_item.rs @@ -9,7 +9,7 @@ use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; use extenddb_storage::util::{sk_column, sk_info}; -use super::key_text::{composite_pk_to_text, parse_sk, pk_to_text}; +use super::key_text::{composite_pk_to_text, parse_sk, pk_to_text, refuse_nul_index_keys}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; @@ -74,6 +74,7 @@ impl PostgresEngine { super::index::fresh_attr_defs(&indexes, &key_info.attribute_definitions), ) .map_err(|e| StorageError::Validation(e.to_string()))?; + refuse_nul_index_keys(&item, &indexes)?; } // Read whenever anything can propagate, secondary or vector. Gating this on diff --git a/crates/storage-postgres/src/data/transactions.rs b/crates/storage-postgres/src/data/transactions.rs index 480847fbf..386b2f873 100644 --- a/crates/storage-postgres/src/data/transactions.rs +++ b/crates/storage-postgres/src/data/transactions.rs @@ -12,12 +12,12 @@ use extenddb_core::types::{ }; use extenddb_core::validation; use extenddb_storage::error::StorageError; -use extenddb_storage::util::pk_to_text; use extenddb_storage::{IdempotencyKey, StreamCapture, TransactGetOp, TransactWriteOp}; use super::index::{ IndexMeta, db_error, enqueue_async_indexes, fetch_write_path_indexes, sync_indexes, }; +use super::key_text::{NUL_IN_KEY, pk_to_text, refuse_nul_index_keys, refuse_nul_key}; use super::tx_helpers::{ check_idempotency_token_in_tx, delete_item_in_tx, fetch_item_for_update, fetch_item_in_tx, insert_item_if_absent_in_tx, stream_record_shard_in_tx, upsert_item_in_tx, @@ -177,6 +177,15 @@ impl PostgresEngine { }); } } + // A member key, or an index key of a Put item, that this backend + // cannot store refuses the request before any row is locked. + for op in ops { + let (key_info, key) = transact_op_key(op); + refuse_nul_key(key, &key_info.key_schema)?; + if let TransactWriteOp::Put { item, .. } = op { + refuse_nul_index_keys(item, &table_indexes[transact_op_table_name(op)])?; + } + } // Run the ops in key order, not request order, so every transaction // locks its items in one global order and two cannot deadlock on each @@ -400,12 +409,7 @@ fn execution_order(ops: &[TransactWriteOp<'_>]) -> Vec { /// The table and the primary key values of the item an op touches. fn lock_key<'a>(op: &'a TransactWriteOp<'_>) -> (&'a str, Vec>) { - let (key_info, key) = match op { - TransactWriteOp::Put { key_info, item, .. } => (key_info, *item), - TransactWriteOp::Delete { key_info, key, .. } - | TransactWriteOp::Update { key_info, key, .. } - | TransactWriteOp::ConditionCheck { key_info, key, .. } => (key_info, *key), - }; + let (key_info, key) = transact_op_key(op); let values = key_info .key_schema .iter() @@ -418,6 +422,17 @@ fn lock_key<'a>(op: &'a TransactWriteOp<'_>) -> (&'a str, Vec>) { (&key_info.table_id, values) } +/// The key info of an op and the item that carries its key: a Put's item, or +/// the key of the other ops. +fn transact_op_key<'a>(op: &'a TransactWriteOp<'_>) -> (&'a TableKeyInfo, &'a Item) { + match op { + TransactWriteOp::Put { key_info, item, .. } => (key_info, *item), + TransactWriteOp::Delete { key_info, key, .. } + | TransactWriteOp::Update { key_info, key, .. } + | TransactWriteOp::ConditionCheck { key_info, key, .. } => (key_info, *key), + } +} + /// Extract the table name from a transactional write operation. fn transact_op_table_name<'a>(op: &'a TransactWriteOp<'_>) -> &'a str { match op { @@ -784,6 +799,13 @@ async fn execute_transact_write_op( .map_err(|e| { TxnOpError::Cancel(CancellationReason::index_key_empty_abort(e.to_string())) })?; + // An index key this backend cannot store, computed by the + // update. + if refuse_nul_index_keys(&item, indexes).is_err() { + return Err(TxnOpError::Cancel(CancellationReason::validation_error( + NUL_IN_KEY, + ))); + } Ok(item) }; // Evaluate condition against empty item if non-existent (DynamoDB semantics) diff --git a/crates/storage-postgres/src/data/update_item.rs b/crates/storage-postgres/src/data/update_item.rs index 01405c0c8..cafa25561 100755 --- a/crates/storage-postgres/src/data/update_item.rs +++ b/crates/storage-postgres/src/data/update_item.rs @@ -10,7 +10,7 @@ use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; use extenddb_storage::util::{sk_column, sk_info}; -use super::key_text::{parse_sk, pk_to_text}; +use super::key_text::{parse_sk, pk_to_text, refuse_nul_index_keys}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; @@ -230,6 +230,7 @@ impl PostgresEngine { validation::SecondaryIndexEmptyContext::UpdateExpression, ) .map_err(|e| StorageError::Validation(e.to_string()))?; + refuse_nul_index_keys(&item, &indexes)?; } // REMOVE and DELETE on a key that holds no row change nothing: the diff --git a/crates/storage-postgres/src/gsi_queue.rs b/crates/storage-postgres/src/gsi_queue.rs index f5d391284..8ef6604e5 100644 --- a/crates/storage-postgres/src/gsi_queue.rs +++ b/crates/storage-postgres/src/gsi_queue.rs @@ -159,7 +159,7 @@ const PG_UNDEFINED_TABLE: &str = "SQLSTATE 42P01"; /// order. A local /// hash (not `std`'s, which is not guaranteed stable across builds) keeps the /// mapping fixed for a given key forever. -pub(crate) fn partition_for(base_pk_text: &str) -> i32 { +fn partition_for(base_pk_text: &str) -> i32 { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a offset basis for byte in base_pk_text.as_bytes() { hash ^= u64::from(*byte); @@ -168,24 +168,6 @@ pub(crate) fn partition_for(base_pk_text: &str) -> i32 { (hash % NUM_WORKERS) as i32 } -/// The `worker_partition` of a queued row: the partition of its base key, -/// which `new_item` carries for puts and updates and `old_item` for deletes -/// (the base key is immutable over an item's lifetime). The key text is the -/// stored (escaped) form, so a key holding U+0001 hashes differently from the -/// raw text a build without the escape hashed; catalog migration 13, -/// `escape_control_chars`, recomputes the column of such rows through this -/// function. -pub(crate) fn worker_partition( - old_item: Option<&Item>, - new_item: Option<&Item>, - context: &PendingApplyContext, -) -> Result { - Ok(match new_item.or(old_item) { - Some(item) => partition_for(&composite_pk_to_text(item, context.base_key_schema())?), - None => 0, - }) -} - /// Check if a `StorageError` is caused by an undefined table (SQLSTATE 42P01). /// /// This occurs when an index table is dropped (table deleted) while an async @@ -348,7 +330,14 @@ pub(crate) async fn enqueue_gsi_pending( // catalog documents it was read from (`catalog_json`); the item images // are stored in the form of `item_data` (`item_to_json`). let context_json = to_catalog_json(context)?; - let worker_partition = worker_partition(old_item, new_item, context)?; + + // Route all updates for a given base item to one worker. + // The base key is immutable over an item's lifetime; `new_item` carries it + // for puts/updates, `old_item` for deletes. + let worker_partition = match new_item.or(old_item) { + Some(item) => partition_for(&composite_pk_to_text(item, context.base_key_schema())?), + None => 0, + }; let delay_interval = jitter_delay_ms(delay_ms) as f64 / 1000.0; sqlx::query( diff --git a/crates/storage-postgres/src/migrations/backend.rs b/crates/storage-postgres/src/migrations/backend.rs index aa99706ea..d1f06a3d6 100644 --- a/crates/storage-postgres/src/migrations/backend.rs +++ b/crates/storage-postgres/src/migrations/backend.rs @@ -106,6 +106,23 @@ impl HasManagementStore for PostgresStores { } } +#[cfg(test)] +impl PostgresStores { + /// The stores of a run over `catalog` and `data`, which look for other + /// sessions, for a test that calls a body's `detect`. + pub(crate) fn for_detect(catalog: PgPool, data: PgPool) -> Self { + Self { + management: PostgresCatalogStore::new(catalog.clone()), + catalog, + data, + data_watch: None, + lock: None, + application: runner_application(), + checks_sessions: true, + } + } +} + /// The catalog's stores under a held migration lock, for `encryption-key /// switch`, `rotate` and `reset` (RFC-0000 section 8, common rules): the /// management store over the runner's catalog connection, holding no key. diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/escape.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/escape.rs new file mode 100644 index 000000000..a4e9a9ab9 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/escape.rs @@ -0,0 +1,49 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Migration 13's copy of the escape that the item documents are stored +//! through (`extenddb_storage::util::escape_json_strings`): U+0000 as U+0001 +//! U+0001, U+0001 as U+0001 U+0002, every other character as it is. It is +//! kept in this module so that the module's checksum covers it, and a later +//! change to the write path's escape cannot change what this migration +//! writes. + +use serde_json::Value; + +/// The escaped form of one string, or `None` when it holds neither +/// character. +fn escape_str(s: &str) -> Option { + if !s.bytes().any(|b| b == 0 || b == 1) { + return None; + } + let mut out = String::with_capacity(s.len() + 8); + for ch in s.chars() { + match ch { + '\u{0}' => out.push_str("\u{1}\u{1}"), + '\u{1}' => out.push_str("\u{1}\u{2}"), + other => out.push(other), + } + } + Some(out) +} + +/// The escaped form of a document: every object key and string value, at +/// every depth. +pub(crate) fn escape_document(v: Value) -> Value { + match v { + Value::String(s) => match escape_str(&s) { + Some(t) => Value::String(t), + None => Value::String(s), + }, + Value::Array(items) => Value::Array(items.into_iter().map(escape_document).collect()), + Value::Object(map) => { + let mut out = serde_json::Map::with_capacity(map.len()); + for (k, val) in map { + let key = escape_str(&k).unwrap_or(k); + out.insert(key, escape_document(val)); + } + Value::Object(out) + } + other => other, + } +} diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs deleted file mode 100644 index 80948d131..000000000 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/keys.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Two rewrites of migration 13 that cannot be done by escaping a stored text -//! where it lies, because the text is derived from the key strings: -//! -//! - A partition key column of a key schema with more than one HASH attribute -//! holds the netstring join of the parts (`:,` each), and the -//! escape changes a part's length. [`rebuild_composite_rows`] splits each -//! legacy value, escapes the parts and joins them again with the new -//! lengths, through the function the write path uses -//! (`key_text::join_escaped_parts`). -//! - `gsi_pending.worker_partition` is a hash of the stored base key text -//! (`gsi_queue::partition_for`), so it changes with the key text. -//! [`recompute_worker_partitions`] recomputes it with the function the -//! enqueue uses (`gsi_queue::worker_partition`). -//! -//! Both run in the data body's transaction, after the table's other columns. - -use extenddb_storage::migrations::MigrationError; -use sqlx::PgConnection; - -use super::{db_error, rewrite_longest_first}; -use crate::data::key_text::reescape_legacy_composite; -use crate::gsi_queue::{PendingApplyContext, worker_partition}; - -/// The `backup_items` rows whose `pk` holds a composite key: the rows of a -/// backup whose table's key schema has more than one HASH attribute. A boolean -/// SQL expression over a `backup_items` row; `backups` is in the same catalog -/// database. -pub(crate) const BACKUP_ITEMS_COMPOSITE_ROWS: &str = "backup_arn IN (\ - SELECT b.backup_arn FROM backups b WHERE (\ - SELECT COUNT(*) FROM jsonb_array_elements(b.key_schema) e \ - WHERE e->>'KeyType' = 'HASH') > 1)"; - -/// Whether a catalog key schema (`[{"AttributeName", "KeyType"}, ...]`) has -/// more than one HASH attribute, so its partition key column holds a netstring -/// join. -pub(crate) fn has_composite_partition_key(key_schema: &serde_json::Value) -> bool { - key_schema.as_array().is_some_and(|elements| { - elements - .iter() - .filter(|e| e.get("KeyType").and_then(serde_json::Value::as_str) == Some("HASH")) - .count() - > 1 - }) -} - -/// Rebuild the composite key text in `col` of the rows that `rows` (a boolean -/// SQL expression over the row) selects and that hold U+0001, one row at a -/// time, longest legacy text first and in batches ([`rewrite_longest_first`]). -/// A SQL `replace()` over the whole text would leave each length prefix -/// counting the raw part (`2:a\x01,1:b,` would become `2:a\x01\x02,1:b,`, -/// where this release writes and looks up `3:a\x01\x02,1:b,`). A value that is -/// not a netstring fails the body, naming the table and column (`what`), and -/// the store's transaction rolls back. -pub(crate) async fn rebuild_composite_rows( - conn: &mut PgConnection, - quoted_table: &str, - col: &str, - rows: &str, - what: &str, -) -> Result { - rewrite_longest_first(conn, quoted_table, col, rows, what, |legacy| { - reescape_legacy_composite(legacy).ok_or_else(|| { - MigrationError::Store(format!( - "re-encode {what}: the composite key {legacy:?} is not a netstring" - )) - }) - }) - .await -} - -/// The partition a row queued with these columns gets from this release's -/// enqueue, or `None` when a column does not decode (a worker handles such a -/// row as a poison row, whatever partition holds it). -fn current_partition( - old_item: Option, - new_item: Option, - index_context: serde_json::Value, -) -> Option { - let old_item = old_item.map(crate::data::json_to_item).transpose().ok()?; - let new_item = new_item.map(crate::data::json_to_item).transpose().ok()?; - let context: PendingApplyContext = crate::catalog_json::from_catalog_json(index_context).ok()?; - worker_partition(old_item.as_ref(), new_item.as_ref(), &context).ok() -} - -/// Recompute `worker_partition` of the queued rows whose item holds U+0001, -/// after their jsonb columns were re-encoded in the same transaction. -/// -/// A release without the escape hashed the raw base key; this release hashes -/// the escaped one, so for a key holding U+0001 a row queued before the -/// upgrade and the next write of the same item would be claimed by different -/// workers, in either order, which breaks the queue's one item, one worker -/// rule. Every row of one item moves to the same new partition and keeps its -/// `id` and `ready_at`, so the item's rows are still claimed in write order, -/// and a row enqueued after the upgrade gets a `ready_at` no earlier than -/// theirs from the partition clamp in `enqueue_gsi_pending`. -pub(crate) async fn recompute_worker_partitions(conn: &mut PgConnection) -> Result { - type Row = ( - i64, - i32, - Option, - Option, - serde_json::Value, - ); - // '\u0001' is how jsonb::text renders U+0001; chr(92) spells the backslash - // as in `escape_jsonb_rows`. The base key is in new_item, or in old_item for - // a delete, as `worker_partition` reads it. - let rows: Vec = sqlx::query_as( - "SELECT id, worker_partition, old_item, new_item, index_context FROM gsi_pending \ - WHERE position((chr(92) || 'u0001') IN COALESCE(new_item, old_item)::text) > 0 \ - ORDER BY id FOR UPDATE", - ) - .fetch_all(&mut *conn) - .await - .map_err(|e| db_error("find the gsi_pending rows to repartition", &e))?; - let mut changed: u64 = 0; - for (id, stored, old_item, new_item, index_context) in rows { - let Some(partition) = current_partition(old_item, new_item, index_context) else { - continue; - }; - if partition == stored { - continue; - } - sqlx::query("UPDATE gsi_pending SET worker_partition = $1 WHERE id = $2") - .bind(partition) - .bind(id) - .execute(&mut *conn) - .await - .map_err(|e| db_error(&format!("repartition gsi_pending row {id}"), &e))?; - changed += 1; - } - Ok(changed) -} diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs index 6b3f3335a..626f7609d 100644 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs @@ -1,25 +1,26 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Migration 13, `escape_control_chars`, PostgreSQL: re-encode the rows an -//! earlier release wrote, whose strings are stored raw. +//! Migration 13, `escape_control_chars`, PostgreSQL: re-encode the item +//! documents an earlier release wrote, whose strings are stored raw. //! -//! This release stores every string through the order-preserving escape in -//! `extenddb_storage::util::escape_control` (U+0000 as U+0001 U+0001, U+0001 -//! as U+0001 U+0002), so that U+0000, which DynamoDB accepts anywhere a string -//! appears, can be held in `TEXT` and `jsonb` columns. A row an earlier -//! release wrote holds its strings raw, and a raw U+0001 followed by U+0001 or -//! U+0002 reads back differently under the decoder (a lone U+0001 reads back -//! unchanged). Earlier releases could not store U+0000, so for their rows the -//! escape of the stored text is the re-encode, and a row without U+0001 -//! encodes to itself and is left alone. +//! This release stores every string of an item document (names, map keys, +//! values) through an escape (U+0000 as U+0001 U+0001, U+0001 as U+0001 +//! U+0002), so that U+0000, which DynamoDB accepts anywhere a string appears, +//! can be held in `jsonb`. A document an earlier release wrote holds its +//! strings raw, and a raw U+0001 followed by U+0001 or U+0002 reads back +//! differently under the decoder (a lone U+0001 reads back unchanged). +//! Earlier releases could not store U+0000, so for their documents the escape +//! of the stored text is the re-encode, and a document without U+0001 is left +//! alone. The key columns (`pk`, `sk_s`, `base_pk` and the others) are not +//! rewritten: this release stores a key as earlier releases stored it, and +//! refuses a key value that holds U+0000 (`data::key_text`). //! -//! Two bodies, one per database. The catalog body rewrites `backup_items`, -//! which lives in the catalog database; the data body rewrites every data -//! table, index table and vector index table (the text key columns and -//! `item_data`), the item images of `gsi_pending` (`old_item`, `new_item`) -//! and the stream records of `stream_records` and `stream_pending`, and -//! recomputes `gsi_pending.worker_partition` for the rows it changes. +//! Two bodies, one per database. The catalog body rewrites +//! `backup_items.item_data`, which lives in the catalog database; the data +//! body rewrites `item_data` of every data table, index table and vector +//! index table, the item images of `gsi_pending` (`old_item`, `new_item`) and +//! the stream records of `stream_records` and `stream_pending`. //! `gsi_pending.index_context` is not rewritten: catalog migration 11, //! `attribute_name_escape`, applies the same escape to it once. Tables are //! listed from the catalog rows; a row whose table is `DELETING`, or whose @@ -37,18 +38,21 @@ //! status read does not look for sessions, so the preview runs beside a //! server as for every other migration. //! -//! The key text and document rewrites call the write path's escape and key -//! text functions (`escape_control`, `escape_json_strings`, -//! `key_text::reescape_legacy_composite`, `gsi_queue::worker_partition`), so -//! a migrated row is the row this release writes for the same item. +//! No index entry and no constraint covers the strings of a document, so a +//! rewrite fails only when the database does, for example on a lost +//! connection or a full disk. The catalog body commits before the data body +//! runs. A data body that fails leaves the catalog store at migration 13 and +//! the data store behind it; neither a server of this release nor one of an +//! earlier release starts against the deployment until `extenddb migrate +//! --yes` runs the data body again. //! -//! This module's checksum covers `mod.rs`, `keys.rs`, `order.rs` and +//! The rewrite escapes through this module's own copy of the escape +//! ([`escape`]). This module's checksum covers `mod.rs`, `escape.rs` and //! `guard.rs`, and is pinned once the migration is released. They are //! excluded from rustfmt and clippy so neither can require an edit. +mod escape; mod guard; -mod keys; -mod order; use async_trait::async_trait; use extenddb_storage::migrations::{CodeBody, Done, MigrationError}; @@ -59,20 +63,20 @@ use super::PostgresStores; pub(crate) use guard::other_sessions; #[cfg(test)] pub(crate) use guard::{IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows}; -pub(crate) use keys::{BACKUP_ITEMS_COMPOSITE_ROWS, has_composite_partition_key}; -pub(crate) use order::{BATCH, rewrite_longest_first, with_detail}; /// The text of every file of this module, whose SHA-256 the checksum test pins. pub(crate) const SOURCE: &str = concat!( include_str!("mod.rs"), - include_str!("keys.rs"), - include_str!("order.rs"), + include_str!("escape.rs"), include_str!("guard.rs"), ); /// Recorded as this migration's checksum. Changes only with a new migration. const FINGERPRINT: &str = "0013_escape_control_chars/postgres/1"; +/// Rows read per round trip. +const BATCH: usize = 500; + /// The catalog body: `backup_items`. pub(crate) struct EscapeBackupItems; @@ -130,11 +134,11 @@ impl CodeBody for EscapeDataRows { } } -/// A failed statement as a migration error: `what`, the database's message -/// with its DETAIL ([`with_detail`]), and the SQLSTATE, which the runner reads -/// to run the body again after a lock timeout. +/// A failed statement as a migration error: `what`, the database's message, +/// and the SQLSTATE, which the runner reads to run the body again after a +/// lock timeout. pub(crate) fn db_error(what: &str, e: &sqlx::Error) -> MigrationError { - let message = format!("{what}: {}", with_detail(e)); + let message = format!("{what}: {e}"); match e.as_database_error().and_then(|d| d.code()) { Some(code) => MigrationError::Database { message, @@ -144,31 +148,17 @@ pub(crate) fn db_error(what: &str, e: &sqlx::Error) -> MigrationError { } } -/// One physical table's rewrite: its text key columns, and the jsonb columns -/// whose rows are re-encoded one by one. +/// One physical table's rewrite: the jsonb columns that hold its item +/// documents. struct EscapeWork { /// Bare (unquoted) table name, e.g. `_ddb_` or `gsi_pending`. table: String, - text_columns: Vec, - jsonb_columns: Vec, - /// `gsi_pending` only: recompute `worker_partition` after the re-encode - /// ([`keys::recompute_worker_partitions`]). - recompute_worker_partition: bool, - /// The DynamoDB table (and index) the physical table holds, for errors - /// and notes. + columns: Vec, + /// The DynamoDB table (and index) the physical table holds, for notes. ddb_name: Option, } impl EscapeWork { - /// `
.`, with the DynamoDB name when known: how errors name a - /// column. - fn column(&self, col: &str) -> String { - match &self.ddb_name { - Some(ddb) => format!("{}.{col} ({ddb})", self.table), - None => format!("{}.{col}", self.table), - } - } - /// `
`, with the DynamoDB name when known: how notes name a table. fn label(&self) -> String { match &self.ddb_name { @@ -178,120 +168,50 @@ impl EscapeWork { } } -/// A text key column and the rows of it that hold a composite partition key. -struct TextKeyColumn { - name: String, - /// SQL boolean expression over the row, true where the column holds the - /// netstring join of several HASH attributes. Those rows are rebuilt one - /// by one ([`keys::rebuild_composite_rows`]); the others hold one - /// attribute's text and get the single-statement SQL replace. - composite_rows: String, -} - -impl TextKeyColumn { - fn new(name: String, composite: bool) -> Self { - let composite_rows = if composite { "TRUE" } else { "FALSE" }.to_owned(); - Self { - name, - composite_rows, - } - } -} - -/// The columns of `table` in the public schema of type `data_type` among -/// `names` (or, for `None`, the key columns `pk`, `base_pk`, `sk*_s` and -/// `base_sk*_s`), in column order. -async fn columns( +/// The jsonb columns of `table` in the public schema among `names`, in column +/// order; none when the table does not exist. +async fn jsonb_columns( conn: &mut PgConnection, table: &str, - data_type: &str, - names: Option<&[&str]>, + names: &[&str], ) -> Result, MigrationError> { - let names: Option> = names.map(|n| n.iter().map(|c| (*c).to_owned()).collect()); + let names: Vec = names.iter().map(|c| (*c).to_owned()).collect(); sqlx::query_scalar( "SELECT column_name::text FROM information_schema.columns \ - WHERE table_schema = 'public' AND table_name = $1 AND data_type = $2 \ - AND CASE WHEN $3::text[] IS NULL \ - THEN column_name IN ('pk', 'base_pk') OR column_name::text ~ '^(base_)?sk[0-9]*_s$' \ - ELSE column_name::text = ANY($3) END \ + WHERE table_schema = 'public' AND table_name = $1 AND data_type = 'jsonb' \ + AND column_name::text = ANY($2) \ ORDER BY ordinal_position", ) .bind(table) - .bind(data_type) .bind(names) .fetch_all(&mut *conn) .await - .map_err(|e| db_error(&format!("list the {data_type} columns of {table}"), &e)) -} - -/// The rewrite of a `_ddb_*` table, whose columns are read from -/// `information_schema.columns` so that exactly the sort key columns this -/// table has (`sk_s`, `sk_s`, `base_sk_s`, ...) are covered. `None` -/// when the physical table does not exist. `composite` names the columns -/// whose key schema has more than one HASH attribute, so they hold a -/// netstring join on every row. -async fn dynamic_table_work( - conn: &mut PgConnection, - table: String, - composite: &[&str], -) -> Result, MigrationError> { - let text_columns = columns(conn, &table, "text", None).await?; - let jsonb_columns = columns(conn, &table, "jsonb", Some(&["item_data"])).await?; - if text_columns.is_empty() && jsonb_columns.is_empty() { - return Ok(None); - } - let text_columns = text_columns - .into_iter() - .map(|name| { - let composite = composite.contains(&name.as_str()); - TextKeyColumn::new(name, composite) - }) - .collect(); - Ok(Some(EscapeWork { - table, - text_columns, - jsonb_columns, - recompute_worker_partition: false, - ddb_name: None, - })) + .map_err(|e| db_error(&format!("list the jsonb columns of {table}"), &e)) } -/// The rewrite of a fixed-name table, with the candidate columns filtered -/// through `information_schema.columns`. `None` when the table is absent. -async fn fixed_table_work( +/// The rewrite of `table`'s columns among `names`, or `None` when the table +/// has none of them. +async fn table_work( conn: &mut PgConnection, table: &str, - text: &[&str], - jsonb: &[&str], + names: &[&str], + ddb_name: Option, ) -> Result, MigrationError> { - let text_columns = if text.is_empty() { - Vec::new() - } else { - columns(conn, table, "text", Some(text)).await? - }; - let jsonb_columns = columns(conn, table, "jsonb", Some(jsonb)).await?; - if text_columns.is_empty() && jsonb_columns.is_empty() { - return Ok(None); - } - Ok(Some(EscapeWork { + let columns = jsonb_columns(conn, table, names).await?; + Ok((!columns.is_empty()).then(|| EscapeWork { table: table.to_owned(), - text_columns: text_columns - .into_iter() - .map(|name| TextKeyColumn::new(name, false)) - .collect(), - jsonb_columns, - recompute_worker_partition: false, - ddb_name: None, + columns, + ddb_name, })) } /// The re-encoded form of a stored jsonb value, or `None` when re-encoding -/// does not change it. `escape_json_strings` only changes strings and object -/// keys containing U+0000 or U+0001, so a plain document and a document whose +/// does not change it. The escape only changes strings and object keys +/// containing U+0000 or U+0001, so a plain document and a document whose /// strings hold the literal six-character text backslash-u-0001 both come /// back equal and are skipped. pub(crate) fn reencoded_json(value: &serde_json::Value) -> Option { - let escaped = extenddb_storage::util::escape_json_strings(value.clone()); + let escaped = escape::escape_document(value.clone()); (escaped != *value).then_some(escaped) } @@ -350,74 +270,6 @@ async fn escape_jsonb_rows( Ok(changed) } -/// Rewrite one table; returns the number of row updates. -async fn escape_rows_in_table( - conn: &mut PgConnection, - work: &EscapeWork, -) -> Result { - let quoted = format!("\"{}\"", work.table); - let mut rewritten: u64 = 0; - - // Key text columns holding one attribute's text: TEXT has no escaping - // layer, so a single SQL statement per column is exact. NULL columns never - // match (position() is NULL). The statement can fail on the primary key - // when two legacy keys differ only by a U+0002 after a U+0001, depending - // on the order it meets them (`order`); it runs under a savepoint, and on - // a unique violation the column is rewritten again row by row, longest - // legacy text first. Rows holding a composite key are rebuilt part by - // part instead; the other columns of the row keep the replace(). - for col in &work.text_columns { - let TextKeyColumn { - name, - composite_rows, - } = col; - let what = work.column(name); - let single_rows = format!("NOT ({composite_rows})"); - let sql = format!( - "UPDATE {quoted} SET \"{name}\" = replace(\"{name}\", chr(1), chr(1) || chr(2)) \ - WHERE position(chr(1) IN \"{name}\") > 0 AND {single_rows}" - ); - sqlx::query("SAVEPOINT escape_column") - .execute(&mut *conn) - .await - .map_err(|e| db_error(&format!("savepoint before {what}"), &e))?; - match sqlx::query(&sql).execute(&mut *conn).await { - Ok(done) => { - sqlx::query("RELEASE SAVEPOINT escape_column") - .execute(&mut *conn) - .await - .map_err(|e| db_error(&format!("release the savepoint of {what}"), &e))?; - rewritten += done.rows_affected(); - } - Err(e) if crate::pg_util::is_unique_violation(&e) => { - sqlx::query("ROLLBACK TO SAVEPOINT escape_column") - .execute(&mut *conn) - .await - .map_err(|e| db_error(&format!("roll back {what}"), &e))?; - // Legacy text holds no U+0000, so the escape is the replace() - // above. - rewritten += rewrite_longest_first(conn, "ed, name, &single_rows, &what, |legacy| { - Ok(extenddb_storage::util::escape_control(legacy).into_owned()) - }) - .await?; - } - Err(e) => return Err(db_error(&format!("re-encode {what}"), &e)), - } - if composite_rows != "FALSE" { - rewritten += - keys::rebuild_composite_rows(conn, "ed, name, composite_rows, &what).await?; - } - } - - for col in &work.jsonb_columns { - rewritten += escape_jsonb_rows(conn, "ed, col).await?; - } - if work.recompute_worker_partition { - rewritten += keys::recompute_worker_partitions(conn).await?; - } - Ok(rewritten) -} - /// Rewrite every table of `work` in order; one note per table with a change. async fn escape_all( conn: &mut PgConnection, @@ -425,7 +277,11 @@ async fn escape_all( notes: &mut Vec, ) -> Result<(), MigrationError> { for w in work { - let rewritten = escape_rows_in_table(conn, w).await?; + let quoted = format!("\"{}\"", w.table); + let mut rewritten: u64 = 0; + for col in &w.columns { + rewritten += escape_jsonb_rows(conn, "ed, col).await?; + } if rewritten > 0 { notes.push(format!("{}: {rewritten} row update(s)", w.label())); } @@ -434,31 +290,19 @@ async fn escape_all( } /// The catalog body on `conn`, the catalog database in the runner's -/// transaction. `backup_items.pk` is the data table's `pk` as the backup -/// copied it, so a backup of a table with several HASH attributes holds a -/// netstring join there. +/// transaction. pub(crate) async fn escape_catalog(conn: &mut PgConnection) -> Result, MigrationError> { let mut notes = Vec::new(); - let mut work = Vec::new(); - if let Some(mut w) = fixed_table_work(conn, "backup_items", &["pk", "sk"], &["item_data"]).await? { - for col in &mut w.text_columns { - if col.name == "pk" { - col.composite_rows = BACKUP_ITEMS_COMPOSITE_ROWS.to_owned(); - } - } - work.push(w); - } + let work: Vec = table_work(conn, "backup_items", &["item_data"], None) + .await? + .into_iter() + .collect(); escape_all(conn, &work, &mut notes).await?; Ok(notes) } /// The data body on `conn`, the data database in the runner's transaction, /// with the tables listed from `catalog`. -/// -/// A partition key column whose key schema has more than one HASH attribute -/// holds a netstring join (`key_text::composite_pk_to_text`): `pk` of a table -/// or index with such a key schema, and `base_pk` of the index and vector -/// tables of a table with one. pub(crate) async fn escape_data( catalog: &PgPool, conn: &mut PgConnection, @@ -466,9 +310,8 @@ pub(crate) async fn escape_data( let mut notes = Vec::new(); let mut work: Vec = Vec::new(); - type TableRow = (String, String, String, String, serde_json::Value); - let tables: Vec = sqlx::query_as( - "SELECT table_id, table_name, account_id, table_status, key_schema FROM tables \ + let tables: Vec<(String, String, String, String)> = sqlx::query_as( + "SELECT table_id, table_name, account_id, table_status FROM tables \ ORDER BY table_id COLLATE \"C\"", ) .fetch_all(catalog) @@ -476,18 +319,13 @@ pub(crate) async fn escape_data( .map_err(|e| db_error("list tables", &e))?; let deleting: std::collections::HashSet<&str> = tables .iter() - .filter(|(_, _, _, status, _)| status == "DELETING") - .map(|(id, _, _, _, _)| id.as_str()) + .filter(|(_, _, _, status)| status == "DELETING") + .map(|(id, _, _, _)| id.as_str()) .collect(); - let composite_tables: std::collections::HashSet<&str> = tables - .iter() - .filter(|(_, _, _, _, ks)| has_composite_partition_key(ks)) - .map(|(id, _, _, _, _)| id.as_str()) - .collect(); - // How errors and notes name the DynamoDB table of a physical table. + // How notes name the DynamoDB table of a physical table. let ddb_tables: std::collections::HashMap<&str, String> = tables .iter() - .map(|(id, name, account, _, _)| (id.as_str(), format!("table {name:?} of account {account}"))) + .map(|(id, name, account, _)| (id.as_str(), format!("table {name:?} of account {account}"))) .collect(); let ddb_table = |table_id: &str| { ddb_tables @@ -495,51 +333,26 @@ pub(crate) async fn escape_data( .cloned() .unwrap_or_else(|| format!("table id {table_id}")) }; - let skip = |label: String, physical: &str, notes: &mut Vec, table_id: &str| { - if deleting.contains(table_id) { - notes.push(format!("{label}: skipped, the table is being deleted")); - } else { - notes.push(format!("{label}: skipped, its physical table {physical} does not exist")); - } - }; - for (id, _, _, _, ks) in &tables { - let label = ddb_table(id); - let physical = format!("_ddb_{id}"); - let cols: &[&str] = if has_composite_partition_key(ks) { &["pk"] } else { &[] }; - match dynamic_table_work(conn, physical.clone(), cols).await? { - Some(mut w) if !deleting.contains(id.as_str()) => { - w.ddb_name = Some(label); - work.push(w); - } - _ => skip(label, &physical, &mut notes, id), - } - } - let indexes: Vec<(String, String, String, serde_json::Value)> = sqlx::query_as( - "SELECT index_id, table_id, index_name, key_schema FROM indexes \ - ORDER BY index_id COLLATE \"C\"", + // Every physical table the catalog lists: (physical name, the id of its + // DynamoDB table, how notes name it). + let mut physical: Vec<(String, String, String)> = tables + .iter() + .map(|(id, _, _, _)| (format!("_ddb_{id}"), id.clone(), ddb_table(id))) + .collect(); + let indexes: Vec<(String, String, String)> = sqlx::query_as( + "SELECT index_id, table_id, index_name FROM indexes ORDER BY index_id COLLATE \"C\"", ) .fetch_all(catalog) .await .map_err(|e| db_error("list indexes", &e))?; - for (id, table_id, name, ks) in &indexes { - let label = format!("index {name:?} of {}", ddb_table(table_id)); - let physical = format!("_ddb_{id}"); - let mut cols: Vec<&str> = Vec::new(); - if has_composite_partition_key(ks) { - cols.push("pk"); - } - if composite_tables.contains(table_id.as_str()) { - cols.push("base_pk"); - } - match dynamic_table_work(conn, physical.clone(), &cols).await? { - Some(mut w) if !deleting.contains(table_id.as_str()) => { - w.ddb_name = Some(label); - work.push(w); - } - _ => skip(label, &physical, &mut notes, table_id), - } - } + physical.extend(indexes.iter().map(|(id, table_id, name)| { + ( + format!("_ddb_{id}"), + table_id.clone(), + format!("index {name:?} of {}", ddb_table(table_id)), + ) + })); let vectors: Vec<(String, String, String)> = sqlx::query_as( "SELECT index_id, table_id, index_name FROM vector_indexes \ ORDER BY index_id COLLATE \"C\"", @@ -547,40 +360,38 @@ pub(crate) async fn escape_data( .fetch_all(catalog) .await .map_err(|e| db_error("list vector indexes", &e))?; - for (id, table_id, name) in &vectors { - let label = format!("vector index {name:?} of {}", ddb_table(table_id)); - let physical = format!("_ddb_vec_{id}"); - let cols: &[&str] = if composite_tables.contains(table_id.as_str()) { - &["base_pk"] - } else { - &[] - }; - match dynamic_table_work(conn, physical.clone(), cols).await? { - Some(mut w) if !deleting.contains(table_id.as_str()) => { - w.ddb_name = Some(label); - work.push(w); - } - _ => skip(label, &physical, &mut notes, table_id), + physical.extend(vectors.iter().map(|(id, table_id, name)| { + ( + format!("_ddb_vec_{id}"), + table_id.clone(), + format!("vector index {name:?} of {}", ddb_table(table_id)), + ) + })); + + for (table, table_id, label) in physical { + if deleting.contains(table_id.as_str()) { + notes.push(format!("{label}: skipped, the table is being deleted")); + continue; + } + match table_work(conn, &table, &["item_data"], Some(label.clone())).await? { + Some(w) => work.push(w), + None => notes.push(format!("{label}: skipped, its physical table {table} does not exist")), } } // Fixed tables holding item documents. `gsi_pending.index_context` is a // catalog document, which migration 11 escaped once with the same // mapping; escaping it again would read a U+0001 back as U+0001 U+0002. - if let Some(mut w) = - fixed_table_work(conn, "gsi_pending", &[], &["old_item", "new_item"]).await? - { - w.recompute_worker_partition = true; - work.push(w); - } // A stream record waits in `stream_pending` until the numbering moves it // to `stream_records` (migration 7), so both hold item documents. // `record_bytes`, the numbering's estimate of a batch's size, keeps the // length the write sent. - for table in ["stream_records", "stream_pending"] { - if let Some(w) = fixed_table_work(conn, table, &[], &["record_data"]).await? { - work.push(w); - } + for (table, columns) in [ + ("gsi_pending", &["old_item", "new_item"][..]), + ("stream_records", &["record_data"][..]), + ("stream_pending", &["record_data"][..]), + ] { + work.extend(table_work(conn, table, columns, None).await?); } escape_all(conn, &work, &mut notes).await?; diff --git a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/order.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/order.rs deleted file mode 100644 index 048e7bad2..000000000 --- a/crates/storage-postgres/src/migrations/m0013_escape_control_chars/order.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Row-by-row rewrites of one key column for migration 13, in an order that -//! keeps the table's primary key valid after every row. -//! -//! `PostgreSQL` checks a primary key as each row changes, not at the end of the -//! statement. Two legacy keys that differ only by a U+0002 after a U+0001, such -//! as `a\x01` and `a\x01\x02` with the same other key columns, escape to two -//! different texts, `a\x01\x02` and `a\x01\x02\x02`, but the first one's new -//! text is the second one's legacy text. If the shorter one is rewritten first, -//! the table holds `a\x01\x02` twice until the longer one is rewritten, and the -//! update fails with SQLSTATE 23505. A one-statement `UPDATE` meets the two rows -//! in heap order, so whether it fails depends on where they are stored. -//! -//! [`rewrite_longest_first`] rewrites the rows in descending byte length of -//! their legacy text, which never produces such a duplicate: -//! -//! - Every rewrite makes the text longer. Every row it rewrites holds a U+0001, -//! and the escape adds one byte for each; a rebuilt composite key also gives -//! each part its new length, which never takes fewer digits than the old one. -//! - Suppose rewriting row `r` gives the text that row `s` holds, and the two -//! rows agree on the other key columns. If `s` has not been rewritten yet, it -//! holds its legacy text, and that text is the new text of `r`, so it is -//! longer than the legacy text of `r` and `s` was rewritten earlier. If `s` -//! has been rewritten, the two rows have the same new text, and since the -//! escape is injective their legacy texts were equal. -//! - Each other key column holds the legacy texts of every row, or, when an -//! earlier pass of the same transaction rewrote it, their escapes. Either -//! way two rows agree on it now exactly when they agreed before the -//! migration. Two rows that agreed on every key column before the migration -//! would have broken the primary key, so no rewrite meets a duplicate. - -use extenddb_storage::migrations::MigrationError; -use sqlx::PgConnection; - -use super::db_error; - -/// Rows read from the cursor per round trip, and the batch `escape_jsonb_rows` -/// reads. -pub(crate) const BATCH: usize = 500; - -/// The cursor [`rewrite_longest_first`] declares and closes before returning. -const CURSOR: &str = "escape_0013_longest_first"; - -/// Rewrite `col` of the rows that hold U+0001 and that `rows` (a boolean SQL -/// expression over the row) selects, one row at a time, longest legacy text -/// first; `rewrite` gives a row's new text from its legacy text. Runs in the -/// caller's transaction and returns the number of rows changed. `what` names -/// the column in errors, with the DynamoDB table when the caller knows it. -/// -/// One cursor is declared over the matching rows in that order and read -/// [`BATCH`] rows at a time, so this process holds one batch, and `PostgreSQL` -/// sorts the matching rows in `work_mem`, spilling to temporary files beyond -/// it. The cursor's rows are fixed when it is declared and each is returned -/// once, so no row is rewritten twice. Each row is locked as the cursor -/// returns it, as the single-statement path locks the rows it updates. -pub(crate) async fn rewrite_longest_first( - conn: &mut PgConnection, - quoted_table: &str, - col: &str, - rows: &str, - what: &str, - rewrite: impl Fn(&str) -> Result, -) -> Result { - let failed = |step: &str, e: &sqlx::Error| db_error(&format!("{step} {what}"), e); - sqlx::query(&format!( - "DECLARE {CURSOR} NO SCROLL CURSOR FOR \ - SELECT ctid::text, \"{col}\" FROM {quoted_table} \ - WHERE position(chr(1) IN \"{col}\") > 0 AND ({rows}) \ - ORDER BY octet_length(\"{col}\") DESC FOR UPDATE" - )) - .execute(&mut *conn) - .await - .map_err(|e| failed("find the rows to rewrite in", &e))?; - let fetch = format!("FETCH {BATCH} FROM {CURSOR}"); - let update = format!("UPDATE {quoted_table} SET \"{col}\" = $1 WHERE ctid = $2::tid"); - let mut changed: u64 = 0; - loop { - let batch: Vec<(String, String)> = sqlx::query_as(&fetch) - .fetch_all(&mut *conn) - .await - .map_err(|e| failed("read the rows to rewrite in", &e))?; - for (ctid, legacy) in &batch { - let done = sqlx::query(&update) - .bind(rewrite(legacy)?) - .bind(ctid) - .execute(&mut *conn) - .await - .map_err(|e| failed("re-encode", &e))?; - changed += done.rows_affected(); - } - if batch.len() < BATCH { - break; - } - } - sqlx::query(&format!("CLOSE {CURSOR}")) - .execute(&mut *conn) - .await - .map_err(|e| failed("close the cursor over", &e))?; - Ok(changed) -} - -/// A database error as text, with `PostgreSQL`'s DETAIL when the error has one; -/// for a unique violation the DETAIL names the key already present. sqlx's -/// `Display` writes the message alone. The DETAIL is quoted with its control -/// characters escaped, since the keys this migration rewrites hold them. -pub(crate) fn with_detail(e: &sqlx::Error) -> String { - let detail = match e { - sqlx::Error::Database(db) => db - .try_downcast_ref::() - .and_then(sqlx::postgres::PgDatabaseError::detail), - _ => None, - }; - match detail { - Some(detail) => format!("{e} (DETAIL: {detail:?})"), - None => e.to_string(), - } -} diff --git a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs index 9fbab36f6..50cab992b 100644 --- a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs @@ -6,11 +6,13 @@ //! of `m0013_tests`. That the runner stops on a `detect` item before its first //! write is checked over two databases in `tests/migrations_golden.rs`. +use extenddb_storage::migrations::CodeBody; use sqlx::PgPool; use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; +use super::PostgresStores; use super::m0013_escape_control_chars::{ - IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows, other_sessions, + EscapeBackupItems, IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows, other_sessions, }; use super::m0013_tests::{base_conn, scratch, seed, skip, test_application}; @@ -208,3 +210,60 @@ async fn only_a_store_with_rows_is_checked() { assert!(data_has_rows(&s.db, &s.db).await.unwrap()); s.cleanup().await; } + +/// The catalog body's `detect` stops a run while another session holds the +/// catalog database and `backup_items` holds a row, with one item that names +/// the session; with no backup item, or once the session is gone, it finds +/// nothing. +#[tokio::test] +async fn the_catalog_body_stops_a_run_while_another_session_holds_the_catalog() { + if base_conn().is_none() { + skip("the_catalog_body_stops_a_run_while_another_session_holds_the_catalog"); + return; + } + let s = scratch().await; + let base = base_conn().unwrap(); + let stores = PostgresStores::for_detect(s.db.clone(), s.db.clone()); + let client = unnamed(&base, &s.db_name).await; + let client_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&client) + .await + .unwrap(); + assert_eq!( + EscapeBackupItems.detect(&stores).await.unwrap(), + Vec::::new(), + "backup_items is empty" + ); + + seed(&s.db).await; + let (user, addr): (String, Option) = sqlx::query_as( + "SELECT usename::text, client_addr::text FROM pg_stat_activity WHERE pid = $1", + ) + .bind(client_pid) + .fetch_one(&s.db) + .await + .unwrap(); + let want = format!( + "1 other session(s) hold the catalog database {}: {user} from {} (no application \ + name). Migration 13 rewrites stored strings and runs with every ExtendDB server \ + stopped and every other session on the database closed, because a server still \ + writing would leave rows in the earlier encoding. Stop them and run `extenddb \ + migrate --yes` again. If the only other sessions are idle connections a connection \ + pooler holds, set EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1 to skip this check", + s.db_name, + addr.as_deref().unwrap_or("no client address shown"), + ); + assert_eq!(EscapeBackupItems.detect(&stores).await.unwrap(), vec![want]); + + client.close().await; + let mut items = EscapeBackupItems.detect(&stores).await.unwrap(); + for _ in 0..50 { + if items.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + items = EscapeBackupItems.detect(&stores).await.unwrap(); + } + assert_eq!(items, Vec::::new(), "the session closed"); + s.cleanup().await; +} diff --git a/crates/storage-postgres/src/migrations/m0013_keys_tests.rs b/crates/storage-postgres/src/migrations/m0013_keys_tests.rs deleted file mode 100644 index 05326d4bf..000000000 --- a/crates/storage-postgres/src/migrations/m0013_keys_tests.rs +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Live checks of migration 13's composite key rebuild and `worker_partition` -//! recompute, with the scratch database and the skip convention of -//! `m0013_tests`: without `EXTENDDB_TEST_PG_CONNECTION_STRING` every live test -//! reports a skip and passes. Each seeds rows the way a release without the -//! escape wrote them. - -//! Live checks against a scratch database, with the helpers and the -//! skip convention of `migrations::live_reencode`: without -//! `EXTENDDB_TEST_PG_CONNECTION_STRING` every test reports a skip and -//! passes. Each seeds rows the way a build without the escape wrote them. - -use extenddb_core::types::{ - AttributeDefinition, AttributeValue, Item, KeySchemaElement, KeyType, Projection, - ProjectionType, ScalarAttributeType, -}; -use serde_json::json; -use sqlx::PgPool; - -use super::m0013_tests::{base_conn, run_pool, scratch, skip}; -use crate::data::key_text::composite_pk_to_text; -use crate::gsi_queue::{ - GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending, partition_for, - worker_partition, -}; - -fn element(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } -} - -fn text(v: &str) -> AttributeValue { - AttributeValue::S(v.to_owned()) -} - -async fn exec(db: &PgPool, sql: &str, binds: &[serde_json::Value]) { - let mut q = sqlx::query(sql); - for b in binds { - q = q.bind(b.clone()); - } - q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); -} - -async fn texts(db: &PgPool, sql: &str) -> Vec { - sqlx::query_scalar(sql) - .fetch_all(db) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) -} - -/// A table with two HASH attributes (`t2`), a two-HASH GSI on a one-HASH -/// table (`i2` on `t1`), a one-HASH GSI on `t2` (`i3`), and a backup of -/// each table, each holding a legacy row with a raw U+0001 in a HASH part. -async fn seed_composite(db: &PgPool) { - exec( - db, - "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'esc')", - &[], - ) - .await; - let one = json!([{"AttributeName": "pk", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"}]); - let two = json!([{"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"}]); - for (id, ks) in [("t1", &one), ("t2", &two)] { - exec( - db, - &format!( - "INSERT INTO tables (account_id, table_name, key_schema, \ - attribute_definitions, table_status, table_arn, table_id) \ - VALUES ('111122223333', '{id}', $1, '[]', 'ACTIVE', \ - 'arn:aws:dynamodb:us-east-1:111122223333:table/{id}', '{id}')" - ), - std::slice::from_ref(ks), - ) - .await; - } - for (table, index, ks) in [ - ( - "t1", - "i2", - json!([{"AttributeName": "g1", "KeyType": "HASH"}, - {"AttributeName": "g2", "KeyType": "HASH"}]), - ), - ( - "t2", - "i3", - json!([{"AttributeName": "g", "KeyType": "HASH"}]), - ), - ] { - exec( - db, - &format!( - "INSERT INTO indexes (table_id, index_id, index_name, index_type, \ - key_schema, projection) VALUES ('{table}', '{index}', '{index}', 'GSI', \ - $1, '{{\"ProjectionType\": \"ALL\"}}')" - ), - &[ks], - ) - .await; - } - sqlx::raw_sql( - r#"CREATE TABLE "_ddb_t2" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, sk_s)); - CREATE TABLE "_ddb_i2" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); - CREATE TABLE "_ddb_i3" ( - pk TEXT COLLATE "C" NOT NULL, sk_s TEXT COLLATE "C", - base_pk TEXT COLLATE "C" NOT NULL, base_sk_s TEXT COLLATE "C", - item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s)); - INSERT INTO "_ddb_t2" VALUES - (E'2:a\x01,1:b,', 's', - '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}, "sk": {"S": "s"}}'), - ('1:x,1:y,', 's', '{"h1": {"S": "x"}, "h2": {"S": "y"}, "sk": {"S": "s"}}'); - INSERT INTO "_ddb_i2" VALUES - (E'2:g\x01,1:h,', NULL, E'p\x01', E's\x01', - '{"g1": {"S": "g\u0001"}, "g2": {"S": "h"}, "pk": {"S": "p\u0001"}}'); - INSERT INTO "_ddb_i3" VALUES - (E'g\x01', NULL, E'2:a\x01,1:b,', 's', - '{"g": {"S": "g\u0001"}, "h1": {"S": "a\u0001"}, "h2": {"S": "b"}}'); - INSERT INTO backups (backup_arn, backup_name, table_id, table_name, account_id, - key_schema, attribute_definitions) VALUES - ('b1', 'b1', 't1', 't1', '111122223333', - '[{"AttributeName": "pk", "KeyType": "HASH"}]', '[]'), - ('b2', 'b2', 't2', 't2', '111122223333', - '[{"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}]', '[]'); - INSERT INTO backup_items (backup_arn, pk, sk, item_data) VALUES - ('b1', E'p\x01', NULL, '{"pk": {"S": "p\u0001"}}'), - ('b2', E'2:a\x01,1:b,', NULL, '{"h1": {"S": "a\u0001"}, "h2": {"S": "b"}}');"#, - ) - .execute(db) - .await - .expect("seed the legacy rows"); -} - -#[tokio::test] -async fn rebuilds_composite_partition_keys_part_by_part() { - if base_conn().is_none() { - skip("rebuilds_composite_partition_keys_part_by_part"); - return; - } - let s = scratch().await; - seed_composite(&s.db).await; - run_pool(&s.db).await.expect("run the data code migrations"); - - // What this build writes and looks up for the legacy key - // h1 = "a\x01", h2 = "b": each part escaped, then joined. - let mut item = Item::new(); - item.insert("h1".to_owned(), text("a\u{1}")); - item.insert("h2".to_owned(), text("b")); - let ks = [element("h1", KeyType::Hash), element("h2", KeyType::Hash)]; - let expected = composite_pk_to_text(&item, &ks).expect("composite key text"); - assert_eq!(expected, "3:a\u{1}\u{2},1:b,"); - - // The table with two HASH attributes: the legacy row is rebuilt, the - // plain row keeps its text. - assert_eq!( - texts(&s.db, "SELECT pk FROM \"_ddb_t2\" ORDER BY pk").await, - vec!["1:x,1:y,".to_owned(), expected.clone()] - ); - // A two-HASH GSI: pk rebuilt, the one-HASH base key replaced. - let row: (String, String, String) = - sqlx::query_as("SELECT pk, base_pk, base_sk_s FROM \"_ddb_i2\"") - .fetch_one(&s.db) - .await - .expect("read _ddb_i2"); - assert_eq!( - row, - ( - "3:g\u{1}\u{2},1:h,".to_owned(), - "p\u{1}\u{2}".to_owned(), - "s\u{1}\u{2}".to_owned() - ) - ); - // A one-HASH GSI on the two-HASH table: pk replaced, base_pk rebuilt. - let row: (String, String) = sqlx::query_as("SELECT pk, base_pk FROM \"_ddb_i3\"") - .fetch_one(&s.db) - .await - .expect("read _ddb_i3"); - assert_eq!(row, ("g\u{1}\u{2}".to_owned(), expected.clone())); - // backup_items: the backup of the two-HASH table is rebuilt, the - // other replaced. - assert_eq!( - texts(&s.db, "SELECT pk FROM backup_items ORDER BY backup_arn").await, - vec!["p\u{1}\u{2}".to_owned(), expected] - ); - s.cleanup().await; -} - -/// The base key attribute of [`context`]. Its name holds U+0001, so a decode -/// that read the stored context raw would not find the key on the item. -const PK: &str = "pk\u{1}"; - -fn context() -> PendingApplyContext { - PendingApplyContext::Gsi(GsiApplyContext { - base_key_schema: vec![element(PK, KeyType::Hash)], - attribute_definitions: vec![AttributeDefinition { - attribute_name: PK.to_owned(), - attribute_type: ScalarAttributeType::S, - }], - index: GsiIndexDef { - index_id: "i1".to_owned(), - key_schema: vec![element("g", KeyType::Hash)], - projection: Projection { - projection_type: ProjectionType::All, - non_key_attributes: None, - }, - }, - }) -} - -/// The partition a build without the escape gave a row for `item`: the -/// hash of the raw key text. -fn legacy_partition(item: &Item) -> i32 { - let raw = extenddb_storage::util::composite_pk_to_text(item, &[element(PK, KeyType::Hash)]) - .expect("raw key text"); - partition_for(&raw) -} - -#[tokio::test] -async fn recomputes_the_worker_partition_of_rows_queued_before_the_upgrade() { - if base_conn().is_none() { - skip("recomputes_the_worker_partition_of_rows_queued_before_the_upgrade"); - return; - } - let ctx = context(); - // A key holding U+0001 whose raw and escaped texts hash to different - // workers, so the test sees the move. - let item = [ - "a\u{1}b", - "b\u{1}", - "\u{1}c", - "key\u{1}1", - "key\u{1}2", - "key\u{1}3", - ] - .into_iter() - .map(|k| { - let mut item = Item::new(); - item.insert(PK.to_owned(), text(k)); - item.insert("g".to_owned(), text("v")); - item - }) - .find(|item| { - legacy_partition(item) != worker_partition(None, Some(item), &ctx).expect("partition") - }) - .expect("a key whose partition moves"); - let current = worker_partition(None, Some(&item), &ctx).expect("partition"); - let legacy = legacy_partition(&item); - - // A key value without U+0001 and a non-key string with it: same text - // both ways. - let mut plain = Item::new(); - plain.insert(PK.to_owned(), text("plain")); - plain.insert("note".to_owned(), text("n\u{1}")); - let plain_partition = legacy_partition(&plain); - - let s = scratch().await; - // The images as a release without the escape stored them, and the - // context through the catalog escape, as a release with migration 11 - // stores it. - let stored_ctx = crate::catalog_json::to_catalog_json(&ctx).expect("context json"); - let raw = |i: &Item| serde_json::to_value(i).expect("item json"); - for (old_item, new_item, partition) in [ - (None, Some(raw(&item)), legacy), - (Some(raw(&item)), None, legacy), - (None, Some(raw(&plain)), plain_partition), - ] { - sqlx::query( - "INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, \ - index_context) VALUES ('t1', $1, $2, $3, $4)", - ) - .bind(partition) - .bind(old_item) - .bind(new_item) - .bind(&stored_ctx) - .execute(&s.db) - .await - .expect("seed a queued row"); - } - - run_pool(&s.db).await.expect("run the data code migrations"); - - let partitions: Vec = - sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id") - .fetch_all(&s.db) - .await - .expect("read gsi_pending"); - assert_eq!(partitions, vec![current, current, plain_partition]); - - // The next write of the item is queued on the same worker. - let mut tx = s.db.begin().await.expect("begin"); - enqueue_gsi_pending(&mut tx, "t1", None, Some(&item), 1, &ctx) - .await - .expect("enqueue the next write"); - tx.commit().await.expect("commit"); - let next: i32 = - sqlx::query_scalar("SELECT worker_partition FROM gsi_pending ORDER BY id DESC LIMIT 1") - .fetch_one(&s.db) - .await - .expect("read the new row"); - assert_eq!(next, current); - s.cleanup().await; -} - -mod unit { - use super::super::m0013_escape_control_chars::has_composite_partition_key; - use serde_json::json; - - #[test] - fn only_a_key_schema_with_two_or_more_hash_attributes_is_composite() { - let one = json!([ - {"AttributeName": "pk", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"} - ]); - let two = json!([ - {"AttributeName": "h1", "KeyType": "HASH"}, - {"AttributeName": "h2", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"} - ]); - let ranges = json!([ - {"AttributeName": "h", "KeyType": "HASH"}, - {"AttributeName": "r1", "KeyType": "RANGE"}, - {"AttributeName": "r2", "KeyType": "RANGE"} - ]); - assert!(!has_composite_partition_key(&one)); - assert!(has_composite_partition_key(&two)); - assert!(!has_composite_partition_key(&ranges)); - assert!(!has_composite_partition_key(&json!({}))); - } -} diff --git a/crates/storage-postgres/src/migrations/m0013_order_tests.rs b/crates/storage-postgres/src/migrations/m0013_order_tests.rs deleted file mode 100644 index 0d45fe3ec..000000000 --- a/crates/storage-postgres/src/migrations/m0013_order_tests.rs +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright 2026 ExtendDB contributors -// SPDX-License-Identifier: Apache-2.0 - -//! Live checks of migration 13's ordered key rewrite, with the scratch database -//! and the skip convention of `m0013_tests`. The tables are created by the DDL -//! `CreateTable` runs, so their primary keys are the production ones. Each -//! test stores legacy keys that differ only by a U+0002 after a U+0001, the -//! shorter one first in the heap, the order a one-statement rewrite fails on. -//! `item_data` is `{}`: the tests check the key columns. - -//! Live checks with the scratch database and the skip convention of -//! `migrations::live_reencode`. The tables are created by the DDL -//! `CreateTable` runs, so their primary keys are the production ones. Each -//! test stores legacy keys that differ only by a U+0002 after a U+0001, -//! the shorter one first in the heap, the order a one-statement rewrite -//! fails on. `item_data` is `{}`: the tests check the key columns. - -use extenddb_core::types::{AttributeDefinition, KeySchemaElement, KeyType, ScalarAttributeType}; -use extenddb_storage::util::escape_control; -use sqlx::PgPool; - -use super::m0013_escape_control_chars::{BATCH, rewrite_longest_first}; -use super::m0013_tests::{base_conn, run_pool, scratch, skip}; -use crate::PostgresEngine; -use crate::data::key_text::reescape_legacy_composite; - -fn key(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } -} - -fn string_attributes(key_schema: &[KeySchemaElement]) -> Vec { - key_schema - .iter() - .map(|k| AttributeDefinition { - attribute_name: k.attribute_name.clone(), - attribute_type: ScalarAttributeType::S, - }) - .collect() -} - -fn json(value: &T) -> serde_json::Value { - serde_json::to_value(value).expect("json") -} - -/// The account, the `tables` row and the data table of table `id`. -async fn table(db: &PgPool, id: &str, key_schema: &[KeySchemaElement]) { - let attributes = string_attributes(key_schema); - sqlx::query( - "INSERT INTO accounts (account_id, account_name) VALUES ('111122223333', 'order') \ - ON CONFLICT DO NOTHING", - ) - .execute(db) - .await - .expect("seed the account"); - sqlx::query( - "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ - table_status, table_arn, table_id) VALUES ('111122223333', $1, $2, $3, 'ACTIVE', \ - 'arn:aws:dynamodb:us-east-1:111122223333:table/' || $1, $1)", - ) - .bind(id) - .bind(json(&key_schema)) - .bind(json(&attributes)) - .execute(db) - .await - .expect("seed the tables row"); - let mut tx = db.begin().await.expect("begin"); - PostgresEngine::create_data_table(&mut tx, id, key_schema, &attributes) - .await - .expect("create the data table"); - tx.commit().await.expect("commit"); -} - -/// The `indexes` row and the data table of GSI `id` on table `table_id`. -async fn index( - db: &PgPool, - table_id: &str, - base_key_schema: &[KeySchemaElement], - id: &str, - key_schema: &[KeySchemaElement], -) { - sqlx::query( - "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ - projection) VALUES ($1, $2, $2, 'GSI', $3, '{\"ProjectionType\": \"ALL\"}')", - ) - .bind(table_id) - .bind(id) - .bind(json(&key_schema)) - .execute(db) - .await - .expect("seed the indexes row"); - let mut tx = db.begin().await.expect("begin"); - PostgresEngine::create_index_data_table( - &mut tx, - id, - key_schema, - &string_attributes(key_schema), - base_key_schema, - &string_attributes(base_key_schema), - ) - .await - .expect("create the index data table"); - tx.commit().await.expect("commit"); -} - -/// Insert rows into `_ddb_` one at a time, in the order given, which -/// is their heap order in a new table. -async fn insert(db: &PgPool, id: &str, columns: &[&str], rows: &[Vec]) { - let names: Vec = columns.iter().map(|c| format!("\"{c}\"")).collect(); - let params: Vec = (1..=columns.len()).map(|i| format!("${i}")).collect(); - let sql = format!( - "INSERT INTO \"_ddb_{id}\" ({}, item_data) VALUES ({}, '{{}}')", - names.join(", "), - params.join(", ") - ); - for row in rows { - let mut q = sqlx::query(&sql); - for value in row { - q = q.bind(value); - } - q.execute(db).await.unwrap_or_else(|e| panic!("{sql}: {e}")); - } -} - -fn row(values: &[&str]) -> Vec { - values.iter().map(|v| (*v).to_owned()).collect() -} - -/// Every value of `col` in `_ddb_`, sorted. -async fn column(db: &PgPool, id: &str, col: &str) -> Vec { - let sql = format!("SELECT \"{col}\" FROM \"_ddb_{id}\""); - let mut values: Vec = sqlx::query_scalar(&sql) - .fetch_all(db) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")); - values.sort(); - values -} - -/// The escape of each legacy text, sorted: what 004 must leave. -fn escaped>(legacy: &[S]) -> Vec { - let mut values: Vec = legacy - .iter() - .map(|t| escape_control(t.as_ref()).into_owned()) - .collect(); - values.sort(); - values -} - -fn rebuilt>(legacy: &[S]) -> Vec { - let mut values: Vec = legacy - .iter() - .map(|t| reescape_legacy_composite(t.as_ref()).expect("a netstring")) - .collect(); - values.sort(); - values -} - -async fn migrate(db: &PgPool) { - run_pool(db).await.expect("004 completes"); -} - -#[tokio::test] -async fn rewrites_a_partition_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_a_partition_key_pair_longest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "tp", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["a\u{1}", "a\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tp", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "tp", "pk").await, escaped(&legacy)); - s.cleanup().await; -} - -#[tokio::test] -async fn rewrites_a_sort_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_a_sort_key_pair_longest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "ts", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["s\u{1}", "s\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|sk| row(&["p", sk])).collect(); - insert(&s.db, "ts", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "ts", "sk_s").await, escaped(&legacy)); - assert_eq!(column(&s.db, "ts", "pk").await, vec!["p", "p"]); - s.cleanup().await; -} - -#[tokio::test] -async fn rebuilds_a_composite_partition_key_pair_longest_first() { - if base_conn().is_none() { - skip("rebuilds_a_composite_partition_key_pair_longest_first"); - return; - } - let s = scratch().await; - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tc", &ks).await; - // h1 = "a\x01" and h1 = "a\x01\x02", h2 = "b": the first one's rebuilt - // text is the second one's legacy text. - let legacy = ["2:a\u{1},1:b,", "3:a\u{1}\u{2},1:b,"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tc", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - let expected = rebuilt(&legacy); - assert_eq!( - expected, - vec!["3:a\u{1}\u{2},1:b,", "4:a\u{1}\u{2}\u{2},1:b,"] - ); - assert_eq!(column(&s.db, "tc", "pk").await, expected); - s.cleanup().await; -} - -#[tokio::test] -async fn rewrites_an_index_base_key_pair_longest_first() { - if base_conn().is_none() { - skip("rewrites_an_index_base_key_pair_longest_first"); - return; - } - let s = scratch().await; - let base = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; - table(&s.db, "tb", &base).await; - index(&s.db, "tb", &base, "ib", &[key("g", KeyType::Hash)]).await; - // Two base items with the same index key and base sort key. The base - // table's own pair is the partition key case above; it is left empty - // here so the index table is the one that is checked. - let legacy = ["p\u{1}", "p\u{1}\u{2}"]; - let rows: Vec> = legacy.iter().map(|p| row(&["g", p, "s"])).collect(); - insert(&s.db, "ib", &["pk", "base_pk", "base_sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "ib", "base_pk").await, escaped(&legacy)); - s.cleanup().await; -} - -/// More rows than one batch on both paths: a single-attribute column whose -/// one-statement rewrite fails, and a composite partition key column. The -/// pair of each table is three U+0001 long, so the rows between its two -/// lengths put the longer one in the first batch and the shorter one in the -/// second. Every final text is the escape of its legacy text; a row -/// rewritten twice would hold a longer one. -#[tokio::test] -async fn rewrites_each_row_once_across_batches() { - if base_conn().is_none() { - skip("rewrites_each_row_once_across_batches"); - return; - } - let fillers = 600; - assert!(fillers > BATCH); - let s = scratch().await; - - table( - &s.db, - "tf", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let short = "a\u{1}\u{1}\u{1}"; - let long = "a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2}"; - assert_eq!(escape_control(short), long); - let mut legacy = vec![short.to_owned()]; - legacy.extend((0..fillers).map(|i| format!("k\u{1}{i:04}"))); - legacy.push(long.to_owned()); - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tf", &["pk", "sk_s"], &rows).await; - - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tk", &ks).await; - let short = "4:a\u{1}\u{1}\u{1},1:b,"; - let long = "7:a\u{1}\u{2}\u{1}\u{2}\u{1}\u{2},1:b,"; - assert_eq!(reescape_legacy_composite(short).as_deref(), Some(long)); - let mut composite = vec![short.to_owned()]; - composite.extend((0..fillers).map(|i| format!("5:k\u{1}{i:03},1:b,"))); - composite.push(long.to_owned()); - let rows: Vec> = composite.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tk", &["pk", "sk_s"], &rows).await; - - migrate(&s.db).await; - assert_eq!(column(&s.db, "tf", "pk").await, escaped(&legacy)); - assert_eq!(column(&s.db, "tk", "pk").await, rebuilt(&composite)); - s.cleanup().await; -} - -/// A pair whose byte order is the reverse of its length order: the escape -/// of `a\x01b` is `a\x01\x02b`, which sorts below it, so an order by the -/// text itself, highest first, would rewrite the shorter key first. -#[tokio::test] -async fn rewrites_a_pair_whose_byte_order_is_shortest_first() { - if base_conn().is_none() { - skip("rewrites_a_pair_whose_byte_order_is_shortest_first"); - return; - } - let s = scratch().await; - table( - &s.db, - "tv", - &[key("pk", KeyType::Hash), key("sk", KeyType::Range)], - ) - .await; - let legacy = ["a\u{1}b", "a\u{1}\u{2}b"]; - let rows: Vec> = legacy.iter().map(|pk| row(&[pk, "s"])).collect(); - insert(&s.db, "tv", &["pk", "sk_s"], &rows).await; - migrate(&s.db).await; - assert_eq!(column(&s.db, "tv", "pk").await, escaped(&legacy)); - s.cleanup().await; -} - -/// An error from a rewrite names the DynamoDB table of the physical table: -/// here a two-HASH table whose `pk` is not a netstring. -#[tokio::test] -async fn an_error_names_the_dynamodb_table() { - if base_conn().is_none() { - skip("an_error_names_the_dynamodb_table"); - return; - } - let s = scratch().await; - let ks = [ - key("h1", KeyType::Hash), - key("h2", KeyType::Hash), - key("sk", KeyType::Range), - ]; - table(&s.db, "tn", &ks).await; - insert(&s.db, "tn", &["pk", "sk_s"], &[row(&["x\u{1}", "s"])]).await; - let err = run_pool(&s.db) - .await - .expect_err("a composite key that is not a netstring"); - let text = err.to_string(); - assert!( - text.contains("_ddb_tn.pk (table \"tn\" of account 111122223333)"), - "{text}" - ); - s.cleanup().await; -} - -#[tokio::test] -async fn a_duplicate_that_remains_is_reported_with_its_key() { - if base_conn().is_none() { - skip("a_duplicate_that_remains_is_reported_with_its_key"); - return; - } - let s = scratch().await; - sqlx::raw_sql( - r#"CREATE TABLE "dup" (pk TEXT COLLATE "C" PRIMARY KEY); - INSERT INTO "dup" VALUES (E'x\x01'), (E'y\x01');"#, - ) - .execute(&s.db) - .await - .expect("seed"); - let mut tx = s.db.begin().await.expect("begin"); - // A rewrite that gives every row one text: the second update fails. - let err = rewrite_longest_first(&mut tx, "\"dup\"", "pk", "TRUE", "dup.pk (t)", |_| { - Ok("z\u{1}".to_owned()) - }) - .await - .expect_err("a duplicate"); - let text = err.to_string(); - assert!(text.starts_with("re-encode dup.pk (t): "), "{text}"); - assert!( - text.contains("(DETAIL: \"Key (pk)=(z\\u{1}) already exists.\")"), - "{text}" - ); - tx.rollback().await.expect("rollback"); - s.cleanup().await; -} diff --git a/crates/storage-postgres/src/migrations/m0013_tests.rs b/crates/storage-postgres/src/migrations/m0013_tests.rs index 24cac406b..92f3b0a7c 100644 --- a/crates/storage-postgres/src/migrations/m0013_tests.rs +++ b/crates/storage-postgres/src/migrations/m0013_tests.rs @@ -135,10 +135,13 @@ pub(crate) async fn run(s: &Scratch) -> Result, MigrationError> { run_pool(&s.db).await } -/// Seed a data table, an index table, `gsi_pending`, `stream_records`, -/// `stream_pending` and `backup_items` with three row kinds: raw U+0001 in -/// key columns and inside jsonb strings and object keys, the literal -/// six-character text backslash-u-0001 inside a jsonb string, and plain rows. +/// Seed a data table, an index table, a vector index table, `gsi_pending`, +/// `stream_records`, `stream_pending` and `backup_items` with three row +/// kinds: raw U+0001 in key columns and inside jsonb strings and object keys, +/// the literal six-character text backslash-u-0001 inside a jsonb string, and +/// plain rows. The catalog also lists a `DELETING` table `t2`, whose physical +/// table holds a raw U+0001 row, with an index, and a table `t3` with no +/// physical table. pub(crate) async fn seed(db: &PgPool) { let ks = json!([ {"AttributeName": "pk", "KeyType": "HASH"}, @@ -175,6 +178,42 @@ pub(crate) async fn seed(db: &PgPool) { .execute(db) .await .expect("seed the indexes row"); + for (table_id, status) in [("t2", "DELETING"), ("t3", "ACTIVE")] { + sqlx::query( + "INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \ + table_status, table_arn, table_id) VALUES ($1, $2, $3, $4, $5, $6, $2)", + ) + .bind("111122223333") + .bind(table_id) + .bind(&ks) + .bind(&ad) + .bind(status) + .bind(format!( + "arn:aws:dynamodb:us-east-1:111122223333:table/{table_id}" + )) + .execute(db) + .await + .expect("seed a tables row"); + } + sqlx::query( + "INSERT INTO indexes (table_id, index_id, index_name, index_type, key_schema, \ + projection) VALUES ('t2', 'i2', 'gsi2', 'GSI', $1, $2)", + ) + .bind(json!([{"AttributeName": "gpk", "KeyType": "HASH"}])) + .bind(json!({"ProjectionType": "ALL"})) + .execute(db) + .await + .expect("seed the index row of the deleting table"); + sqlx::query( + "INSERT INTO vector_indexes (table_id, index_id, index_name, dimensions, \ + distance_function, vector_attribute, projection) \ + VALUES ('t1', 'v1', 'vec1', 2, 'COSINE', $1, $2)", + ) + .bind(json!({"AttributeName": "emb"})) + .bind(json!({"ProjectionType": "ALL"})) + .execute(db) + .await + .expect("seed the vector_indexes row"); sqlx::raw_sql( r#"CREATE TABLE "_ddb_t1" ( @@ -196,11 +235,32 @@ pub(crate) async fn seed(db: &PgPool) { base_sk_b BYTEA, item_data JSONB NOT NULL, PRIMARY KEY (pk, base_pk, base_sk_s) + ); + CREATE TABLE "_ddb_t2" ( + pk TEXT COLLATE "C" NOT NULL PRIMARY KEY, + item_data JSONB NOT NULL + ); + CREATE TABLE "_ddb_vec_v1" ( + base_pk TEXT COLLATE "C" NOT NULL PRIMARY KEY, + item_data JSONB NOT NULL );"#, ) .execute(db) .await - .expect("create the physical data and index tables"); + .expect("create the physical data, index and vector index tables"); + for (table, key_column, pk) in [ + ("_ddb_t2", "pk", "d\u{1}"), + ("_ddb_vec_v1", "base_pk", "a\u{1}b"), + ] { + sqlx::query(&format!( + "INSERT INTO \"{table}\" ({key_column}, item_data) VALUES ($1, $2)" + )) + .bind(pk) + .bind(json!({"pk": {"S": pk}, "k\u{1}": {"S": "v\u{1}"}})) + .execute(db) + .await + .expect("seed a row of the deleting table or of the vector index table"); + } for (pk, sk, item) in [ ( @@ -335,18 +395,25 @@ async fn reencodes_legacy_rows() { assert_eq!( notes, vec![ - "backup_items: 3 row update(s)", - "_ddb_t1 (table \"t\" of account 111122223333): 3 row update(s)", - "_ddb_i1 (index \"gsi1\" of table \"t\" of account 111122223333): 5 row update(s)", + "backup_items: 1 row update(s)", + "table \"t2\" of account 111122223333: skipped, the table is being deleted", + "table \"t3\" of account 111122223333: skipped, its physical table _ddb_t3 does not \ + exist", + "index \"gsi2\" of table \"t2\" of account 111122223333: skipped, the table is being \ + deleted", + "_ddb_t1 (table \"t\" of account 111122223333): 1 row update(s)", + "_ddb_i1 (index \"gsi1\" of table \"t\" of account 111122223333): 1 row update(s)", + "_ddb_vec_v1 (vector index \"vec1\" of table \"t\" of account 111122223333): 1 row \ + update(s)", "gsi_pending: 1 row update(s)", "stream_records: 1 row update(s)", "stream_pending: 1 row update(s)", ] ); - // Data table: raw U+0001 became U+0001 U+0002 in the key columns and - // inside every jsonb string and object key; the literal-backslash row - // and the plain row are byte-identical. + // Data table: raw U+0001 became U+0001 U+0002 inside every jsonb string + // and object key, and the key columns keep their text; the + // literal-backslash row and the plain row are byte-identical. let rows: Vec<(String, String, serde_json::Value)> = sqlx::query_as("SELECT pk, sk_s, item_data FROM \"_ddb_t1\" ORDER BY pk") .fetch_all(&s.db) @@ -356,8 +423,8 @@ async fn reencodes_legacy_rows() { rows, vec![ ( - "a\u{1}\u{2}b".to_owned(), - "s\u{1}\u{2}".to_owned(), + "a\u{1}b".to_owned(), + "s\u{1}".to_owned(), json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), ), ( @@ -373,7 +440,8 @@ async fn reencodes_legacy_rows() { ] ); - // Index table: pk, sk_s, base_pk, base_sk_s and item_data all re-encoded. + // Index table: item_data re-encoded, pk, sk_s, base_pk and base_sk_s as + // they were. let rows: Vec<(String, String, String, String, serde_json::Value)> = sqlx::query_as( "SELECT pk, sk_s, base_pk, base_sk_s, item_data FROM \"_ddb_i1\" ORDER BY pk", ) @@ -384,10 +452,10 @@ async fn reencodes_legacy_rows() { rows, vec![ ( - "g\u{1}\u{2}".to_owned(), - "gs\u{1}\u{2}".to_owned(), - "a\u{1}\u{2}b".to_owned(), - "s\u{1}\u{2}".to_owned(), + "g\u{1}".to_owned(), + "gs\u{1}".to_owned(), + "a\u{1}b".to_owned(), + "s\u{1}".to_owned(), json!({"gpk": {"S": "g\u{1}\u{2}"}}), ), ( @@ -400,6 +468,29 @@ async fn reencodes_legacy_rows() { ] ); + // The vector index table is re-encoded; the deleting table is not. + for (table, key_column, pk, item) in [ + ( + "_ddb_vec_v1", + "base_pk", + "a\u{1}b", + json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), + ), + ( + "_ddb_t2", + "pk", + "d\u{1}", + json!({"pk": {"S": "d\u{1}"}, "k\u{1}": {"S": "v\u{1}"}}), + ), + ] { + let rows: Vec<(String, serde_json::Value)> = + sqlx::query_as(&format!("SELECT {key_column}, item_data FROM \"{table}\"")) + .fetch_all(&s.db) + .await + .expect("read a vector index or deleting table"); + assert_eq!(rows, vec![(pk.to_owned(), item)], "{table}"); + } + // gsi_pending: NULL old_item stays NULL, the raw row's item image is // re-encoded, and its index context is left as it is: migration 11 // escapes `index_context`. The plain row is untouched. @@ -452,7 +543,8 @@ async fn reencodes_legacy_rows() { ] ); - // backup_items, including the NULL sk row. + // backup_items, including the NULL sk row: item_data re-encoded, pk and + // sk as they were. let rows: Vec<(String, Option, serde_json::Value)> = sqlx::query_as("SELECT pk, sk, item_data FROM backup_items ORDER BY pk") .fetch_all(&s.db) @@ -462,8 +554,8 @@ async fn reencodes_legacy_rows() { rows, vec![ ( - "p\u{1}\u{2}".to_owned(), - Some("s\u{1}\u{2}".to_owned()), + "p\u{1}".to_owned(), + Some("s\u{1}".to_owned()), json!({"pk": {"S": "p\u{1}\u{2}"}}), ), ("plain".to_owned(), None, json!({"pk": {"S": "plain"}}),), @@ -512,8 +604,8 @@ async fn reencodes_jsonb_rows_with_standard_conforming_strings_off() { .fetch_one(&s.db) .await .unwrap(); - assert_eq!(pk, "a\u{1}\u{2}b"); - assert_eq!(sk, "s\u{1}\u{2}"); + assert_eq!(pk, "a\u{1}b"); + assert_eq!(sk, "s\u{1}"); assert_eq!( item, json!({"pk": {"S": "a\u{1}\u{2}b"}, "k\u{1}\u{2}": {"S": "v\u{1}\u{2}"}}), diff --git a/crates/storage-postgres/src/migrations/mod.rs b/crates/storage-postgres/src/migrations/mod.rs index 94c2ce3d5..451cb1d17 100644 --- a/crates/storage-postgres/src/migrations/mod.rs +++ b/crates/storage-postgres/src/migrations/mod.rs @@ -704,10 +704,6 @@ pub async fn apply_all_migrations( #[cfg(test)] mod m0013_guard_tests; #[cfg(test)] -mod m0013_keys_tests; -#[cfg(test)] -mod m0013_order_tests; -#[cfg(test)] mod m0013_tests; #[cfg(test)] mod tests; diff --git a/crates/storage-postgres/tests/backup_restore/control_chars.rs b/crates/storage-postgres/tests/backup_restore/control_chars.rs index c3b50757a..baebcaf3b 100644 --- a/crates/storage-postgres/tests/backup_restore/control_chars.rs +++ b/crates/storage-postgres/tests/backup_restore/control_chars.rs @@ -18,13 +18,17 @@ async fn stored_rows(s: &Scratch, physical_id: &str) -> Vec { .expect("read stored rows") } -/// Items holding U+0000 and U+0001 in key values, index key values, nested -/// values, and attribute names are stored through the control-character -/// escape. The legacy reader decodes the backup's items, and a restore +/// Items holding U+0001 in key values and index key values, and U+0000 and +/// U+0001 in nested values and attribute names: the documents are stored +/// through the control-character escape, and the key columns hold the key +/// text as it is. The legacy reader decodes the backup's items, and a restore /// copies `backup_items` text into the target as it is and derives the key /// columns and index rows from it, so those must come out in the same stored -/// form as the source's (escaped once, not twice), and the restored items -/// must read back equal to what was written. +/// form as the source's (documents escaped once, not twice), and the restored +/// items must read back equal to what was written. One item, stored as a +/// write before the GSI existed would store it, holds U+0000 in the GSI's key +/// `g`, which the key columns cannot hold: the source's index has no row for +/// it, and the restore leaves it out of the index too. #[tokio::test] async fn restore_keeps_control_characters_in_keys_indexes_and_items() { if base_conn().is_none() { @@ -53,17 +57,17 @@ async fn restore_keeps_control_characters_in_keys_indexes_and_items() { .await .expect("describe the source"); let src_key_info = key_info("nul_src", &src, &src_desc); - let items: Vec = [ + let mut items: Vec = [ serde_json::json!({ - "pk": {"S": "p\u{0}a"}, "sk": {"N": "1"}, - "g": {"S": "g\u{0}\u{1}"}, "l": {"S": "l\u{1}\u{1}x"}, + "pk": {"S": "p\u{1}a"}, "sk": {"N": "1"}, + "g": {"S": "g\u{1}\u{2}"}, "l": {"S": "l\u{1}\u{1}x"}, "n\u{0}ame": {"S": "v\u{0}"}, "m": {"M": {"k\u{1}": {"S": "\u{0}"}, "plain": {"N": "2"}}}, "list": {"L": [{"S": "\u{1}\u{2}"}, {"SS": ["a\u{0}", "b"]}]} }), serde_json::json!({ - "pk": {"S": "p\u{0}a"}, "sk": {"N": "2"}, - "g": {"S": "g\u{0}\u{1}"}, "l": {"S": "l\u{0}"} + "pk": {"S": "p\u{1}a"}, "sk": {"N": "2"}, + "g": {"S": "g\u{1}\u{2}"}, "l": {"S": "l\u{1}"}, "v": {"S": "\u{0}"} }), serde_json::json!({"pk": {"S": "\u{1}"}, "sk": {"N": "3"}, "l": {"S": "\u{1}\u{2}"}}), serde_json::json!({"pk": {"S": "plain"}, "sk": {"N": "4"}, "g": {"S": "g"}}), @@ -85,6 +89,21 @@ async fn restore_keeps_control_characters_in_keys_indexes_and_items() { .expect("put"); } + let nul_in_gsi_key: Item = serde_json::from_value(serde_json::json!({ + "pk": {"S": "nul"}, "sk": {"N": "5"}, "g": {"S": "g\u{0}"} + })) + .expect("item"); + sqlx::query(&format!( + "INSERT INTO \"_ddb_{src}\" (pk, sk_n, item_data) VALUES ('nul', 5, $1)" + )) + .bind(extenddb_storage::util::escape_json_strings( + serde_json::to_value(&nul_in_gsi_key).expect("item json"), + )) + .execute(&s.db) + .await + .expect("store the item as a write before the GSI would"); + items.push(nul_in_gsi_key); + let backup = s .engine .create(ACCOUNT, "nul_src", "b", JobPermit::detached()) @@ -115,7 +134,8 @@ async fn restore_keeps_control_characters_in_keys_indexes_and_items() { assert_eq!(table_status(&s, "nul_dst").await.as_deref(), Some("ACTIVE")); // The base table and each index table hold the same stored rows as the - // source's, so every key column and document was escaped exactly once. + // source's, so every key column kept its text and every document was + // escaped exactly once. assert_eq!( stored_rows(&s, &desc.table_id).await, stored_rows(&s, &src).await diff --git a/crates/storage-postgres/tests/fixtures/golden/0013_escape_control_chars.txt b/crates/storage-postgres/tests/fixtures/golden/0013_escape_control_chars.txt index fafe378b2..d7bc17052 100644 --- a/crates/storage-postgres/tests/fixtures/golden/0013_escape_control_chars.txt +++ b/crates/storage-postgres/tests/fixtures/golden/0013_escape_control_chars.txt @@ -1,66 +1,66 @@ -_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g0\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/gsi1 pk="g1\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s000\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s003\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s006\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p0\u{1}\u{2}" sk=Some("s009\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s001\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s004\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p1\u{1}\u{2}" sk=Some("s007\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s002\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s005\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -_ddb_T:seed_tbl pk="seed-p2\u{1}\u{2}" sk=Some("s008\u{1}\u{2}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p0\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p1\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") -backup_items pk="seed-p2\u{1}\u{2}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}" sk=Some("s000\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}" sk=Some("s003\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}" sk=Some("s006\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p0\u{1}" sk=Some("s009\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}" sk=Some("s001\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}" sk=Some("s004\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p1\u{1}" sk=Some("s007\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}" sk=Some("s002\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}" sk=Some("s005\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 base pk="seed-p2\u{1}" sk=Some("s008\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}" sk=Some("s000\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}" sk=Some("s002\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}" sk=Some("s004\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}" sk=Some("s006\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g0\u{1}" sk=Some("s008\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}" sk=Some("s001\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}" sk=Some("s003\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}" sk=Some("s005\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}" sk=Some("s007\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/gsi1 pk="g1\u{1}" sk=Some("s009\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}" sk=Some("s000\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}" sk=Some("s003\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}" sk=Some("s006\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p0\u{1}" sk=Some("s009\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}" sk=Some("s001\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}" sk=Some("s004\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p1\u{1}" sk=Some("s007\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}" sk=Some("s002\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}" sk=Some("s005\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 base pk="seed-p2\u{1}" sk=Some("s008\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_I:seed_tbl/lsi1 pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}" sk=Some("s000\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}" sk=Some("s003\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}" sk=Some("s006\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p0\u{1}" sk=Some("s009\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}" sk=Some("s001\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}" sk=Some("s004\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p1\u{1}" sk=Some("s007\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}" sk=Some("s002\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}" sk=Some("s005\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +_ddb_T:seed_tbl pk="seed-p2\u{1}" sk=Some("s008\u{1}") Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p0\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p1\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") +backup_items pk="seed-p2\u{1}" sk=None Some("note\u{1}\u{2}=v\u{1}\u{2}\u{2}") catalog notes: -backup_items: 20 row update(s) +backup_items: 10 row update(s) data notes: -_ddb_T:seed_tbl (table "seed_tbl" of account 123456789012): 30 row update(s) -_ddb_I:seed_tbl/lsi1 (index "lsi1" of table "seed_tbl" of account 123456789012): 40 row update(s) -_ddb_I:seed_tbl/gsi1 (index "gsi1" of table "seed_tbl" of account 123456789012): 50 row update(s) +_ddb_T:seed_tbl (table "seed_tbl" of account 123456789012): 10 row update(s) +_ddb_I:seed_tbl/lsi1 (index "lsi1" of table "seed_tbl" of account 123456789012): 10 row update(s) +_ddb_I:seed_tbl/gsi1 (index "gsi1" of table "seed_tbl" of account 123456789012): 10 row update(s) diff --git a/crates/storage-postgres/tests/migrations_golden.rs b/crates/storage-postgres/tests/migrations_golden.rs index 246cea3cf..f3ee27f8a 100644 --- a/crates/storage-postgres/tests/migrations_golden.rs +++ b/crates/storage-postgres/tests/migrations_golden.rs @@ -449,7 +449,8 @@ async fn rows_of(pool: &PgPool, table: &str, label: &str, key: [&str; 2]) -> Vec /// Migration 13 on the 0.1.14 fixture, migrated through 12, whose strings an /// earlier release stored with a raw U+0001: in the key columns of /// `seed_tbl`'s table, GSI and LSI, in their documents, and in the backup's -/// `backup_items`. +/// `backup_items`. The documents are re-encoded, and the key columns keep +/// their text. #[tokio::test] async fn migration_13_escapes_the_strings_an_earlier_release_stored() { let Some(base) = base_conn() else { @@ -537,6 +538,69 @@ async fn ledger_rows_of_13(pool: &PgPool) -> i64 { .unwrap() } +/// A partition key of 2046 bytes, within the service's 2048, made of letters +/// from a fixed pseudo-random sequence with U+0001 after every second one +/// (682 of them), which an earlier release stores in `pk` as it is. Migration +/// 13 applies in both stores and leaves the key's 2046 bytes as they were; +/// escaping the key column would make it 2728 bytes, over PostgreSQL's btree +/// entry limit of 2704. +#[tokio::test] +async fn migration_13_applies_over_a_long_key_holding_u0001() { + let Some(base) = base_conn() else { + return skip("migration 13 long key"); + }; + let mut state: u32 = 0x2545_f491; + let mut key = String::new(); + for i in 0..1364 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + key.push(char::from(b'a' + (state % 26) as u8)); + if i % 2 == 1 { + key.push('\u{1}'); + } + } + assert_eq!((key.len(), key.matches('\u{1}').count()), (2046, 682)); + let s = Scratch::new(&base, "pgm_g13k").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::UniqueAccessKeyIds).await; + let catalog = s.catalog().await; + let data = s.data().await; + let (table, _) = seed_tbl_tables(&catalog).await.remove(0); + let item = serde_json::json!({"pk": {"S": key}, "sk": {"S": "long"}}); + sqlx::query(&format!( + "INSERT INTO \"{table}\" (pk, sk_s, item_data) VALUES ($1, 'long', $2)" + )) + .bind(&key) + .bind(&item) + .execute(&data) + .await + .expect("main stores the key"); + catalog.close().await; + data.close().await; + + s.migrate_through(MigrationId::EscapeControlChars).await; + assert_eq!(s.status().await, CatalogStatus::Current { version: LATEST }); + let catalog = s.catalog().await; + let data = s.data().await; + assert_eq!(ledger_rows_of_13(&catalog).await, 1, "catalog ledger"); + assert_eq!(ledger_rows_of_13(&data).await, 1, "data ledger"); + let (pk, stored): (String, serde_json::Value) = sqlx::query_as(&format!( + "SELECT pk, item_data FROM \"{table}\" WHERE sk_s = 'long'" + )) + .fetch_one(&data) + .await + .unwrap(); + assert_eq!(pk, key); + let escaped = key.replace('\u{1}', "\u{1}\u{2}"); + assert_eq!( + stored, + serde_json::json!({"pk": {"S": escaped}, "sk": {"S": "long"}}) + ); + catalog.close().await; + data.close().await; +} + /// While another session holds the data database of a store with tables, /// `migrate --yes` stops with exit 5 before its first write, naming the /// session, and migrates once the session is gone. diff --git a/crates/storage-postgres/tests/restore_job/control_chars.rs b/crates/storage-postgres/tests/restore_job/control_chars.rs index 907ecea2e..10c63210e 100644 --- a/crates/storage-postgres/tests/restore_job/control_chars.rs +++ b/crates/storage-postgres/tests/restore_job/control_chars.rs @@ -6,9 +6,9 @@ use extenddb_storage::util::{escape_json_strings, unescape_json_strings}; use super::*; /// `bulk_load` writes each item's `item_data` in the stored form that the -/// write path gives it (`data::item_to_json`): an item with U+0000 and U+0001 -/// in its key, its names and its values loads, and its row holds the escape -/// once. +/// write path gives it (`data::item_to_json`): an item with U+0001 in its +/// key and U+0000 and U+0001 in its names and values loads, and its row holds +/// the escape once. #[tokio::test] async fn bulk_load_stores_control_characters_through_the_escape() { if !pg_available("bulk_load_stores_control_characters_through_the_escape") { @@ -18,7 +18,7 @@ async fn bulk_load_stores_control_characters_through_the_escape() { let row = available_backup(&s, "Music").await; let (_desc, key, claim) = register(&s, &row, "Loaded", None).await; let written = serde_json::json!({ - "pk": {"S": "p\u{0}a"}, + "pk": {"S": "p\u{1}a"}, "sk": {"N": "1"}, "g": {"S": "g\u{1}"}, "n\u{0}ame": {"M": {"k\u{1}": {"S": "\u{0}\u{1}\u{2}"}}} diff --git a/crates/storage/src/util/key.rs b/crates/storage/src/util/key.rs index b72d1f202..9391c1d3b 100755 --- a/crates/storage/src/util/key.rs +++ b/crates/storage/src/util/key.rs @@ -23,8 +23,8 @@ pub enum SortKeyValue { /// For multi-attribute keys, uses netstring encoding: each part is encoded as /// `:,` and concatenated. This is collision-free /// regardless of value content. The parts are the raw attribute strings; a -/// backend whose columns cannot hold every character (PostgreSQL, see -/// `escape_control`) escapes its key text in its own wrapper. +/// backend whose columns cannot hold every character (PostgreSQL text cannot +/// hold U+0000) refuses such a key in its own wrapper. pub fn composite_pk_to_text( item: &Item, key_schema: &[KeySchemaElement], diff --git a/tests/test_nul_strings.py b/tests/test_nul_strings.py index 0e1d8c511..4fba14353 100644 --- a/tests/test_nul_strings.py +++ b/tests/test_nul_strings.py @@ -12,18 +12,25 @@ the character rather than its escape text and has to keep it out of the way of its own storage encoding. +The PostgreSQL backend's key columns cannot hold NUL. It stores NUL in values, +attribute names and map keys, and refuses a key value that holds NUL with a +ValidationException (see docs/differences-from-dynamodb.md): the tests that +put NUL in a key skip there, and ``test_postgresql_refuses_nul_in_a_key_value`` +pins that answer. + U+0001 is included because a storage encoding that handles NUL has to leave the next code point alone as well. """ from __future__ import annotations +import random import time import pytest from botocore.exceptions import ClientError -from conftest import scoped_table, wait_for_gsi_items +from conftest import configured_backend, scoped_table, wait_for_gsi_items NUL = "\u0000" SOH = "\u0001" @@ -37,18 +44,39 @@ # escape text (starts with 0x5c), then "a" (0x61). SORT_KEYS = [NUL, SOH, " ", ESCAPE_TEXT, "a"] -# The item under the NUL sort key carries the character in every kind of -# position the item model has. +ON_POSTGRESQL = configured_backend() == "postgres" +nul_keys = pytest.mark.skipif( + ON_POSTGRESQL, + reason="the PostgreSQL backend refuses NUL in a key value; see " + "docs/differences-from-dynamodb.md", +) +# The two key characters the item tests run with: NUL where keys can hold it. +KEY_CHARS = [pytest.param(NUL, id="nul", marks=nul_keys), pytest.param(SOH, id="soh")] + +NUL_IN_KEY = ( + "Key attribute values cannot contain the character U+0000 on the PostgreSQL " + "storage backend, whose text columns cannot hold the byte 0x00. Remove the " + "character from the key value, or use another storage backend." +) + +# NUL in every kind of position the item model has outside the keys, which +# hold U+0001. RICH_ITEM = { - "pk": {"S": PK}, - "sk": {"S": NUL}, - "g": {"S": f"g{NUL}"}, + "pk": {"S": f"r{SOH}"}, + "sk": {"S": f"{SOH}{SOH}"}, + "g": {"S": f"g{SOH}{SOH}"}, "v": {"S": f"v{NUL}"}, f"n{NUL}n": {"S": "x"}, "m": {"M": {f"k{NUL}": {"S": f"{NUL}"}, f"k{SOH}{SOH}": {"N": "1"}}}, "l": {"L": [{"S": NUL}, {"S": f"{SOH}{NUL}{SOH}"}]}, "ss": {"SS": [NUL, "a"]}, } +RICH_KEY = {"pk": RICH_ITEM["pk"], "sk": RICH_ITEM["sk"]} + +# The item under the NUL sort key, with NUL in its GSI key and a value. +NUL_KEY_ITEM = {"pk": {"S": PK}, "sk": {"S": NUL}, "g": {"S": f"g{NUL}"}, "v": {"S": f"v{NUL}"}} + +UPDATE_KEY = {"pk": {"S": PK_SOH}, "sk": {"S": " "}} def _query(client, table, **kwargs): @@ -64,55 +92,71 @@ def _sks(resp): return [i["sk"]["S"] for i in resp["Items"]] +def _error(exc) -> tuple[int, str, str]: + err = exc.value.response + return (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) + + +TABLE_SCHEMA = dict( + attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + GlobalSecondaryIndexes=[ + { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + ], +) + + @pytest.fixture(scope="class") def nul_table(dynamodb_client): - """(S, S) table with GSI gsi1 on g; the partition PK holds SORT_KEYS, plus - a control item in the partition without the NUL and one in a partition - keyed with U+0001.""" - with scoped_table( - dynamodb_client, - attribute_definitions=[ - {"AttributeName": "pk", "AttributeType": "S"}, - {"AttributeName": "sk", "AttributeType": "S"}, - {"AttributeName": "g", "AttributeType": "S"}, - ], - key_schema=[ - {"AttributeName": "pk", "KeyType": "HASH"}, - {"AttributeName": "sk", "KeyType": "RANGE"}, - ], - GlobalSecondaryIndexes=[ - { - "IndexName": "gsi1", - "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], - "Projection": {"ProjectionType": "ALL"}, - } - ], - ) as name: - dynamodb_client.put_item(TableName=name, Item=RICH_ITEM) - for sk in SORT_KEYS[1:]: - dynamodb_client.put_item( - TableName=name, Item={"pk": {"S": PK}, "sk": {"S": sk}, "g": {"S": "plain"}} - ) - dynamodb_client.put_item( - TableName=name, Item={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": "x"}, "g": {"S": "plain"}} - ) - dynamodb_client.put_item( - TableName=name, - Item={"pk": {"S": PK_SOH}, "sk": {"S": SOH}, "g": {"S": f"g{SOH}"}, "v": {"S": SOH}}, - ) - yield name + """(S, S) table with GSI gsi1 on g. It holds RICH_ITEM, an item keyed with + U+0001, and the item UPDATE_KEY names; where keys can hold NUL, also the + partition PK with SORT_KEYS (NUL_KEY_ITEM under the NUL sort key) and a + control item in the partition without the NUL. Yields the table name and + its item count.""" + with scoped_table(dynamodb_client, **TABLE_SCHEMA) as name: + items = [ + RICH_ITEM, + {"pk": {"S": PK_SOH}, "sk": {"S": SOH}, "g": {"S": f"g{SOH}"}, "v": {"S": SOH}}, + {**UPDATE_KEY, "g": {"S": "plain"}}, + ] + if not ON_POSTGRESQL: + items.append(NUL_KEY_ITEM) + items += [{"pk": {"S": PK}, "sk": {"S": sk}, "g": {"S": "plain"}} for sk in SORT_KEYS[1:]] + items.append({"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": "x"}, "g": {"S": "plain"}}) + for item in items: + dynamodb_client.put_item(TableName=name, Item=item) + yield name, len(items) class TestNulInStrings: - def test_item_with_nul_everywhere_round_trips(self, dynamodb_client, nul_table): + def test_item_with_nul_outside_its_keys_round_trips(self, dynamodb_client, nul_table): + table, _ = nul_table + resp = dynamodb_client.get_item(TableName=table, Key=RICH_KEY, ConsistentRead=True) + assert resp["Item"] == RICH_ITEM + + @nul_keys + def test_item_with_nul_in_its_keys_round_trips(self, dynamodb_client, nul_table): + table, _ = nul_table resp = dynamodb_client.get_item( - TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + TableName=table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True ) - assert resp["Item"] == RICH_ITEM + assert resp["Item"] == NUL_KEY_ITEM def test_soh_item_round_trips(self, dynamodb_client, nul_table): + table, _ = nul_table resp = dynamodb_client.get_item( - TableName=nul_table, Key={"pk": {"S": PK_SOH}, "sk": {"S": SOH}}, ConsistentRead=True + TableName=table, Key={"pk": {"S": PK_SOH}, "sk": {"S": SOH}}, ConsistentRead=True ) assert resp["Item"] == { "pk": {"S": PK_SOH}, @@ -121,83 +165,102 @@ def test_soh_item_round_trips(self, dynamodb_client, nul_table): "v": {"S": SOH}, } + @nul_keys def test_partition_order_is_byte_order_with_nul_first(self, dynamodb_client, nul_table): - assert _sks(_query(dynamodb_client, nul_table, ConsistentRead=True)) == SORT_KEYS + table, _ = nul_table + assert _sks(_query(dynamodb_client, table, ConsistentRead=True)) == SORT_KEYS assert ( - _sks(_query(dynamodb_client, nul_table, ScanIndexForward=False, ConsistentRead=True)) + _sks(_query(dynamodb_client, table, ScanIndexForward=False, ConsistentRead=True)) == SORT_KEYS[::-1] ) + @nul_keys def test_nul_and_its_escape_text_are_different_keys(self, dynamodb_client, nul_table): + table, _ = nul_table by_nul = dynamodb_client.get_item( - TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + TableName=table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True )["Item"] by_text = dynamodb_client.get_item( - TableName=nul_table, Key={"pk": {"S": PK}, "sk": {"S": ESCAPE_TEXT}}, ConsistentRead=True + TableName=table, Key={"pk": {"S": PK}, "sk": {"S": ESCAPE_TEXT}}, ConsistentRead=True )["Item"] assert by_nul["sk"]["S"] == NUL and len(by_nul["sk"]["S"]) == 1 assert by_text["sk"]["S"] == ESCAPE_TEXT and len(by_text["sk"]["S"]) == 6 + @nul_keys def test_partition_key_with_nul_is_distinct_from_the_key_without_it( self, dynamodb_client, nul_table ): + table, _ = nul_table resp = dynamodb_client.get_item( - TableName=nul_table, Key={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": NUL}}, ConsistentRead=True + TableName=table, Key={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": NUL}}, ConsistentRead=True ) assert "Item" not in resp - resp = _query(dynamodb_client, nul_table, values={":p": {"S": PK_WITHOUT_NUL}}, ConsistentRead=True) + resp = _query(dynamodb_client, table, values={":p": {"S": PK_WITHOUT_NUL}}, ConsistentRead=True) assert _sks(resp) == ["x"] + @nul_keys def test_range_conditions_treat_nul_as_a_byte(self, dynamodb_client, nul_table): + table, _ = nul_table below_space = _query( - dynamodb_client, nul_table, cond="pk = :p AND sk < :s", values={":s": {"S": " "}}, + dynamodb_client, table, cond="pk = :p AND sk < :s", values={":s": {"S": " "}}, ConsistentRead=True, ) assert _sks(below_space) == [NUL, SOH] between = _query( - dynamodb_client, nul_table, cond="pk = :p AND sk BETWEEN :lo AND :hi", + dynamodb_client, table, cond="pk = :p AND sk BETWEEN :lo AND :hi", values={":lo": {"S": NUL}, ":hi": {"S": SOH}}, ConsistentRead=True, ) assert _sks(between) == [NUL, SOH] prefix = _query( - dynamodb_client, nul_table, cond="pk = :p AND begins_with(sk, :pre)", + dynamodb_client, table, cond="pk = :p AND begins_with(sk, :pre)", values={":pre": {"S": NUL}}, ConsistentRead=True, ) assert _sks(prefix) == [NUL] text_prefix = _query( - dynamodb_client, nul_table, cond="pk = :p AND begins_with(sk, :pre)", + dynamodb_client, table, cond="pk = :p AND begins_with(sk, :pre)", values={":pre": {"S": "\\"}}, ConsistentRead=True, ) assert _sks(text_prefix) == [ESCAPE_TEXT] + @nul_keys def test_pages_of_one_visit_every_key_once(self, dynamodb_client, nul_table): """The cursor for a NUL key travels through LastEvaluatedKey and back through ExclusiveStartKey; the walk must neither skip nor repeat.""" + table, _ = nul_table seen: list[str] = [] kwargs: dict = {"Limit": 1, "ConsistentRead": True} while True: - resp = _query(dynamodb_client, nul_table, **kwargs) + resp = _query(dynamodb_client, table, **kwargs) seen += _sks(resp) if "LastEvaluatedKey" not in resp: break kwargs["ExclusiveStartKey"] = resp["LastEvaluatedKey"] assert seen == SORT_KEYS - def test_gsi_holds_the_item_with_a_nul_key(self, dynamodb_client, nul_table): + @pytest.mark.parametrize( + "gsi_key,want", + [ + pytest.param(f"g{NUL}", NUL_KEY_ITEM, id="nul", marks=nul_keys), + pytest.param(f"g{SOH}{SOH}", RICH_ITEM, id="soh"), + ], + ) + def test_gsi_holds_the_item(self, dynamodb_client, nul_table, gsi_key, want): + table, _ = nul_table + def walk(): return dynamodb_client.query( - TableName=nul_table, + TableName=table, IndexName="gsi1", KeyConditionExpression="g = :g", - ExpressionAttributeValues={":g": {"S": f"g{NUL}"}}, + ExpressionAttributeValues={":g": {"S": gsi_key}}, )["Items"] - items = wait_for_gsi_items(walk, 1) - assert items == [RICH_ITEM] + assert wait_for_gsi_items(walk, 1) == [want] def test_filter_on_a_nul_named_attribute(self, dynamodb_client, nul_table): + table, _ = nul_table resp = dynamodb_client.scan( - TableName=nul_table, + TableName=table, FilterExpression="#n = :x", ExpressionAttributeNames={"#n": f"n{NUL}n"}, ExpressionAttributeValues={":x": {"S": "x"}}, @@ -205,16 +268,17 @@ def test_filter_on_a_nul_named_attribute(self, dynamodb_client, nul_table): ) assert resp["Items"] == [RICH_ITEM] resp = _query( - dynamodb_client, nul_table, FilterExpression="v = :v", - values={":v": {"S": f"v{NUL}"}}, ConsistentRead=True, + dynamodb_client, table, FilterExpression="v = :v", + values={":p": RICH_ITEM["pk"], ":v": {"S": f"v{NUL}"}}, ConsistentRead=True, ) assert resp["Items"] == [RICH_ITEM] def test_condition_expression_sees_the_nul_named_attribute(self, dynamodb_client, nul_table): + table, _ = nul_table # Exists on the rich item: the conditional write goes through. dynamodb_client.update_item( - TableName=nul_table, - Key={"pk": {"S": PK}, "sk": {"S": NUL}}, + TableName=table, + Key=RICH_KEY, UpdateExpression="SET touched = :t", ConditionExpression="attribute_exists(#n)", ExpressionAttributeNames={"#n": f"n{NUL}n"}, @@ -222,25 +286,21 @@ def test_condition_expression_sees_the_nul_named_attribute(self, dynamodb_client ) with pytest.raises(ClientError) as exc: dynamodb_client.update_item( - TableName=nul_table, - Key={"pk": {"S": PK}, "sk": {"S": "a"}}, + TableName=table, + Key=UPDATE_KEY, UpdateExpression="SET touched = :t", ConditionExpression="attribute_exists(#n)", ExpressionAttributeNames={"#n": f"n{NUL}n"}, ExpressionAttributeValues={":t": {"BOOL": True}}, ) - assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException" - dynamodb_client.update_item( - TableName=nul_table, - Key={"pk": {"S": PK}, "sk": {"S": NUL}}, - UpdateExpression="REMOVE touched", - ) + assert _error(exc) == (400, "ConditionalCheckFailedException", "The conditional request failed") + dynamodb_client.update_item(TableName=table, Key=RICH_KEY, UpdateExpression="REMOVE touched") def test_update_item_sets_nul_named_attribute_and_nul_value(self, dynamodb_client, nul_table): - key = {"pk": {"S": PK}, "sk": {"S": " "}} + table, _ = nul_table resp = dynamodb_client.update_item( - TableName=nul_table, - Key=key, + TableName=table, + Key=UPDATE_KEY, UpdateExpression="SET #a = :v, m2 = :m", ExpressionAttributeNames={"#a": f"u{NUL}"}, ExpressionAttributeValues={ @@ -251,44 +311,46 @@ def test_update_item_sets_nul_named_attribute_and_nul_value(self, dynamodb_clien ) assert resp["Attributes"][f"u{NUL}"] == {"S": f"{NUL}z"} assert resp["Attributes"]["m2"] == {"M": {f"{NUL}": {"L": [{"S": SOH}]}}} - got = dynamodb_client.get_item(TableName=nul_table, Key=key, ConsistentRead=True)["Item"] + got = dynamodb_client.get_item(TableName=table, Key=UPDATE_KEY, ConsistentRead=True)["Item"] assert got[f"u{NUL}"] == {"S": f"{NUL}z"} assert got["m2"] == {"M": {f"{NUL}": {"L": [{"S": SOH}]}}} resp = dynamodb_client.update_item( - TableName=nul_table, - Key=key, + TableName=table, + Key=UPDATE_KEY, UpdateExpression="REMOVE #a, m2", ExpressionAttributeNames={"#a": f"u{NUL}"}, ReturnValues="ALL_NEW", ) assert f"u{NUL}" not in resp["Attributes"] and "m2" not in resp["Attributes"] - def test_batch_and_transact_writes_and_reads(self, dynamodb_client, nul_table): - b1 = {"pk": {"S": f"batch{NUL}"}, "sk": {"S": NUL}, "g": {"S": "plain"}, f"{NUL}": {"S": NUL}} - t1 = {"pk": {"S": f"tx{NUL}"}, "sk": {"S": f"{NUL}{NUL}"}, "g": {"S": "plain"}} - dynamodb_client.batch_write_item(RequestItems={nul_table: [{"PutRequest": {"Item": b1}}]}) + @pytest.mark.parametrize("c", KEY_CHARS) + def test_batch_and_transact_writes_and_reads(self, dynamodb_client, nul_table, c): + table, _ = nul_table + b1 = {"pk": {"S": f"batch{c}"}, "sk": {"S": c}, "g": {"S": "plain"}, f"{NUL}": {"S": NUL}} + t1 = {"pk": {"S": f"tx{c}"}, "sk": {"S": f"{c}{c}"}, "g": {"S": "plain"}, "v": {"S": NUL}} + dynamodb_client.batch_write_item(RequestItems={table: [{"PutRequest": {"Item": b1}}]}) dynamodb_client.transact_write_items( - TransactItems=[{"Put": {"TableName": nul_table, "Item": t1}}] + TransactItems=[{"Put": {"TableName": table, "Item": t1}}] ) got = dynamodb_client.batch_get_item( RequestItems={ - nul_table: { + table: { "Keys": [{"pk": b1["pk"], "sk": b1["sk"]}, {"pk": t1["pk"], "sk": t1["sk"]}], "ConsistentRead": True, } } - )["Responses"][nul_table] + )["Responses"][table] assert sorted(got, key=lambda i: i["pk"]["S"]) == sorted([b1, t1], key=lambda i: i["pk"]["S"]) tg = dynamodb_client.transact_get_items( TransactItems=[ - {"Get": {"TableName": nul_table, "Key": {"pk": b1["pk"], "sk": b1["sk"]}}}, - {"Get": {"TableName": nul_table, "Key": {"pk": t1["pk"], "sk": t1["sk"]}}}, + {"Get": {"TableName": table, "Key": {"pk": b1["pk"], "sk": b1["sk"]}}}, + {"Get": {"TableName": table, "Key": {"pk": t1["pk"], "sk": t1["sk"]}}}, ] )["Responses"] assert [r["Item"] for r in tg] == [b1, t1] dynamodb_client.batch_write_item( RequestItems={ - nul_table: [ + table: [ {"DeleteRequest": {"Key": {"pk": b1["pk"], "sk": b1["sk"]}}}, {"DeleteRequest": {"Key": {"pk": t1["pk"], "sk": t1["sk"]}}}, ] @@ -296,15 +358,164 @@ def test_batch_and_transact_writes_and_reads(self, dynamodb_client, nul_table): ) def test_scan_counts_every_item(self, dynamodb_client, nul_table): - resp = dynamodb_client.scan(TableName=nul_table, Select="COUNT", ConsistentRead=True) - assert resp["Count"] == len(SORT_KEYS) + 2 + table, count = nul_table + resp = dynamodb_client.scan(TableName=table, Select="COUNT", ConsistentRead=True) + assert resp["Count"] == count + + @pytest.mark.parametrize("c", KEY_CHARS) + def test_delete_item_on_the_key(self, dynamodb_client, nul_table, c): + table, _ = nul_table + key = {"pk": {"S": f"del{c}"}, "sk": {"S": c}} + dynamodb_client.put_item(TableName=table, Item={**key, "v": {"S": NUL}}) + resp = dynamodb_client.delete_item(TableName=table, Key=key, ReturnValues="ALL_OLD") + assert resp["Attributes"] == {**key, "v": {"S": NUL}} + assert "Item" not in dynamodb_client.get_item(TableName=table, Key=key, ConsistentRead=True) + + +def _long_key() -> str: + """2046 bytes: 1364 random letters with U+0001 after every second one, 682 + in all. The service allows a partition key value of 2048 bytes. Random + letters keep PostgreSQL from compressing the key below its btree entry + limit of 2704 bytes; a repeated pattern would compress.""" + rng = random.Random(368) + key = "".join( + rng.choice("abcdefghijklmnopqrstuvwxyz") + ("" if i % 2 == 0 else SOH) for i in range(1364) + ) + assert (len(key.encode()), key.count(SOH)) == (2046, 682) + return key + + +def test_a_long_key_holding_u0001_is_stored(dynamodb_client): + """A 2046-byte partition key with 682 U+0001, and a GSI partition key of + the same shape, are stored and read back. Each U+0001 stays one byte in + the key, as every earlier release stored it.""" + key = _long_key() + with scoped_table(dynamodb_client, **TABLE_SCHEMA) as table: + base = {"pk": {"S": key}, "sk": {"S": "s"}} + indexed = {"pk": {"S": "short-key1"}, "sk": {"S": "s"}, "g": {"S": key}} + for item in (base, indexed): + dynamodb_client.put_item(TableName=table, Item=item) + got = dynamodb_client.get_item(TableName=table, Key=base, ConsistentRead=True) + assert got["Item"] == base - def test_delete_item_on_a_nul_key(self, dynamodb_client, nul_table): - key = {"pk": {"S": f"del{NUL}"}, "sk": {"S": NUL}} - dynamodb_client.put_item(TableName=nul_table, Item={**key, "g": {"S": "plain"}}) - resp = dynamodb_client.delete_item(TableName=nul_table, Key=key, ReturnValues="ALL_OLD") - assert resp["Attributes"] == {**key, "g": {"S": "plain"}} - assert "Item" not in dynamodb_client.get_item(TableName=nul_table, Key=key, ConsistentRead=True) + def walk(): + return dynamodb_client.query( + TableName=table, + IndexName="gsi1", + KeyConditionExpression="g = :g", + ExpressionAttributeValues={":g": {"S": key}}, + )["Items"] + + assert wait_for_gsi_items(walk, 1) == [indexed] + + +# Requests whose key value holds NUL, each answered by the PostgreSQL backend +# with NUL_IN_KEY, and none of which stores an item. +NUL_KEY = {"pk": {"S": f"a{NUL}"}, "sk": {"S": "s"}} +REFUSED = [ + ("PutItem, partition key", "put_item", lambda t: dict(TableName=t, Item=NUL_KEY)), + ( + "PutItem, sort key", + "put_item", + lambda t: dict(TableName=t, Item={"pk": {"S": "p"}, "sk": {"S": NUL}}), + ), + ( + "PutItem, GSI key", + "put_item", + lambda t: dict(TableName=t, Item={"pk": {"S": "p"}, "sk": {"S": "s"}, "g": {"S": f"g{NUL}"}}), + ), + ( + "UpdateItem, a GSI key the update sets", + "update_item", + lambda t: dict( + TableName=t, + Key={"pk": {"S": "p"}, "sk": {"S": "s"}}, + UpdateExpression="SET g = :g", + ExpressionAttributeValues={":g": {"S": f"g{NUL}"}}, + ), + ), + ("GetItem", "get_item", lambda t: dict(TableName=t, Key=NUL_KEY)), + ("DeleteItem", "delete_item", lambda t: dict(TableName=t, Key=NUL_KEY)), + ( + "Query, partition key", + "query", + lambda t: dict( + TableName=t, + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": NUL_KEY["pk"]}, + ), + ), + ( + "Query, sort key bound", + "query", + lambda t: dict( + TableName=t, + KeyConditionExpression="pk = :p AND sk BETWEEN :lo AND :hi", + ExpressionAttributeValues={":p": {"S": "p"}, ":lo": {"S": NUL}, ":hi": {"S": "z"}}, + ), + ), + ( + "Query, GSI key", + "query", + lambda t: dict( + TableName=t, + IndexName="gsi1", + KeyConditionExpression="g = :g", + ExpressionAttributeValues={":g": {"S": f"g{NUL}"}}, + ), + ), + ( + "BatchWriteItem", + "batch_write_item", + lambda t: dict(RequestItems={t: [{"PutRequest": {"Item": NUL_KEY}}]}), + ), + ("BatchGetItem", "batch_get_item", lambda t: dict(RequestItems={t: {"Keys": [NUL_KEY]}})), + ( + "TransactWriteItems", + "transact_write_items", + lambda t: dict(TransactItems=[{"Put": {"TableName": t, "Item": NUL_KEY}}]), + ), + ( + "TransactGetItems", + "transact_get_items", + lambda t: dict(TransactItems=[{"Get": {"TableName": t, "Key": NUL_KEY}}]), + ), +] + + +@pytest.mark.skipif(not ON_POSTGRESQL, reason="the refusal is the PostgreSQL backend's") +def test_postgresql_refuses_nul_in_a_key_value(dynamodb_client): + with scoped_table(dynamodb_client, **TABLE_SCHEMA) as table: + for label, operation, request in REFUSED: + with pytest.raises(ClientError) as exc: + getattr(dynamodb_client, operation)(**request(table)) + assert _error(exc) == (400, "ValidationException", NUL_IN_KEY), label + # An Update member that computes such a GSI key cancels the + # transaction with the same message. + with pytest.raises(ClientError) as exc: + dynamodb_client.transact_write_items( + TransactItems=[ + { + "Update": { + "TableName": table, + "Key": {"pk": {"S": "p"}, "sk": {"S": "s"}}, + "UpdateExpression": "SET g = :g", + "ExpressionAttributeValues": {":g": {"S": f"g{NUL}"}}, + } + } + ] + ) + assert _error(exc) == ( + 400, + "TransactionCanceledException", + "Transaction cancelled, please refer cancellation reasons for specific reasons " + "[ValidationError]", + ) + assert exc.value.response["CancellationReasons"] == [ + {"Code": "ValidationError", "Message": NUL_IN_KEY} + ] + resp = dynamodb_client.scan(TableName=table, Select="COUNT", ConsistentRead=True) + assert resp["Count"] == 0, "a refused write stored an item" @pytest.fixture(scope="module") @@ -328,10 +539,10 @@ def nul_streams_client(endpoint_url): return boto3.client(**kwargs) -def test_stream_records_carry_nul_keys_names_and_values(dynamodb_client, nul_streams_client): - """INSERT, MODIFY, and REMOVE records for an item whose key, attribute - names, map keys, and values hold U+0000 and U+0001 come back byte-identical - in Keys, NewImage, and OldImage.""" +def test_stream_records_carry_nul_names_and_values(dynamodb_client, nul_streams_client): + """INSERT, MODIFY, and REMOVE records for an item whose key holds U+0001 + and whose attribute names, map keys, and values hold U+0000 and U+0001 + come back byte-identical in Keys, NewImage, and OldImage.""" from test_streams import _drain_all_shards with scoped_table( @@ -347,18 +558,17 @@ def test_stream_records_carry_nul_keys_names_and_values(dynamodb_client, nul_str StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"}, ) as name: stream_arn = dynamodb_client.describe_table(TableName=name)["Table"]["LatestStreamArn"] - key = {"pk": {"S": PK}, "sk": {"S": NUL}} first = {**RICH_ITEM} dynamodb_client.put_item(TableName=name, Item=first) second = dynamodb_client.update_item( TableName=name, - Key=key, + Key=RICH_KEY, UpdateExpression="SET #a = :v REMOVE #n", ExpressionAttributeNames={"#a": f"u{NUL}", "#n": f"n{NUL}n"}, ExpressionAttributeValues={":v": {"S": f"{SOH}{NUL}"}}, ReturnValues="ALL_NEW", )["Attributes"] - dynamodb_client.delete_item(TableName=name, Key=key) + dynamodb_client.delete_item(TableName=name, Key=RICH_KEY) deadline = time.monotonic() + 30 records: list[dict] = [] @@ -369,7 +579,7 @@ def test_stream_records_carry_nul_keys_names_and_values(dynamodb_client, nul_str time.sleep(0.5) assert [r["eventName"] for r in records] == ["INSERT", "MODIFY", "REMOVE"] for r in records: - assert r["dynamodb"]["Keys"] == key + assert r["dynamodb"]["Keys"] == RICH_KEY assert records[0]["dynamodb"]["NewImage"] == first assert "OldImage" not in records[0]["dynamodb"] assert records[1]["dynamodb"]["OldImage"] == first From 3be8ff525bf19b94e46aaf853aeb124da49bf948 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:44:52 +0000 Subject: [PATCH 25/30] fix(storage-mongodb): decode the field names of marked documents only item_data_to_json decoded the field names of every document. Names that main wrote with U+0001 followed by U+0001 or U+0002 read back changed. c\x01 and c\x01\x02 became one attribute, and the next UpdateItem stored the item without the other. A write now escapes the field names of a document only when one of them holds U+0000, which main could not store. It marks that document with the top-level field names_escaped. The decoder reads only a marked document, so every document that main wrote reads back as written. Stream records follow the same rule, and GetRecords carries the mark through its aggregation. The native update paths do not read the document. A value whose field names hold U+0000 or U+0001 therefore takes the session path, as such an attribute name already did. A live test stores a document as main wrote it, with c\x01 and c\x01\x02. GetItem returns both, and an UpdateItem on the session path and one on the native path keep both. A unit test reads such names and a map key back as written. --- crates/storage-mongodb/src/backup_engine.rs | 11 +- crates/storage-mongodb/src/data/mod.rs | 179 +++++++++++++----- crates/storage-mongodb/src/data_engine.rs | 75 ++++++-- .../src/data_engine_live_tests.rs | 3 + .../data_engine_live_tests_control_names.rs | 82 ++++++++ .../src/data_engine_update_create.rs | 16 +- crates/storage-mongodb/src/migrations/mod.rs | 6 +- crates/storage-mongodb/src/pushdown.rs | 11 +- crates/storage-mongodb/src/stream_engine.rs | 3 +- .../storage-mongodb/src/stream_record_docs.rs | 5 +- 10 files changed, 302 insertions(+), 89 deletions(-) create mode 100644 crates/storage-mongodb/src/data_engine_live_tests_control_names.rs diff --git a/crates/storage-mongodb/src/backup_engine.rs b/crates/storage-mongodb/src/backup_engine.rs index 22edadf80..3d9bb67ab 100644 --- a/crates/storage-mongodb/src/backup_engine.rs +++ b/crates/storage-mongodb/src/backup_engine.rs @@ -1986,12 +1986,11 @@ impl LegacyBackupReader for MongoEngine { /// it), then a cursor over its `_backup_` collection in /// batches of [`paging::DEFAULT_FETCH_BATCH`] documents. The collection /// is a copy of the table's documents in their stored form, with the - /// field names as the release that took it stored them, so each is - /// decoded as the data path decodes a stored document - /// ([`document_to_item`]). A backup taken before the escape holds raw - /// names, which read back as the data path reads that release's - /// documents (see `item_data_to_json`). The collection is immutable - /// while the backup is AVAILABLE, so no snapshot is held; a + /// field names and the `names_escaped` mark as the release that took it + /// stored them, so each is decoded as the data path decodes a stored + /// document ([`document_to_item`]). A backup taken before the escape + /// holds no mark, and its names read back as written. The collection + /// is immutable while the backup is AVAILABLE, so no snapshot is held; a /// DeleteBackup's drop ends the cursor with an error. fn items( &self, diff --git a/crates/storage-mongodb/src/data/mod.rs b/crates/storage-mongodb/src/data/mod.rs index 4ee910a3b..1e9ba94fe 100644 --- a/crates/storage-mongodb/src/data/mod.rs +++ b/crates/storage-mongodb/src/data/mod.rs @@ -16,7 +16,8 @@ use extenddb_core::types::{ }; use extenddb_storage::error::StorageError; use extenddb_storage::util::{ - composite_pk_to_text, encode_netstring_composite, escape_json_keys, sk_info, unescape_json_keys, + composite_pk_to_text, encode_netstring_composite, escape_json_keys, needs_escape, sk_info, + unescape_json_keys, }; /// Returns the `MongoDB` collection name for a `DynamoDB` table. @@ -36,51 +37,93 @@ pub fn composite_id(pk_text: &str, sk_text: &str) -> String { encode_netstring_composite(&[pk_text.to_owned(), sk_text.to_owned()]) } -/// Convert an item (base item or projected index item) to the BSON stored -/// under `item_data`. +/// Top-level field of a document whose `item_data` field names are stored +/// through the escape, set to `true`; a document without it holds its names +/// as written. +pub(crate) const NAMES_ESCAPED: &str = "names_escaped"; + +/// Whether an object key of the JSON tree `v`, at any depth, satisfies `test`. +fn any_name(v: &serde_json::Value, test: &dyn Fn(&str) -> bool) -> bool { + match v { + serde_json::Value::Object(map) => map.iter().any(|(k, val)| test(k) || any_name(val, test)), + serde_json::Value::Array(items) => items.iter().any(|item| any_name(item, test)), + _ => false, + } +} + +/// Whether a field name of the JSON tree `v`, at any depth, holds U+0000 or +/// U+0001, the characters the escape changes. A native update path refuses +/// such a value: it cannot see whether the stored document is marked, so it +/// cannot tell which form its names take there. +pub(crate) fn names_need_escape(v: &serde_json::Value) -> bool { + any_name(v, &needs_escape) +} + +/// Convert the JSON form of an item, or of a record that carries items, to +/// the BSON stored for it, and say whether its field names were escaped. /// /// BSON field names are C strings and cannot contain U+0000, while `DynamoDB` -/// accepts it in attribute names and map keys. Every object key in the item's -/// JSON form is run through the shared order-preserving escape (U+0000 and -/// U+0001 become two-character sequences, see -/// `extenddb_storage::util::escape_control`) before the BSON conversion, so -/// the stored document never carries a NUL field name. String values are left -/// alone; BSON strings are length-prefixed and hold U+0000 verbatim. +/// accepts it in attribute names and map keys. When a field name at any depth +/// holds U+0000, every field name is run through the shared escape (U+0000 +/// and U+0001 become two-character sequences, see +/// `extenddb_storage::util::escape_control`) and the caller marks the +/// document with [`NAMES_ESCAPED`]. Any other tree is stored as it is, as a +/// release before the escape stored it, so a name that holds U+0001 alone +/// keeps its text. String values are never escaped; BSON strings are +/// length-prefixed and hold U+0000 verbatim. /// -/// Every conversion of an item to `item_data` BSON must go through this -/// function or [`json_to_item_data`]; a direct `bson::to_bson` on item JSON -/// fails in the driver at write time when a name contains U+0000. -/// [`item_data_to_json`] reverses the escape on read. -pub(crate) fn item_to_item_data(item: &Item) -> Result { - let item_json = - serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; - json_to_item_data(item_json) +/// Every conversion of an item to `item_data` BSON goes through this +/// function; a direct `bson::to_bson` on item JSON fails in the driver at +/// write time when a name contains U+0000. [`item_data_to_json`] reverses the +/// escape for a marked document. +pub(crate) fn json_to_item_data( + json: serde_json::Value, +) -> Result<(bson::Bson, bool), StorageError> { + let escaped = any_name(&json, &|name| name.contains('\0')); + let json = if escaped { + escape_json_keys(json) + } else { + json + }; + let bson = bson::to_bson(&json).map_err(|e| StorageError::Internal(e.to_string()))?; + Ok((bson, escaped)) +} + +/// Insert the `item_data` of `item` into `doc`, and [`NAMES_ESCAPED`] when its +/// field names were escaped ([`json_to_item_data`]). +fn insert_item_data(doc: &mut Document, item: &Item) -> Result<(), StorageError> { + let json = serde_json::to_value(item).map_err(|e| StorageError::Internal(e.to_string()))?; + let (bson, escaped) = json_to_item_data(json)?; + doc.insert("item_data", bson); + if escaped { + doc.insert(NAMES_ESCAPED, true); + } + Ok(()) } -/// JSON-tree variant of [`item_to_item_data`], for payloads that carry items -/// nested inside another structure (stream records with key/image maps). -pub(crate) fn json_to_item_data(json: serde_json::Value) -> Result { - let escaped = escape_json_keys(json); - bson::to_bson(&escaped).map_err(|e| StorageError::Internal(e.to_string())) +/// Whether `doc` is marked with [`NAMES_ESCAPED`]. +pub(crate) fn names_escaped(doc: &Document) -> bool { + doc.get_bool(NAMES_ESCAPED).unwrap_or(false) } -/// Reverse of [`json_to_item_data`]: BSON read from storage back to JSON with -/// the object-key escape undone. +/// Reverse of [`json_to_item_data`]: BSON read from storage back to JSON, +/// with the field-name escape undone when the document is marked +/// (`escaped`). /// -/// Documents written by a release before the escape hold their field names -/// raw, and there is no migration and no startup check for them: unlike -/// `PostgreSQL`, nothing here can fail to store (BSON strings already hold -/// U+0000, and a raw field name reads back through the driver), so the only -/// effect is on a legacy name that happens to contain U+0001 immediately -/// followed by U+0001 or U+0002, which this decoder reads as U+0000 or -/// U+0001. A lone U+0001 and every string value are unchanged. That exposure -/// was judged too narrow to make every `MongoDB` upgrade acknowledge a gate -/// with nothing to rewrite; the upgrade manual's "Data Migrations" section -/// states the limitation for operators. -pub(crate) fn item_data_to_json(value: &bson::Bson) -> Result { +/// A document without the mark holds its names as they were written: every +/// document a release before the escape wrote, and every document of this +/// release whose names hold no U+0000. Its names read back unchanged. +pub(crate) fn item_data_to_json( + value: &bson::Bson, + escaped: bool, +) -> Result { let json: serde_json::Value = bson::from_bson(value.clone()) .map_err(|e| StorageError::Internal(format!("BSON to JSON conversion error: {e}")))?; - Ok(unescape_json_keys(json)) + Ok(if escaped { + unescape_json_keys(json) + } else { + json + }) } /// Convert a `DynamoDB` Item to a `MongoDB` BSON document for storage. @@ -93,10 +136,6 @@ pub fn item_to_document( ) -> Result { let pk_text = composite_pk_to_text(item, key_schema)?; - // Serialize the full item as item_data (object keys escaped, see - // item_to_item_data). - let item_bson = item_to_item_data(item)?; - let mut doc = Document::new(); // Build the _id field @@ -117,7 +156,9 @@ pub fn item_to_document( doc.insert("pk", pk_text); } - doc.insert("item_data", item_bson); + // The full item as item_data, its names escaped and the document marked + // when one holds U+0000 (see json_to_item_data). + insert_item_data(&mut doc, item)?; Ok(doc) } @@ -242,8 +283,7 @@ pub fn index_document( insert_typed_sk(&mut doc, &field, sk_type, sk_value)?; } - let item_bson = item_to_item_data(projected)?; - doc.insert("item_data", item_bson); + insert_item_data(&mut doc, projected)?; Ok(doc) } @@ -302,7 +342,7 @@ pub fn document_to_item(doc: &Document) -> Result { .get("item_data") .ok_or_else(|| StorageError::Internal("Document missing item_data field".to_string()))?; - let json_value = item_data_to_json(item_data)?; + let json_value = item_data_to_json(item_data, names_escaped(doc))?; let item: Item = serde_json::from_value(json_value) .map_err(|e| StorageError::Internal(format!("JSON to Item conversion error: {e}")))?; @@ -533,11 +573,61 @@ mod tests { let doc = item_to_document(&item, &schema, &attrs).unwrap(); assert_no_nul_field_names(&bson::Bson::Document(doc.clone())); + assert_eq!(doc.get_bool(NAMES_ESCAPED), Ok(true)); let back = document_to_item(&doc).unwrap(); assert_eq!(back, item); } + /// A document without the mark holds its names as written, which is how + /// every release before the escape stored them: names that hold U+0001 + /// followed by U+0001 or U+0002 read back unchanged, and two of them that + /// would decode to one name stay two. An item whose names hold U+0001 but + /// no U+0000 is stored the same way. + #[test] + fn a_document_without_the_mark_reads_back_its_names_as_written() { + let (schema, attrs) = schema_pk_str_sk_num(); + let names = ["pk", "sk", "c\u{1}", "c\u{1}\u{2}", "a\u{1}\u{2}"]; + let stored = doc! { + "_id": "2:p\u{1},1:1,", + "pk": "p\u{1}", + "item_data": { + "pk": {"S": "p\u{1}"}, + "sk": {"N": "1"}, + "c\u{1}": {"S": "one"}, + "c\u{1}\u{2}": {"S": "two"}, + "a\u{1}\u{2}": {"M": {"k\u{1}\u{1}": {"S": "v"}}}, + }, + }; + let item = document_to_item(&stored).unwrap(); + assert_eq!(item.keys().map(String::as_str).collect::>(), { + let mut sorted = names.to_vec(); + sorted.sort_unstable(); + sorted + }); + assert_eq!(item["c\u{1}"], AttributeValue::S("one".to_owned())); + assert_eq!(item["c\u{1}\u{2}"], AttributeValue::S("two".to_owned())); + let AttributeValue::M(map) = &item["a\u{1}\u{2}"] else { + panic!("a map"); + }; + assert_eq!(map.keys().collect::>(), ["k\u{1}\u{1}"]); + + let rewritten = item_to_document(&item, &schema, &attrs).unwrap(); + assert_eq!(rewritten.get(NAMES_ESCAPED), None); + let mut stored_names: Vec<&str> = rewritten + .get_document("item_data") + .unwrap() + .keys() + .map(String::as_str) + .collect(); + stored_names.sort_unstable(); + assert_eq!( + stored_names, + item.keys().map(String::as_str).collect::>() + ); + assert_eq!(document_to_item(&rewritten).unwrap(), item); + } + #[test] fn plain_item_document_stores_raw_field_names() { use std::collections::BTreeMap; @@ -552,6 +642,7 @@ mod tests { item.insert("attr".to_owned(), AttributeValue::M(inner)); let doc = item_to_document(&item, &schema, &attrs).unwrap(); + assert_eq!(doc.get(NAMES_ESCAPED), None); let item_data = doc.get_document("item_data").unwrap(); let names: Vec<&str> = item_data.keys().map(String::as_str).collect(); assert_eq!(names, vec!["attr", "pk", "sk"]); diff --git a/crates/storage-mongodb/src/data_engine.rs b/crates/storage-mongodb/src/data_engine.rs index b88e63b7f..d55eaaa7c 100644 --- a/crates/storage-mongodb/src/data_engine.rs +++ b/crates/storage-mongodb/src/data_engine.rs @@ -28,8 +28,9 @@ use extenddb_storage::{ use crate::MongoEngine; use crate::condition::condition_to_filter; use crate::data::{ - binary_sk_to_hex, composite_id, data_collection_name, document_to_item, index_document, - index_entry_filter, item_to_document, json_to_item_data, pk_filter, sk_field_name, sk_suffix, + NAMES_ESCAPED, binary_sk_to_hex, composite_id, data_collection_name, document_to_item, + index_document, index_entry_filter, item_to_document, json_to_item_data, names_need_escape, + pk_filter, sk_field_name, sk_suffix, }; use crate::pushdown::{Pushable, is_pushable}; @@ -37,8 +38,9 @@ use extenddb_core::types::{Projection, ProjectionType}; /// Resolve a single-component update path for the native MongoDB fast path. /// Literal attribute names containing dots or beginning with `$` cannot be -/// represented safely by MongoDB's ordinary update paths, and names -/// containing U+0000 or U+0001 differ from the stored (escaped) field name, +/// represented safely by MongoDB's ordinary update paths, and a name +/// containing U+0000 or U+0001 is stored escaped in a document marked +/// `names_escaped` and as it is in another, which this path does not read, /// so they must use the Rust/session path. fn native_attribute_name(path: &[PathElement], maps: &ExpressionMaps) -> Option { if path.len() != 1 { @@ -1831,11 +1833,16 @@ impl MongoEngine { _ => return None, // complex expressions (if_not_exists, list_append, arithmetic) }; let field = format!("item_data.{attr_name}"); - // The value lands inside item_data, so its nested map - // keys must be in stored (escaped) form, matching what - // item_to_document writes. + // The value lands inside item_data. A nested field name + // holding U+0000 or U+0001 is stored escaped in a marked + // document and as it is in another, and this path does + // not read the document, so such a value takes the slow + // path; any other value is stored the same in both. let val_json = serde_json::to_value(val).ok()?; - let val_bson = json_to_item_data(val_json).ok()?; + if names_need_escape(&val_json) { + return None; + } + let val_bson = bson::to_bson(&val_json).ok()?; set_doc.insert(field, val_bson); } UpdateAction::Remove { path } => { @@ -2256,8 +2263,8 @@ impl MongoEngine { serde_json::to_value(&record).map_err(|e| StorageError::Internal(e.to_string()))?; // The record's key and image maps carry attribute names as object // keys, which become BSON field names; convert through the same - // escaping helper as item_data. - let record_bson = json_to_item_data(record_json)?; + // helper as item_data, and mark the record when it escaped them. + let (record_bson, escaped) = json_to_item_data(record_json)?; // key_info already carries table_id — no need to re-read the catalog // just to resolve it, and re-reading inside the session against the @@ -2265,16 +2272,20 @@ impl MongoEngine { // needlessly. let table_id = &key_info.table_id; + let mut record_doc = doc! { + "sequence_number": &record.dynamodb.sequence_number, + "shard_id": &shard_id, + "table_id": table_id, + "event_name": crate::stream_engine::event_name_ddb_str(record.event_name), + "record_data": record_bson, + "created_at": created_at, + }; + if escaped { + record_doc.insert(NAMES_ESCAPED, true); + } let records_coll = self.data_db.collection::("stream_records"); records_coll - .insert_one(doc! { - "sequence_number": &record.dynamodb.sequence_number, - "shard_id": &shard_id, - "table_id": table_id, - "event_name": crate::stream_engine::event_name_ddb_str(record.event_name), - "record_data": record_bson, - "created_at": created_at, - }) + .insert_one(record_doc) .session(&mut *session) .await .map_err(crate::write_conflict::transaction_error)?; @@ -4745,9 +4756,10 @@ transaction_read_concern = "majority""#, #[test] fn native_update_rejects_control_character_literal_attribute_names() { - // Stored field names carry the escaped form of U+0000 and U+0001, - // so a native update path built from the raw name would target a - // different field; these names must use the Rust/session path. + // A marked document stores the escaped form of U+0000 and U+0001 + // in field names, so a native update path built from the raw name + // would target a different field there; these names must use the + // Rust/session path. for name in ["a\u{0}b", "a\u{1}b"] { let mut names = std::collections::HashMap::new(); names.insert("name".to_owned(), name.to_owned()); @@ -4758,6 +4770,27 @@ transaction_read_concern = "majority""#, } } + #[test] + fn native_update_leaves_a_value_with_control_character_field_names() { + // A marked document stores such a nested name escaped and another + // document stores it as it is, and the native path reads neither, so + // the update takes the session path. A plain nested name stays native. + for (key, native) in [("k\u{0}", false), ("k\u{1}", false), ("k\u{2}", true)] { + let inner = + std::collections::BTreeMap::from([(key.to_owned(), AttributeValue::S("v".into()))]); + let values = + std::collections::HashMap::from([("m".to_owned(), AttributeValue::M(inner))]); + let maps = ExpressionMaps::new(std::collections::HashMap::new(), values); + let tokens = expression::tokenize("SET a = :m").unwrap(); + let actions = expression::parse_update(&tokens).unwrap(); + assert_eq!( + MongoEngine::try_build_native_update(&actions, &maps).is_some(), + native, + "{key:?}" + ); + } + } + #[test] fn native_update_keeps_simple_attribute_names_on_fast_path() { let maps = ExpressionMaps::new( diff --git a/crates/storage-mongodb/src/data_engine_live_tests.rs b/crates/storage-mongodb/src/data_engine_live_tests.rs index 4ea858a58..ab1988f9e 100644 --- a/crates/storage-mongodb/src/data_engine_live_tests.rs +++ b/crates/storage-mongodb/src/data_engine_live_tests.rs @@ -26,6 +26,9 @@ use crate::data::{data_collection_name, document_to_item, item_to_document, pk_f #[path = "data_engine_live_tests_create.rs"] mod create; +#[path = "data_engine_live_tests_control_names.rs"] +mod control_names; + #[path = "data_engine_live_tests_key_names.rs"] mod key_names; diff --git a/crates/storage-mongodb/src/data_engine_live_tests_control_names.rs b/crates/storage-mongodb/src/data_engine_live_tests_control_names.rs new file mode 100644 index 000000000..de381f1f9 --- /dev/null +++ b/crates/storage-mongodb/src/data_engine_live_tests_control_names.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Live MongoDB test for the field names of a document that a release before +//! the escape of U+0000 wrote. Such a document carries no `names_escaped` +//! mark and holds its names as written, so they read back unchanged: `c\x01` +//! and `c\x01\x02` stay two attributes, and an UpdateItem keeps both, on the +//! session path, which reads the item and writes it back, and on the native +//! path. +//! +//! The test reads the replica set URI from `EXTENDDB_TEST_MONGODB_URI` and is +//! `#[ignore]`d, like the tests in the parent module. + +use bson::{Document, doc}; +use extenddb_core::expression::{Expr, UpdateAction}; + +use super::{finish, item_key, maps, path, s, scratch_engine, stored, table, with}; +use crate::data::{NAMES_ESCAPED, data_collection_name, document_to_item}; + +#[tokio::test] +#[ignore = "needs a MongoDB replica set in EXTENDDB_TEST_MONGODB_URI"] +async fn live_names_an_earlier_release_stored_read_back_and_survive_an_update() { + let engine = scratch_engine().await; + let key_info = table(&engine, "legacy-names", false); + let key = item_key(false); + engine + .data_db + .collection::(&data_collection_name(&key_info.table_id)) + .insert_one(doc! { + "_id": "u1", + "pk": "u1", + "item_data": { + "pk": { "S": "u1" }, + "c\u{1}": { "S": "one" }, + "c\u{1}\u{2}": { "S": "two" }, + }, + }) + .await + .expect("store the document as an earlier release wrote it"); + let written = with( + with(key.clone(), "c\u{1}", s("one")), + "c\u{1}\u{2}", + s("two"), + ); + assert_eq!( + engine.get_item_impl(&key_info, &key).await.expect("get"), + Some(written.clone()) + ); + + // ALL_OLD takes the session path; the other update takes the native one. + let mut want = written; + for (name, return_old) in [("z", true), ("y", false)] { + let actions = vec![UpdateAction::Set { + path: path(name), + value: Expr::Placeholder(":v".to_owned()), + }]; + let (old, _) = engine + .update_item_impl( + &key_info, + &key, + &actions, + return_old, + false, + None, + &maps(s(name)), + None, + ) + .await + .unwrap_or_else(|e| panic!("update {name}: {e:?}")); + if return_old { + assert_eq!(old.as_ref(), Some(&want), "the old image of {name}"); + } + want = with(want, name, s(name)); + let doc = stored(&engine, &key_info, &key).await; + assert_eq!(doc.get(NAMES_ESCAPED), None, "after {name}"); + assert_eq!(document_to_item(&doc).expect("item"), want, "after {name}"); + } + assert_eq!( + engine.get_item_impl(&key_info, &key).await.expect("get"), + Some(want) + ); + finish(engine).await; +} diff --git a/crates/storage-mongodb/src/data_engine_update_create.rs b/crates/storage-mongodb/src/data_engine_update_create.rs index f8ca78d86..f6df0c8fb 100644 --- a/crates/storage-mongodb/src/data_engine_update_create.rs +++ b/crates/storage-mongodb/src/data_engine_update_create.rs @@ -30,9 +30,9 @@ //! `item_data: { a: { b: ... } }`, where PutItem stores the field `"a.b"`, //! and the same path conflicts with an update of an attribute named `a`. //! A key attribute name containing U+0000 or U+0001 has the same problem in -//! another form: `item_to_document` stores it escaped -//! (`extenddb_storage::util::control_chars`), and the path would name the -//! raw text. A table with a key attribute name that +//! another form: `item_to_document` stores it escaped in a document marked +//! `names_escaped` (`crate::data::json_to_item_data`), and the path would +//! name the raw text. A table with a key attribute name that //! `key_names_are_plain_paths` rejects therefore does not take the native //! upsert; it takes the session path, which writes the document //! `item_to_document` builds. @@ -50,8 +50,9 @@ use crate::data::key_fields::insert_only_key_fields; /// Whether `name` is usable as one field name in a MongoDB update path. A dot /// would split it into nested fields and a leading `$` would read as an /// operator or positional path. A name containing U+0000 or U+0001 is stored -/// in escaped form, so a path built from the raw name would address a -/// different field (and BSON refuses U+0000 in a field name). +/// escaped in a document marked `names_escaped`, so a path built from the raw +/// name would address a different field there (and BSON refuses U+0000 in a +/// field name). pub(super) fn is_plain_path_name(name: &str) -> bool { !name.contains('.') && !name.starts_with('$') && !needs_escape(name) } @@ -183,8 +184,9 @@ mod tests { #[test] fn a_key_name_with_u0000_or_u0001_leaves_the_native_upsert() { - // item_to_document stores these names escaped, so the - // `item_data.` path of the upsert would name another field. + // item_to_document stores these names escaped in a marked + // document, so the `item_data.` path of the upsert would name + // another field there. assert!(key_names_are_plain_paths(&schema(&[( "a\u{2}b", KeyType::Hash diff --git a/crates/storage-mongodb/src/migrations/mod.rs b/crates/storage-mongodb/src/migrations/mod.rs index a8c94ec09..e79674e37 100644 --- a/crates/storage-mongodb/src/migrations/mod.rs +++ b/crates/storage-mongodb/src/migrations/mod.rs @@ -327,9 +327,9 @@ pub fn migration(id: MigrationId) -> Migration { )], }, MigrationId::EscapeControlChars => Migration::NotApplicable( - "string values already held U+0000; field names an earlier release stored are read \ - back as written unless they hold U+0001 followed by U+0001 or U+0002, and are not \ - rewritten (see the upgrade manual)", + "string values already held U+0000, and a document's field names are escaped only \ + when one holds U+0000, which no earlier release could store, so every document an \ + earlier release wrote reads back as written", ), } } diff --git a/crates/storage-mongodb/src/pushdown.rs b/crates/storage-mongodb/src/pushdown.rs index 05f96dac9..57158d6b3 100644 --- a/crates/storage-mongodb/src/pushdown.rs +++ b/crates/storage-mongodb/src/pushdown.rs @@ -78,9 +78,9 @@ pub fn is_pushable(expr: &Expr, maps: &ExpressionMaps) -> Pushable { /// cannot safely be emitted as a MongoDB field path. A dot would mean nested /// document traversal in MongoDB, while a leading `$` would be interpreted as /// an operator or otherwise have special meaning in a MongoDB path. A name -/// containing U+0000 or U+0001 is stored under its escaped form (see -/// `extenddb_storage::util::escape_control`), so the raw name would not match -/// the stored field. +/// containing U+0000 or U+0001 is stored escaped in a document marked +/// `names_escaped` (see `crate::data::json_to_item_data`) and as it is in +/// another, so one field path cannot match both. fn unsafe_attribute_reason(expr: &Expr, maps: &ExpressionMaps) -> Option<&'static str> { match expr { Expr::Path(elements) => elements.iter().find_map(|element| match element { @@ -402,8 +402,9 @@ mod tests { #[test] fn nul_attribute_name_is_not_pushable() { - // The stored field name is the escaped form, so a raw path on a - // name containing U+0000 would never match; must fall back. + // The stored field name is the escaped form in a marked document, + // so a raw path on a name containing U+0000 would not match; must + // fall back. let expr = Expr::Compare { left: Box::new(path("a\u{0}b")), op: CompareOp::Eq, diff --git a/crates/storage-mongodb/src/stream_engine.rs b/crates/storage-mongodb/src/stream_engine.rs index 7309a5c9d..65d3f8c67 100644 --- a/crates/storage-mongodb/src/stream_engine.rs +++ b/crates/storage-mongodb/src/stream_engine.rs @@ -287,7 +287,7 @@ impl StreamEngine for MongoEngine { { "$match": { "$expr": record_match } }, { "$sort": { "sequence_number": 1 } }, { "$limit": limit }, - { "$project": { "_id": 0, "record_data": 1 } }, + { "$project": { "_id": 0, "record_data": 1, "names_escaped": 1 } }, ], "as": "records", } }, @@ -297,6 +297,7 @@ impl StreamEngine for MongoEngine { "shard_id": 1, "has_record": { "$ne": [{ "$type": "$records" }, "missing"] }, "record_data": "$records.record_data", + "names_escaped": "$records.names_escaped", } }, ]; let cursor = self diff --git a/crates/storage-mongodb/src/stream_record_docs.rs b/crates/storage-mongodb/src/stream_record_docs.rs index 4fa57587c..045b1afb7 100644 --- a/crates/storage-mongodb/src/stream_record_docs.rs +++ b/crates/storage-mongodb/src/stream_record_docs.rs @@ -23,9 +23,10 @@ pub(crate) fn records_from_docs(docs: Vec) -> Result let record_bson = d .remove("record_data") .ok_or_else(|| StorageError::Internal("Missing record_data".to_owned()))?; - // Reverses the object-key escape applied when the record was + // Reverses the object-key escape of a record marked when it was // written; see json_to_item_data. - let json_val = crate::data::item_data_to_json(&record_bson)?; + let json_val = + crate::data::item_data_to_json(&record_bson, crate::data::names_escaped(&d))?; serde_json::from_value(json_val).map_err(|e| StorageError::Internal(e.to_string())) }) .collect() From c8d852f4d6a897b65d756297bbfefecadf362257 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:45:01 +0000 Subject: [PATCH 26/30] fix(storage): leave the TTL attribute name as written UpdateTimeToLive accepts only [A-Za-z0-9._-] in the attribute name (validate_ttl_attribute_name), so the escape never changed the TTL name. On PostgreSQL the fence of the index build bound the escaped name, while update_ttl stores the raw one. A name that the escape changes would never match. PostgreSQL and MongoDB now run main's TTL code. --- crates/storage-mongodb/src/metadata_engine.rs | 25 ++++++------------- .../storage-postgres/src/metadata_engine.rs | 8 ++---- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/crates/storage-mongodb/src/metadata_engine.rs b/crates/storage-mongodb/src/metadata_engine.rs index 3dac4241b..7fe21f9c3 100644 --- a/crates/storage-mongodb/src/metadata_engine.rs +++ b/crates/storage-mongodb/src/metadata_engine.rs @@ -18,7 +18,6 @@ use extenddb_storage::error::StorageError; use crate::MongoEngine; use crate::data::{data_collection_name, document_to_item}; -use extenddb_storage::util::escape_control; fn extract_id_fields(doc: &Document) -> (String, String) { let id = doc.get_document("_id").ok(); @@ -36,15 +35,13 @@ fn extract_id_fields(doc: &Document) -> (String, String) { /// Build the expression that reads a DynamoDB attribute from `item_data` as a /// literal field name. MongoDB normally interprets dots in a query field path /// as nested-document traversal, but DynamoDB permits dots in attribute names. -/// The stored field name is the escaped form of the attribute name (see -/// `extenddb_storage::util::escape_control`), so the lookup targets that form. fn literal_ttl_value_expression(ttl_attribute: &str) -> Document { doc! { "$getField": { "field": "N", "input": { "$getField": { - "field": escape_control(ttl_attribute).as_ref(), + "field": ttl_attribute, "input": "$item_data", } } @@ -72,7 +69,7 @@ fn literal_ttl_epoch_expression(ttl_attribute: &str) -> Document { /// also performs the expiry comparison in MongoDB, so non-expired low-`_id` /// documents cannot starve expired documents later in the collection. fn ttl_candidate_query(ttl_attribute: &str, now_epoch: i64) -> (Document, Document) { - let ttl_field = format!("item_data.{}.N", escape_control(ttl_attribute)); + let ttl_field = format!("item_data.{ttl_attribute}.N"); if ttl_attribute.contains('.') { let ttl_epoch = literal_ttl_epoch_expression(ttl_attribute); ( @@ -377,12 +374,8 @@ impl MetadataEngine for MongoEngine { let coll_name = data_collection_name(table_id); let data_coll = self.data_db.collection::(&coll_name); - // The stored field name is the escaped attribute name, and the - // escape also keeps U+0000 out of the index name. Names without - // U+0000 or U+0001 escape to themselves, so existing index names - // do not change. - let index_name = format!("idx_ttl_{}", escape_control(&ttl_attribute)); - let index_key = format!("item_data.{}.N", escape_control(&ttl_attribute)); + let index_name = format!("idx_ttl_{ttl_attribute}"); + let index_key = format!("item_data.{ttl_attribute}.N"); let index = IndexModel::builder() .keys(doc! { &index_key: 1 }) @@ -440,9 +433,7 @@ impl MetadataEngine for MongoEngine { .get_str("table_id") .map_err(|_| StorageError::Internal("missing table_id".to_string()))?; - // Same escaped form as create_ttl_index so the drop targets the - // index that was created. - let index_name = format!("idx_ttl_{}", escape_control(&ttl_attribute)); + let index_name = format!("idx_ttl_{ttl_attribute}"); let coll_name = data_collection_name(table_id); let data_coll = self.data_db.collection::(&coll_name); @@ -522,11 +513,9 @@ impl MetadataEngine for MongoEngine { if items.len() >= limit { break; } - // Parse the TTL value and check if expired. The stored field - // name is the escaped attribute name. + // Parse the TTL value and check if expired if let Ok(item_data) = doc.get_document("item_data") - && let Ok(ttl_obj) = - item_data.get_document(escape_control(&ttl_attribute).as_ref()) + && let Ok(ttl_obj) = item_data.get_document(&ttl_attribute) && let Ok(n_str) = ttl_obj.get_str("N") && let Ok(ttl_val) = n_str.parse::() && ttl_val >= 1 diff --git a/crates/storage-postgres/src/metadata_engine.rs b/crates/storage-postgres/src/metadata_engine.rs index 6ef499c04..b2f958b3b 100755 --- a/crates/storage-postgres/src/metadata_engine.rs +++ b/crates/storage-postgres/src/metadata_engine.rs @@ -292,9 +292,7 @@ impl MetadataEngine for PostgresEngine { ) -> BoxFuture<'_, Result<(), StorageError>> { let account_id = account_id.to_string(); let table_name = table_name.to_string(); - // Stored attribute names carry the same escape as the rest of item_data, - // so the name SQL addresses must be the stored form. - let ttl_attribute = extenddb_storage::util::escape_control(ttl_attribute).into_owned(); + let ttl_attribute = ttl_attribute.to_string(); Box::pin(async move { Self::validate_account_id(&account_id)?; let (table_id,): (String,) = sqlx::query_as( @@ -410,9 +408,7 @@ impl MetadataEngine for PostgresEngine { ) -> BoxFuture<'_, Result, StorageError>> { let account_id = account_id.to_string(); let table_name = table_name.to_string(); - // Stored attribute names carry the same escape as the rest of item_data, - // so the name SQL addresses must be the stored form. - let ttl_attribute = extenddb_storage::util::escape_control(ttl_attribute).into_owned(); + let ttl_attribute = ttl_attribute.to_string(); Box::pin(async move { Self::validate_account_id(&account_id)?; let (table_id,): (String,) = sqlx::query_as( From 48ee608feaedaff37deac1f331c8445d302d82c1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:45:01 +0000 Subject: [PATCH 27/30] test(cli): wait for other sessions to close before the migration 13 runs test_migrate_applies_migration_13_beside_its_own_sessions slept 1 s after it stopped the server, and ran migrate --yes right after it closed the other session. Both runs count the other sessions on the databases, and PostgreSQL removes a closed session from pg_stat_activity a moment after the close returns. The test now polls pg_stat_activity until no client session holds either database, for at most 30 s. --- tests/test_cli_vector_catalog_migration.py | 24 ++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/tests/test_cli_vector_catalog_migration.py b/tests/test_cli_vector_catalog_migration.py index d1d8c87ac..4fb96b5e4 100644 --- a/tests/test_cli_vector_catalog_migration.py +++ b/tests/test_cli_vector_catalog_migration.py @@ -130,6 +130,25 @@ def _data_db(cli_env): return cli_env["db_name"][: -len("_catalog")] +def _wait_until_alone(databases, timeout=30.0): + """Wait until no client session is connected to `databases`. PostgreSQL + removes a closed session from pg_stat_activity a moment after the close + returns, and a stopped server's sessions end after its process does, so a + run that counts other sessions waits for them here instead of sleeping.""" + deadline = time.monotonic() + timeout + while True: + others = _query( + "postgres", + "SELECT count(*) FROM pg_stat_activity WHERE datname = ANY(%s) " + "AND backend_type = 'client backend'", + (list(databases),), + ) + if others == 0: + return + assert time.monotonic() < deadline, f"{others} session(s) still hold {databases}" + time.sleep(0.1) + + def _query(database, sql, params=()): conn = _conn(database) try: @@ -451,9 +470,9 @@ def test_migrate_applies_migration_13_beside_its_own_sessions(self, cli_env): _seed_table_and_backup(cli_env) finally: _run_extenddb("stop", config=cli_env["config_path"], check=False) - time.sleep(1) - _forget_migration_13(cli_env) catalog, data = cli_env["db_name"], _data_db(cli_env) + _wait_until_alone((catalog, data)) + _forget_migration_13(cli_env) pending = _run_extenddb( "migrate", *_pg_args(), config=cli_env["config_path"], check=False @@ -482,6 +501,7 @@ def test_migrate_applies_migration_13_beside_its_own_sessions(self, cli_env): ), refused_output assert 13 not in _ledger_ids(catalog) assert 13 not in _ledger_ids(data) + _wait_until_alone((catalog, data)) applied = _run_extenddb( "migrate", "--yes", *_pg_args(), From d5c27dc1efbb16212ec42406e50dbeddec5e8381 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:56:54 +0000 Subject: [PATCH 28/30] docs: record how PostgreSQL and MongoDB store U+0000 (ADR-0031) ADR-0031 records the stored form: the escape of the item documents, the refusal of U+0000 in a PostgreSQL key, the MongoDB mark, and migration 13. 0031 is the first number that no open PR claims: #529 and #536 add 0028, and #954 adds 0030. - differences-from-dynamodb.md lists the refusal of U+0000 in a key on PostgreSQL. - The upgrade manual's entry is now a v1.1.0 entry. It says what an operator sees when the data body fails after the catalog body committed, and describes the MongoDB mark. The Current Status paragraph about 1.0.0 and migrations 1 to 12 is as main has it. - 04-component-storage.md and the escape module's comment no longer say that the key columns hold escaped text. The escape's byte order and prefix tests go with that claim. map_json checks a key with needs_escape. --- crates/storage/src/util/control_chars.rs | 75 +++--------- .../0031-u0000-on-postgresql-and-mongodb.md | 108 ++++++++++++++++++ docs/adr/README.md | 1 + docs/design/04-component-storage.md | 28 +++-- docs/differences-from-dynamodb.md | 1 + docs/manuals/07-upgrade-manual.md | 14 ++- 6 files changed, 150 insertions(+), 77 deletions(-) create mode 100644 docs/adr/0031-u0000-on-postgresql-and-mongodb.md diff --git a/crates/storage/src/util/control_chars.rs b/crates/storage/src/util/control_chars.rs index 7dd1bb8e2..c3ae4b019 100644 --- a/crates/storage/src/util/control_chars.rs +++ b/crates/storage/src/util/control_chars.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 -//! Order-preserving escape for the two characters a storage engine may not be -//! able to hold verbatim. +//! Escape for the two characters a storage engine may not be able to hold +//! verbatim in a document. //! //! DynamoDB accepts the character U+0000 anywhere a string appears: partition //! and sort keys, index keys, attribute values, map keys, attribute names. Two -//! of the storage engines cannot store it as is. PostgreSQL `TEXT` rejects the -//! byte (`invalid byte sequence for encoding "UTF8": 0x00`) and `jsonb` rejects -//! the `\u0000` escape. BSON field names are C strings and end at the first NUL. +//! of the storage engines cannot store it as is in a document. PostgreSQL +//! `jsonb` rejects the `\u0000` escape, and BSON field names are C strings and +//! end at the first NUL. PostgreSQL `TEXT` rejects the byte too (`invalid byte +//! sequence for encoding "UTF8": 0x00`); the PostgreSQL key columns are not +//! escaped, and that backend refuses a key value that holds U+0000. //! //! The escape maps each affected character to a two-character sequence that //! contains no NUL: @@ -19,25 +21,16 @@ //! //! Every other character passes through unchanged, so a string without either //! character encodes to itself and the stored form of ordinary data does not -//! change. The mapping is applied per character and the two output sequences -//! share the prefix U+0001, so three properties hold, each pinned by a test -//! below: -//! -//! - **Round trip.** `unescape(escape(s)) == s` for every `s`. -//! - **Byte order.** `escape(a) < escape(b)` exactly when `a < b` under UTF-8 -//! byte comparison. PostgreSQL compares key columns under `COLLATE "C"`, so -//! Query ordering, `BETWEEN`, and cursor comparisons on escaped keys give the -//! same answers as on the originals. -//! - **Prefix.** `escape(p)` is a prefix of `escape(s)` exactly when `p` is a -//! prefix of `s`, so `begins_with` on escaped values is exact. +//! change. The mapping is applied per character, so `unescape(escape(s)) == s` +//! for every `s` and two different strings never escape to the same text; the +//! tests below pin both. //! //! Decoding is lenient about a U+0001 that is not followed by U+0001 or U+0002: -//! it is returned as a literal U+0001. Rows written before this escape existed -//! can hold such a character, and a lenient decoder reads them unchanged. A -//! legacy string that contained U+0001 immediately followed by U+0001 or U+0002 -//! would decode differently; on PostgreSQL, catalog migration 13, -//! `escape_control_chars`, re-encodes such rows so that case cannot arise after -//! it has run. +//! it is returned as a literal U+0001. A string written before this escape +//! existed that contained U+0001 immediately followed by U+0001 or U+0002 +//! would decode differently. On PostgreSQL, catalog migration 13, +//! `escape_control_chars`, re-encodes such documents so that case cannot arise +//! after it has run; on MongoDB only a document marked as escaped is decoded. use std::borrow::Cow; @@ -154,11 +147,7 @@ fn map_json( Value::Object(map) => { let mut out = serde_json::Map::with_capacity(map.len()); for (k, val) in map { - let key = if k.bytes().any(|b| b == 0 || b == 1) { - f(&k) - } else { - k - }; + let key = if needs_escape(&k) { f(&k) } else { k }; out.insert(key, map_json(val, values_too, f)); } Value::Object(out) @@ -236,38 +225,6 @@ mod tests { } } - #[test] - fn escape_preserves_utf8_byte_order() { - // The whole point: PostgreSQL compares the escaped column under - // COLLATE "C", and every ordering answer must equal the answer on - // the originals. - let corpus = corpus(4); - for a in &corpus { - for b in &corpus { - let want = a.as_bytes().cmp(b.as_bytes()); - let got = escape_control(a) - .as_bytes() - .cmp(escape_control(b).as_bytes()); - assert_eq!(want, got, "a={a:?} b={b:?}"); - } - } - } - - #[test] - fn escape_preserves_prefixes() { - // begins_with on escaped values must be exact in both directions. - let corpus = corpus(4); - for p in &corpus { - for s in &corpus { - let want = s.as_bytes().starts_with(p.as_bytes()); - let got = escape_control(s) - .as_bytes() - .starts_with(escape_control(p).as_bytes()); - assert_eq!(want, got, "p={p:?} s={s:?}"); - } - } - } - #[test] fn escaped_forms_are_distinct_for_distinct_inputs() { let corpus = corpus(4); diff --git a/docs/adr/0031-u0000-on-postgresql-and-mongodb.md b/docs/adr/0031-u0000-on-postgresql-and-mongodb.md new file mode 100644 index 000000000..e7a5a8c35 --- /dev/null +++ b/docs/adr/0031-u0000-on-postgresql-and-mongodb.md @@ -0,0 +1,108 @@ +# ADR-0031: How the PostgreSQL and MongoDB backends store U+0000 + +- Status: Accepted +- Date: 2026-11-24 +- Deciders: @LeeroyHannigan + +## Context + +DynamoDB accepts the character U+0000 anywhere a string appears: in partition, +sort and index key values, in values, in map keys and in attribute names. It +sorts as the byte 0x00 (measured on 2026-09-18, issue #364). Two backends +cannot store it as written: + +- PostgreSQL `TEXT` refuses the byte 0x00, and `jsonb` refuses the escape + `\u0000`. Key values live in `TEXT COLLATE "C"` columns that form btree + primary keys. Item documents are `jsonb`: `item_data`, the stream records, + the item images of the queued index updates, and `backup_items`. +- BSON field names are C strings, so MongoDB cannot hold U+0000 in an + attribute name or a map key. BSON string values are length-prefixed and + hold it. + +Before this decision, PostgreSQL answered 500 to every item that held U+0000, +and MongoDB answered 500 to an item whose attribute name or map key held it. + +PostgreSQL refuses a btree entry over 2704 bytes. DynamoDB allows a partition +key value of 2048 bytes and a sort key value of 1024 bytes, so an encoding +that makes key text longer can push a key that an earlier release stored over +that limit. + +Data that an earlier release stored must keep reading back as written. + +## Options Considered + +1. **Escape every string on PostgreSQL, keys included.** Store U+0000 as + U+0001 U+0001 and U+0001 as U+0001 U+0002 in the key columns and in the + documents. The mapping keeps byte order and prefixes, so key comparisons + give the same rows. Each U+0000 and U+0001 adds one byte. A 2046-byte + partition key with 682 U+0001, which DynamoDB and earlier releases store, + becomes 2728 bytes and fails the btree limit: its PutItem answers 500, and + a migration that rewrites the key columns stops on such a row. +2. **`bytea` key columns on PostgreSQL.** Key text stored as bytes holds 0x00 + at its raw length. Every key column, every bind site and every key + comparison changes type, and a migration rewrites every key column of every + table. +3. **Escape the documents only, and refuse U+0000 in keys on PostgreSQL.** The + key columns keep the text earlier releases stored. A table or index key + value that holds U+0000 gets a `ValidationException`, which issue #364 + accepts for a backend that cannot store the byte. The strings of the + `jsonb` documents go through the escape of option 1; no btree entry covers + them. +4. **MongoDB: escape every field name.** A name that an earlier release stored + with U+0001 followed by U+0001 or U+0002 then reads back changed, and two + such names, `c\x01` and `c\x01\x02`, read back as one. The next write of + the item stores it without the other attribute. +5. **MongoDB: escape the field names of a document only when one holds + U+0000, and mark that document.** No earlier release could store such a + name, so every document an earlier release wrote is unmarked, and an + unmarked document is read as it is stored. + +## Decision + +- PostgreSQL takes option 3: the strings of item documents go through the + escape of `extenddb_storage::util::escape_control`, the key columns hold the + key text as earlier releases stored it, and a request whose table key or + index key value holds U+0000 gets a `ValidationException` that names the + limitation. +- MongoDB takes option 5: a document whose field names were escaped carries + the top-level field `names_escaped` set to `true`, and only such a document + is decoded. Stream records follow the same rule. +- Catalog migration 13, `escape_control_chars`, re-encodes on PostgreSQL the + documents earlier releases wrote that hold U+0001, in one transaction per + database with its ledger row. It is breaking and not convergent, because + the escape is not idempotent. It does not apply on SQLite, Cassandra and + MongoDB. + +## Consequences + +- On PostgreSQL every key an earlier release stored keeps its bytes and its + length. Migration 13 rewrites no key column, and `gsi_pending`'s + `worker_partition`, a hash of the base key text, does not change. +- U+0000 in a key value is a documented difference on PostgreSQL + ([Differences from DynamoDB](../differences-from-dynamodb.md)). An item + written before an index existed whose key for that index holds U+0000 is + left out of the index, by the backfill and by a restore, as an item whose + key attribute has another type is. +- No index entry or constraint covers the strings of a document, so a rewrite + of migration 13 fails only when the database does. The catalog body commits + first, so such a failure leaves the data store behind the catalog store + until `extenddb migrate --yes` runs the data body again + ([upgrade manual](../manuals/07-upgrade-manual.md)). +- The native MongoDB update paths do not read the document, so they cannot + tell a marked document from an unmarked one. An update whose attribute name, + or a field name inside its value, holds U+0000 or U+0001 takes the session + path. +- Going back to an earlier release on PostgreSQL means restoring both + databases from the backups taken before the upgrade, as for every breaking + migration. + +--- + +## 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. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7febe92df..e196b7276 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -55,6 +55,7 @@ decision, write a new ADR. | [0026](0026-credential-crypto-on-aws-lc.md) | Credential cryptography uses AWS-LC through aws-lc-rs | Accepted | | [0027](0027-cassandra-index-row-version-stamps.md) | Cassandra: index rows carry the base-row version as their write timestamp | Accepted | | [0029](0029-crates-io-packaging.md) | The workspace crates go to crates.io together, at one version with exact pins | Accepted | +| [0031](0031-u0000-on-postgresql-and-mongodb.md) | How the PostgreSQL and MongoDB backends store U+0000 | Accepted | --- diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index ef10680eb..541b67e84 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -422,20 +422,24 @@ The PostgreSQL backend uses two categories of tables: string appears (measured 2026-09-18: partition and sort keys, index keys, values, strings in lists, map keys, attribute names; it sorts as the byte 0x00 and is a different key from the six-character text `\u0000`). - PostgreSQL `TEXT` rejects the byte and `jsonb` rejects the `\u0000` escape, - so every string that reaches a key column or an `item_data`, `gsi_pending`, - `stream_pending`, `stream_records`, or `backup_items` document goes through the escape in + PostgreSQL `jsonb` rejects the `\u0000` escape, so every string of an + `item_data`, `gsi_pending`, `stream_pending`, `stream_records`, or + `backup_items` document goes through the escape in `extenddb_storage::util::escape_control`: U+0000 is stored as U+0001 U+0001 and U+0001 as U+0001 U+0002; every other character is unchanged, so ordinary - data is stored exactly as before. The mapping preserves UTF-8 byte order and - prefixes, so `COLLATE "C"` comparisons, `BETWEEN`, `begins_with`, and - row-comparison cursors on escaped columns return the rows the raw text - would. SQL that addresses an attribute by name inside `item_data` (the TTL - index and sweep, vector search filters) uses the escaped name. The MongoDB - backend applies the same escape to BSON field names only, since BSON string - values are length-prefixed and hold the byte as is. Rows written before the - escape existed are re-encoded once on PostgreSQL by catalog migration 13, - `escape_control_chars` (see the upgrade manual). + data is stored exactly as before. SQL that addresses an attribute by name + inside `item_data` (vector search filters) uses the escaped name. + PostgreSQL `TEXT` rejects the byte too. The key columns are not escaped: + they hold the key text as an earlier release stored it, and + `data::key_text` refuses a table or index key value that holds U+0000 with + a `ValidationException` (see + [Differences from DynamoDB](../differences-from-dynamodb.md)). The MongoDB + backend escapes the BSON field names of a document in which a name holds + U+0000 and marks the document with `names_escaped`; it decodes only marked + documents, so a document an earlier release wrote reads back as written. + BSON string values are length-prefixed and hold the byte as is. Documents + written before the escape existed are re-encoded once on PostgreSQL by + catalog migration 13, `escape_control_chars` (see the upgrade manual). - **GSI tables**: GSI tables include base table primary key columns (`base_pk`, `base_sk_*`) as actual SQL columns (not just inside `item_data` JSONB). This diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index c44479284..a0b9edf6d 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -15,6 +15,7 @@ from a request sent to that service or backend. | Global Tables | CreateGlobalTable, replication | Not implemented (returns UnknownOperationException) | | DAX (Accelerator) | In-memory caching layer | Not applicable | | PartiQL | ExecuteStatement, BatchExecuteStatement, ExecuteTransaction | Supported for all four statement types (see the PartiQL section below). Built behind a default-on `partiql` build feature. | +| U+0000 in a key attribute value (PostgreSQL backend only) | Accepted in partition keys, sort keys and index keys, and sorted as the byte 0x00 | Refused with a ValidationException: "Key attribute values cannot contain the character U+0000 on the PostgreSQL storage backend, whose text columns cannot hold the byte 0x00. Remove the character from the key value, or use another storage backend." PostgreSQL `TEXT` key columns cannot hold the byte. The answer covers a write whose table key, or whose key for one of the table's indexes, holds the character, and a read, a Query key condition or an `ExclusiveStartKey` that holds it; in `TransactWriteItems` an Update that computes such an index key cancels with a `ValidationError` reason carrying the same message. An item written before an index existed whose key for that index holds U+0000 is left out of the index, by the backfill and by a restore. U+0000 in values, attribute names and map keys is stored and returned as written. SQLite, MongoDB and Cassandra store the character in keys. | | Numeric precision on partition/sort keys (MongoDB backend only) | 38 significant digits | 34 significant digits (BSON Decimal128). Values that exceed this precision are rejected at write and query time with a ValidationException rather than silently downcast. PostgreSQL backend supports the full 38 digits. | | Inverted numeric `BETWEEN` on a sort key (MongoDB backend only) | ValidationException ("The BETWEEN operator requires upper bound to be greater than or equal to lower bound") | Same error in all practical cases. The inversion guard compares bounds via `f64`, so a `KeyConditionExpression` `BETWEEN` whose bounds are inverted only beyond f64's ~15–17 significant digits (e.g. `BETWEEN 10000000000000002 AND 10000000000000001`) is not rejected and returns an empty result set instead. Valid ranges are never wrongly rejected. | | `TransactGetItems` overlapping an in-flight `TransactWriteItems` on the same item | May cancel the read with `TransactionCanceledException` and reason `TransactionConflict` | Never cancels for this reason on PostgreSQL: the read runs in one `REPEATABLE READ` snapshot taken at its first read, so it sees either all of the write or none of it and returns the pre-write state while the write is in flight. That is a legal serial order (the read ordered before the write) and the all-or-nothing guarantee holds, but a client that retries on `TransactionConflict` to observe the newest state will not get that signal here. SQLite behaves the same (one WAL snapshot); MongoDB with the default `snapshot` read concern likewise, and the row above covers the other read concerns. | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index a2800dfc5..ed0b6b8dc 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -6,7 +6,7 @@ 1.0.0 carries the same catalog migrations as 0.1.15, 1 to 12. A catalog that 0.1.15 migrated is Current under 1.0.0, so a deployment on 0.1.15 stops its servers and starts the 1.0.0 binary with no `migrate` step, and a rollback to 0.1.15 starts the 0.1.15 binary on the same catalog and configuration while the deployment has not run `extenddb encryption-key switch`. 1.0.0 also refuses to start on a catalog key that is not 32 bytes in base64 (0.1.15 started on one and failed every signed request), keeps the key in locked memory, and adds an optional KEK file outside the catalog (see [the v1.0.0 entry](#v100-the-catalog-key-is-checked-at-startup-and-kept-in-locked-memory-a-kek-file-is-optional)). On Cassandra, 1.0.0 reads and writes at `LOCAL_QUORUM` where 0.1.15 read many of its rows at `ONE`, so a request fails while fewer than a quorum of its keyspace's replicas are up, which at a replication factor of 2 means one replica down: use a replication factor of 3 before the upgrade (see [the v1.0.0 entry](#v100-cassandra-reads-and-writes-at-local_quorum)). The paragraphs below on catalog migrations 1 to 12, and on a rollback to 0.1.14 or an earlier release, are for a deployment on 0.1.14 or an earlier release. The notes on `[backup.store]` and on backups taken by 0.1.14 and earlier releases apply to every deployment. -This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 13, which `extenddb migrate --list` prints. **Every deployment created by 0.1.14 or an earlier release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every earlier release to migration 1's schema, migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)), and migration 6 adds the backup catalog index and the restore job records ([below](#migration-6-the-backup-catalog-index)). Migration 7 adds the `stream_pending` table to the PostgreSQL data database, where a write stores its stream record until the record gets its sequence number after the write commits; it does not apply to the other backends. Migration 8 adds the `restore_progress` table to the PostgreSQL data database, where a store-backed restore records each data file it applied; it does not apply on the other backends either. +This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 12, which `extenddb migrate --list` prints. **Every deployment created by 0.1.14 or an earlier release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every earlier release to migration 1's schema, migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)), and migration 6 adds the backup catalog index and the restore job records ([below](#migration-6-the-backup-catalog-index)). Migration 7 adds the `stream_pending` table to the PostgreSQL data database, where a write stores its stream record until the record gets its sequence number after the write commits; it does not apply to the other backends. Migration 8 adds the `restore_progress` table to the PostgreSQL data database, where a store-backed restore records each data file it applied; it does not apply on the other backends either. Migration 9, `warm_throughput`, adds a nullable `warm_throughput` column to the `tables` and `indexes` catalog tables on PostgreSQL, SQLite and Cassandra. It holds the `WarmThroughput` a client sets on a table or a global secondary index, which `DescribeTable` reports; nothing acts on the value (see [Differences from DynamoDB](../differences-from-dynamodb.md)). Tables created before the migration report the defaults for their billing mode. On MongoDB it changes nothing, since the catalog collections have no validator, and the ledger records it as not applicable. Migration 9 is breaking: to go back to a release without it, restore the backup taken before the upgrade (see [Rollback Procedure](#rollback-procedure)). @@ -16,7 +16,7 @@ Migration 11 rewrites the attribute names that a PostgreSQL deployment stores in Migration 12, `unique_access_key_ids`, gives the MongoDB `access_keys` collection a unique index on the access key ID (see step 4 of the [general upgrade procedure](#general-upgrade-procedure)); it does not apply on the other backends. -Migration 13, `escape_control_chars`, re-encodes the strings that a PostgreSQL deployment stored before it, so that a string can hold U+0000, and runs only with every server of an earlier release stopped (see [U+0000 in strings on PostgreSQL and MongoDB](#u0000-in-strings-on-postgresql-and-mongodb-catalog-migration-13)). It does not apply on the other backends, where `extenddb migrate --yes` records it as not applicable. A deployment on 0.1.15 or 1.0.0 runs `extenddb migrate --yes` once for it, on every backend. +1.1.0 adds migration 13, `escape_control_chars`, which re-encodes the item documents that a PostgreSQL deployment stored before it, so that a document can hold U+0000, and runs only with every server of an earlier release stopped (see [v1.1.0: U+0000 in strings on PostgreSQL and MongoDB](#v110-u0000-in-strings-on-postgresql-and-mongodb-catalog-migration-13)). It does not apply on the other backends, where `extenddb migrate --yes` records it as not applicable. A deployment on 0.1.15 or 1.0.0 runs `extenddb migrate --yes` once for it, on every backend. Configure `[backup.store]` before the release that stops creating in-catalog backups. The [Backup and Restore manual](14-backup-and-restore.md) covers choosing and securing a store, the recovery figures, the restore drill, catalog-loss recovery and what to do with in-catalog backups. This section says what the upgrade changes. In this release, CreateBackup and RestoreTableFromBackup work as follows: @@ -390,11 +390,13 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. -### U+0000 in strings on PostgreSQL and MongoDB (catalog migration 13) +### v1.1.0: U+0000 in strings on PostgreSQL and MongoDB (catalog migration 13) -DynamoDB accepts U+0000 anywhere a string appears. The PostgreSQL backend now stores every string through an order-preserving escape: U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002, and every other character as it is, so a string that holds neither character is stored as before. The MongoDB backend applies the same escape to BSON field names (attribute names and map keys); BSON string values already held U+0000. SQLite and Cassandra store the character as written, and their stored data does not change. +DynamoDB accepts U+0000 anywhere a string appears. The PostgreSQL backend now stores the strings of an item document (attribute names, map keys and values, in `item_data`, the stream records, the queued index updates and `backup_items`) through an escape: U+0000 as U+0001 U+0001, U+0001 as U+0001 U+0002, and every other character as it is, so a string that holds neither character is stored as before. The PostgreSQL key columns hold the key text as before, and PostgreSQL `TEXT` cannot hold U+0000, so a request whose table key or index key value holds U+0000 gets a `ValidationException` where an earlier release answered 500 (see [Differences from DynamoDB](../differences-from-dynamodb.md)). The MongoDB backend escapes the field names (attribute names and map keys) of a document in which a name holds U+0000, and marks that document; BSON string values already held U+0000. SQLite and Cassandra store the character as written, and their stored data does not change. -**Migration 13, `escape_control_chars`, PostgreSQL.** Rows an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those rows: in the data database, every data table, index table and vector index table (the text key columns and `item_data`), the item images of `gsi_pending` (`old_item` and `new_item`; migration 11 escapes `index_context`), `stream_records` and `stream_pending`; in the catalog database, `backup_items`. Only rows that contain U+0001 change. A partition key column of a key schema with more than one HASH attribute holds the netstring join of the parts, so it is rebuilt part by part, and `gsi_pending.worker_partition` is recomputed for the queued rows the migration changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates. +**Migration 13, `escape_control_chars`, PostgreSQL.** Documents an earlier release wrote hold their strings raw, and a raw U+0001 immediately followed by U+0001 or U+0002 reads back differently under the new decoder; a lone U+0001 reads back unchanged. Migration 13 re-encodes those documents: in the data database, `item_data` of every data table, index table and vector index table, the item images of `gsi_pending` (`old_item` and `new_item`; migration 11 escapes `index_context`), `stream_records` and `stream_pending`; in the catalog database, `backup_items`. Only documents that contain U+0001 change, and no key column changes. The migration reads every row of every table once, so on a large deployment it takes time proportional to the size of the data. Each database's rewrite runs in one transaction with its ledger row: a run that stops leaves that database as it was, and the next `migrate --yes` runs it again. The ledger notes, which `migrate` and `verify` print, name each table the migration changed with its number of row updates, and each table it skipped because the table is being deleted or its physical table does not exist. + +The catalog database's rewrite commits before the data database's rewrite starts. If the data database's rewrite then fails, for example on a lost connection or a full disk, `extenddb migrate` reports the data store at migration 12, behind the catalog store at migration 13. In that state a server of this release refuses to start because the data store is behind, and a server of an earlier release refuses the catalog because it holds migration 13. Fix the cause and run `extenddb migrate --yes` again: it runs the data database's rewrite alone. Upgrade in this order: @@ -406,7 +408,7 @@ The migration cannot tell a row a running server writes from a legacy row, so it A server of this release refuses a deployment where migration 13 is pending, and `extenddb init` applies it to a new deployment, which has nothing to rewrite. The migration is breaking and not convergent: a server of an earlier release refuses the migrated catalog, `migrate --yes --reconverge` skips migration 13, and going back to an earlier release means restoring both databases from the backups taken before the upgrade. A binary of an earlier release given a restored catalog and a migrated data database would read escaped strings as data. -**MongoDB.** The MongoDB backend has no migration for this change; its ledger records migration 13 as not applicable. Field names an earlier release wrote are stored raw. A name that holds a lone U+0001 reads back unchanged, as do all string values and all key strings; a name that holds U+0001 immediately followed by U+0001 or U+0002 reads back with that pair decoded as U+0000 or U+0001. Deployments whose attribute names never contain U+0001 are not affected. +**MongoDB.** The MongoDB backend has no migration for this change; its ledger records migration 13 as not applicable. A document an earlier release wrote holds its field names as written and carries no mark, and it reads back unchanged, whatever U+0001 its names hold. A write of this release escapes the field names only of an item in which a name holds U+0000, which no earlier release could store, and marks that document; it reads back with the names decoded. ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` From 37fc13064c3e93a7127b0a78e5c51bd2949a5a97 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:56:54 +0000 Subject: [PATCH 29/30] test(storage-postgres): build the two long keys from letters and digits test_a_long_key_holding_u0001_is_stored and migration_13_applies_over_a_long_key_holding_u0001 built their 2046-byte key from lowercase letters. PostgreSQL compresses a btree entry over about 2 KB when the compression saves a quarter of it. With each U+0001 stored as two bytes, such a key compresses enough to fit the 2704-byte entry limit. The two tests therefore passed with the key escape in place. A key of letters and digits does not compress that far. Its escaped form fails the insert with "index row size 2752 exceeds btree version 4 maximum 2704", measured on pgvector/pg16 with the DDL of data/ddl.rs. The tests now fail without the fix and pass with it. --- .../storage-postgres/tests/migrations_golden.rs | 15 +++++++++------ tests/test_nul_strings.py | 14 +++++++++----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/storage-postgres/tests/migrations_golden.rs b/crates/storage-postgres/tests/migrations_golden.rs index f3ee27f8a..7ae73eab7 100644 --- a/crates/storage-postgres/tests/migrations_golden.rs +++ b/crates/storage-postgres/tests/migrations_golden.rs @@ -539,23 +539,26 @@ async fn ledger_rows_of_13(pool: &PgPool) -> i64 { } /// A partition key of 2046 bytes, within the service's 2048, made of letters -/// from a fixed pseudo-random sequence with U+0001 after every second one -/// (682 of them), which an earlier release stores in `pk` as it is. Migration -/// 13 applies in both stores and leaves the key's 2046 bytes as they were; -/// escaping the key column would make it 2728 bytes, over PostgreSQL's btree -/// entry limit of 2704. +/// and digits from a fixed pseudo-random sequence with U+0001 after every +/// second one (682 of them), which an earlier release stores in `pk` as it is. +/// Migration 13 applies in both stores and leaves the key's 2046 bytes as they +/// were; escaping the key column would make it 2728 bytes, over PostgreSQL's +/// btree entry limit of 2704. PostgreSQL compresses an entry over about 2 KB +/// when it can, and a key of letters alone compresses enough to fit the limit +/// with each U+0001 stored as two bytes; letters and digits do not. #[tokio::test] async fn migration_13_applies_over_a_long_key_holding_u0001() { let Some(base) = base_conn() else { return skip("migration 13 long key"); }; + const ALNUM: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let mut state: u32 = 0x2545_f491; let mut key = String::new(); for i in 0..1364 { state ^= state << 13; state ^= state >> 17; state ^= state << 5; - key.push(char::from(b'a' + (state % 26) as u8)); + key.push(char::from(ALNUM[(state % 62) as usize])); if i % 2 == 1 { key.push('\u{1}'); } diff --git a/tests/test_nul_strings.py b/tests/test_nul_strings.py index 4fba14353..d7fe542ba 100644 --- a/tests/test_nul_strings.py +++ b/tests/test_nul_strings.py @@ -25,6 +25,7 @@ from __future__ import annotations import random +import string import time import pytest @@ -373,13 +374,16 @@ def test_delete_item_on_the_key(self, dynamodb_client, nul_table, c): def _long_key() -> str: - """2046 bytes: 1364 random letters with U+0001 after every second one, 682 - in all. The service allows a partition key value of 2048 bytes. Random - letters keep PostgreSQL from compressing the key below its btree entry - limit of 2704 bytes; a repeated pattern would compress.""" + """2046 bytes: 1364 random letters and digits with U+0001 after every + second one, 682 in all. The service allows a partition key value of 2048 + bytes. PostgreSQL compresses a btree entry over about 2 KB when it can, + and a key of letters alone compresses enough to fit the 2704-byte entry + limit even with each U+0001 stored as two bytes; letters and digits do + not.""" rng = random.Random(368) key = "".join( - rng.choice("abcdefghijklmnopqrstuvwxyz") + ("" if i % 2 == 0 else SOH) for i in range(1364) + rng.choice(string.ascii_letters + string.digits) + ("" if i % 2 == 0 else SOH) + for i in range(1364) ) assert (len(key.encode()), key.count(SOH)) == (2046, 682) return key From d559e2a127ea17727043df61ae364b41bc089f97 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:14:54 +0000 Subject: [PATCH 30/30] fix(storage-postgres): read a filtered vector search in stored form A SearchVectors request whose condition the equality filters cannot express takes the filtered path of #1449. That path bound each equality filter with the name and the JSON text that the request gives. It also decoded each candidate item from item_data with serde. This branch stores the strings of item_data through the escape, so the path read the stored form. A filter value that holds U+0000 failed the jsonb cast, and the condition read the escaped strings. The search now builds the stored form of the equality filters once, for the filtered path and the other path. The filtered path decodes each candidate through json_to_item before it evaluates the condition, as the other path decodes each hit. a_filtered_vector_search_reads_control_characters_as_written in crates/storage-postgres/tests/catalog_nul_index_writes.rs searches with an equality filter on an inline filter attribute and with a condition. The names and the values hold U+0000 and U+0001. The test checks that the search returns the one item that matches both, as PutItem wrote it. With the filters bound as the request gives them, the search fails with SQLSTATE 22P05 (unsupported Unicode escape sequence). With the items decoded by serde, it returns no item. The new helper vector_table builds the table of this test and of a_vector_index_keeps_its_attribute_names. --- crates/storage-postgres/src/vector_search.rs | 32 ++-- .../src/vector_search_filtered.rs | 21 ++- .../tests/catalog_nul_index_writes.rs | 173 +++++++++++++++--- 3 files changed, 178 insertions(+), 48 deletions(-) diff --git a/crates/storage-postgres/src/vector_search.rs b/crates/storage-postgres/src/vector_search.rs index 8f41424d5..4efd292c8 100644 --- a/crates/storage-postgres/src/vector_search.rs +++ b/crates/storage-postgres/src/vector_search.rs @@ -301,16 +301,22 @@ impl VectorSearchEngine for PostgresEngine { .collect::>() .join(", "); + // The stored item carries the same escape as every other item_data + // column, so the filter's attribute name and value must be compared + // in stored form. + let filters = filters + .iter() + .map(|(name, value)| { + let value_json = crate::catalog_json::to_catalog_json(value)?.to_string(); + Ok(( + extenddb_storage::util::escape_control(name).into_owned(), + value_json, + )) + }) + .collect::, StorageError>>()?; + let score = score_expression(function, 4); if let Some(condition) = &item_filter { - let filters = filters - .iter() - .map(|(name, value)| { - serde_json::to_string(value) - .map(|json| (name.clone(), json)) - .map_err(|e| StorageError::Internal(format!("filter value: {e}"))) - }) - .collect::, _>>()?; let statement = crate::vector_search_filtered::ScanStatement { score, from: format!("FROM {vec_table} WHERE part = $2{predicates}"), @@ -356,14 +362,8 @@ impl VectorSearchEngine for PostgresEngine { .bind(partition.into_bytes()) .bind(top_k) .bind(query_norm); - // The stored item carries the same escape as every other item_data - // column, so the filter's attribute name and value must be compared - // in stored form. - for (name, value) in &filters { - let value_json = crate::catalog_json::to_catalog_json(value)?.to_string(); - query = query - .bind(extenddb_storage::util::escape_control(name).into_owned()) - .bind(value_json); + for (name, value_json) in filters { + query = query.bind(name).bind(value_json); } let rows = query diff --git a/crates/storage-postgres/src/vector_search_filtered.rs b/crates/storage-postgres/src/vector_search_filtered.rs index 3cb37c86f..51ca7c7f0 100644 --- a/crates/storage-postgres/src/vector_search_filtered.rs +++ b/crates/storage-postgres/src/vector_search_filtered.rs @@ -40,7 +40,6 @@ use pgvector::Vector; use sqlx::PgPool; use sqlx::postgres::{PgArguments, Postgres}; use sqlx::query::QueryAs; -use sqlx::types::Json; use extenddb_core::types::Item; use extenddb_storage::VectorItemFilter; @@ -78,7 +77,8 @@ pub(crate) struct ScanStatement { pub(crate) vector: Vector, pub(crate) partition: Vec, pub(crate) norm: f64, - /// Each equality filter's name and its value as JSON text. + /// Each equality filter's name and its value as JSON text, both in the + /// stored form of `item_data`. pub(crate) filters: Vec<(String, String)>, } @@ -156,11 +156,12 @@ async fn offer_page( ); for batch in page.chunks(ITEM_BATCH) { let rids: Vec<&str> = batch.iter().map(|(_, rid)| rid.as_str()).collect(); - let mut items = sqlx::query_as::<_, (i64, Json)>(sqlx::AssertSqlSafe(sql.as_str())) - .bind(rids) - .fetch(scan.connection()); + let mut items = + sqlx::query_as::<_, (i64, serde_json::Value)>(sqlx::AssertSqlSafe(sql.as_str())) + .bind(rids) + .fetch(scan.connection()); let mut position = 0usize; - while let Some((n, Json(item))) = items.try_next().await.map_err(map_sql)? { + while let Some((n, stored)) = items.try_next().await.map_err(map_sql)? { let Some((score, rid)) = batch.get(position) else { return Err(vanished("past the end of the page")); }; @@ -170,6 +171,9 @@ async fn offer_page( return Err(vanished(rid)); } position += 1; + // The condition reads the item as the client wrote it, so the + // stored strings are decoded first. + let item = crate::data::json_to_item(stored)?; if filter.matches(&item)? { kept.push((*score, rid.clone(), item)); if kept.len() == wanted { @@ -196,8 +200,9 @@ fn vanished(rid: &str) -> StorageError { /// /// # Errors /// -/// Returns the mapped statement error, which covers a stored item that does -/// not decode, or the error of [`VectorItemFilter::matches`]. +/// Returns the mapped statement error, [`StorageError::Internal`] for a +/// stored item that does not decode, or the error of +/// [`VectorItemFilter::matches`]. pub(crate) async fn fetch_matching( statement: &ScanStatement, pool: &PgPool, diff --git a/crates/storage-postgres/tests/catalog_nul_index_writes.rs b/crates/storage-postgres/tests/catalog_nul_index_writes.rs index cb4023273..c38888a80 100644 --- a/crates/storage-postgres/tests/catalog_nul_index_writes.rs +++ b/crates/storage-postgres/tests/catalog_nul_index_writes.rs @@ -30,7 +30,10 @@ use extenddb_core::types::{ Item, KeyType, Projection, ProjectionType, SearchSchemaElement, SearchSchemaElementType, TableKeyInfo, UpdateTableInput, VectorAttribute, VectorIndexSpecification, }; -use extenddb_storage::{DataEngine, TableEngine, VectorSearch, VectorSearchEngine}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{ + DataEngine, TableEngine, VectorItemFilter, VectorSearch, VectorSearchEngine, +}; /// The key of the GSI the items carry: a raw U+0001 pair. const GK: &str = "g\u{1}\u{1}k"; @@ -93,6 +96,45 @@ async fn put(s: &Scratch, key_info: &TableKeyInfo, it: Item) { .expect("PutItem"); } +/// A table keyed on `pk` with the vector index `vidx` on `vector`. `schema` +/// is its search schema, and each of its attributes is a string. +fn vector_table( + table: &str, + vector: &str, + schema: &[(&str, SearchSchemaElementType)], +) -> CreateTableInput { + let mut attribute_definitions = vec![s_attr("pk")]; + attribute_definitions.extend(schema.iter().map(|(name, _)| s_attr(name))); + CreateTableInput { + table_name: table.to_owned(), + key_schema: vec![key("pk", KeyType::Hash)], + attribute_definitions, + billing_mode: Some(BillingMode::PayPerRequest), + vector_indexes: Some(vec![VectorIndexSpecification { + index_name: "vidx".to_owned(), + dimensions: 2, + distance_function: DistanceFunction::Cosine, + vector_attribute: VectorAttribute { + attribute_name: vector.to_owned(), + }, + search_schema: Some( + schema + .iter() + .map(|&(name, element_type)| SearchSchemaElement { + attribute_name: name.to_owned(), + element_type, + }) + .collect(), + ), + projection: Some(Projection { + projection_type: ProjectionType::All, + non_key_attributes: None, + }), + }]), + ..Default::default() + } +} + async fn index_id(s: &Scratch, table: &str, index: &str) -> String { sqlx::query_scalar( "SELECT i.index_id FROM indexes i JOIN tables t ON t.table_id = i.table_id \ @@ -282,29 +324,7 @@ async fn a_vector_index_keeps_its_attribute_names() { }; // The vector attribute and the search schema's HASH attribute. let (vector, hash) = ("v\u{1}\u{1}", "t\u{1}\u{2}"); - let input = CreateTableInput { - table_name: "vectors".to_owned(), - key_schema: vec![key("pk", KeyType::Hash)], - attribute_definitions: vec![s_attr("pk"), s_attr(hash)], - billing_mode: Some(BillingMode::PayPerRequest), - vector_indexes: Some(vec![VectorIndexSpecification { - index_name: "vidx".to_owned(), - dimensions: 2, - distance_function: DistanceFunction::Cosine, - vector_attribute: VectorAttribute { - attribute_name: vector.to_owned(), - }, - search_schema: Some(vec![SearchSchemaElement { - attribute_name: hash.to_owned(), - element_type: SearchSchemaElementType::Hash, - }]), - projection: Some(Projection { - projection_type: ProjectionType::All, - non_key_attributes: None, - }), - }]), - ..Default::default() - }; + let input = vector_table("vectors", vector, &[(hash, SearchSchemaElementType::Hash)]); s.engine .create_table(ACCOUNT, input) .await @@ -378,3 +398,108 @@ async fn a_vector_index_keeps_its_attribute_names() { found.hits[0].item ); } + +/// The condition of a filtered search: the item's `note` equals a value. +struct NoteIs(AttributeValue); + +impl VectorItemFilter for NoteIs { + fn matches(&self, item: &Item) -> Result { + Ok(item.get("note") == Some(&self.0)) + } +} + +/// A search with a condition reads the rows in pages and evaluates the +/// condition in this process. Its equality filter on an inline filter +/// attribute, the condition and the item it returns all see the strings as +/// written, with U+0000 and U+0001 in the names and the values. +#[tokio::test] +async fn a_filtered_vector_search_reads_control_characters_as_written() { + let test = "a_filtered_vector_search_reads_control_characters_as_written"; + if base_conn().is_none() { + return skip(test); + } + let options = Options { + pgvector: true, + ..Options::default() + }; + let Some(s) = scratch(test, options).await else { + return; + }; + // The vector attribute, the HASH attribute and the inline filter. + let (vector, hash, tag) = ("v\u{1}\u{1}", "t\u{1}\u{2}", "f\u{1}"); + let schema = [ + (hash, SearchSchemaElementType::Hash), + (tag, SearchSchemaElementType::InlineFilter), + ]; + let input = vector_table("filtered", vector, &schema); + s.engine + .create_table(ACCOUNT, input) + .await + .expect("CreateTable with a vector index"); + let key_info = s + .engine + .table_key_info(ACCOUNT, "filtered") + .await + .expect("table_key_info"); + let tenant = AttributeValue::S("a".to_owned()); + let (wanted_tag, wanted_note) = ( + AttributeValue::S("x\u{0}\u{1}".to_owned()), + AttributeValue::S("n\u{0}\u{1}\u{2}".to_owned()), + ); + let (other_tag, other_note) = ( + AttributeValue::S("x".to_owned()), + AttributeValue::S("n".to_owned()), + ); + // p1 matches. p2 fails the condition and p3 the equality filter. + let rows = [ + ("p1", &wanted_tag, &wanted_note, "0"), + ("p2", &wanted_tag, &other_note, "0.1"), + ("p3", &other_tag, &wanted_note, "0.2"), + ]; + let mut written = BTreeMap::new(); + for (pk, tag_value, note, y) in rows { + let it: Item = BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(pk.to_owned())), + (hash.to_owned(), tenant.clone()), + (tag.to_owned(), tag_value.clone()), + ("note".to_owned(), note.clone()), + ( + "m\u{0}".to_owned(), + AttributeValue::M(BTreeMap::from([( + "k\u{1}".to_owned(), + AttributeValue::S("\u{0}".to_owned()), + )])), + ), + ( + vector.to_owned(), + AttributeValue::L(vec![ + AttributeValue::N("1".to_owned()), + AttributeValue::N(y.to_owned()), + ]), + ), + ]); + written.insert(pk, it.clone()); + put(&s, &key_info, it).await; + } + let found = s + .engine + .search_vectors(VectorSearch { + key_info: &key_info, + index_name: "vidx", + query_vector: &[1.0, 0.0], + top_k: 5, + hash_key: Some((hash, &tenant)), + filters: &[(tag, &wanted_tag)], + item_filter: Some(std::sync::Arc::new(NoteIs(wanted_note.clone()))), + }) + .await + .expect("SearchVectors with a condition"); + assert_eq!(found.hits.len(), 1, "{:?}", found.hits); + // The search puts the vector back from the stored f32s, so the rest of + // the item is compared with what PutItem wrote. + let mut got = found.hits[0].item.clone(); + assert!(got.remove(vector).is_some(), "{got:?}"); + let mut want = written["p1"].clone(); + want.remove(vector); + assert_eq!(got, want); +}