diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a5c416ea5..d51327078 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -402,29 +402,30 @@ SQLite, PostgreSQL, Cassandra and MongoDB migrate through this framework. ### Example: a nullable column on `tables` -Migration 13, `table_note` (13 being the next free id at the time of writing; -migrations 6, 7, 8, 9, 10, 11 and 12 are `backup_catalog_index`, +Migration 14, `table_note` (14 being the next free id at the time of writing; +migrations 6, 7, 8, 9, 10, 11, 12 and 13 are `backup_catalog_index`, `stream_pending`, `restore_progress`, `warm_throughput`, `account_metrics`, -`attribute_name_escape` and `unique_access_key_ids`), adds a nullable -`note TEXT` column to the catalog's `tables` table on SQLite and PostgreSQL. +`attribute_name_escape`, `unique_access_key_ids` and `escape_control_chars`), +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 `migration_ids!` list: ```rust /// Adds a nullable `note` column to the `tables` catalog table. - TableNote = 13, "table_note", + TableNote = 14, "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/0013_table_note.sql`: +`crates/storage-postgres/migrations/0014_table_note.sql`: ```sql -- Copyright 2026 ExtendDB contributors -- SPDX-License-Identifier: Apache-2.0 -- --- Migration 13, table_note, PostgreSQL catalog database: a nullable note +-- Migration 14, 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; @@ -439,7 +440,7 @@ In `crates/storage-postgres/src/migrations/mod.rs`, the arm in `migration()`: bodies: vec![file_body!( StoreKind::Catalog, "migrations", - "0013_table_note.sql" + "0014_table_note.sql" )], }, ``` @@ -458,19 +459,20 @@ and the id in the transactional arm of `runs_in()`: | MigrationId::AccountMetrics | MigrationId::AttributeNameEscape | MigrationId::UniqueAccessKeyIds + | MigrationId::EscapeControlChars | MigrationId::TableNote => RunsIn::Transaction, ``` 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/m0013_table_note.rs`: +`crates/storage-sqlite/src/migrations/m0014_table_note.rs`: ```rust // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Migration 13, `table_note`, SQLite: a nullable `note` column on `tables`. +//! Migration 14, `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 @@ -482,10 +484,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!("m0013_table_note.rs"); +pub(crate) const SOURCE: &str = include_str!("m0014_table_note.rs"); /// Recorded as this migration's checksum. Changes only with a new migration. -const FINGERPRINT: &str = "0013_table_note/sqlite/1"; +const FINGERPRINT: &str = "0014_table_note/sqlite/1"; pub(crate) struct TableNote; @@ -524,7 +526,7 @@ beside the others: ```rust #[rustfmt::skip] #[allow(clippy::all, deprecated)] -mod m0013_table_note; +mod m0014_table_note; ``` and the arm in `migration()`: @@ -535,8 +537,8 @@ and the arm in `migration()`: convergent: true, bodies: vec![StoreBody::code( StoreKind::Catalog, - &m0013_table_note::TableNote, - m0013_table_note::SOURCE, + &m0014_table_note::TableNote, + m0014_table_note::SOURCE, )], }, ``` @@ -548,8 +550,8 @@ rows of `tables`: ```rust #[tokio::test] -async fn migration_13_adds_the_note_column_to_tables() { - let db = temp_db("m13"); +async fn migration_14_adds_the_note_column_to_tables() { + let db = temp_db("m14"); load_dump(&db, DEV_0_1_14).await; run(&db).await.expect("migrate"); let mut text = dump( @@ -559,12 +561,12 @@ async fn migration_13_adds_the_note_column_to_tables() { ) .await; text.push_str(&dump(&db, "SELECT table_name, note FROM tables ORDER BY table_name").await); - golden("0013_table_note", &text); + golden("0014_table_note", &text); } ``` -`EXTENDDB_BLESS_EXPECTED=1 cargo test -p extenddb-storage-sqlite --lib migration_13` -writes `crates/storage-sqlite/tests/fixtures/golden/0013_table_note.txt`, one +`EXTENDDB_BLESS_EXPECTED=1 cargo test -p extenddb-storage-sqlite --lib migration_14` +writes `crates/storage-sqlite/tests/fixtures/golden/0014_table_note.txt`, one tab-separated line per row under each query: ``` @@ -579,15 +581,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 13 refuse a catalog that has it, and a rollback restores the +without migration 14 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 13, and on a catalog at -migration 12 `extenddb migrate` lists migration 13 as pending and exits 3. +entry. `extenddb migrate --list` then shows migration 14, and on a catalog at +migration 13 `extenddb migrate` lists migration 14 as pending and exits 3. ### Running the migration tests diff --git a/crates/storage-cassandra/src/migrations/mod.rs b/crates/storage-cassandra/src/migrations/mod.rs index ee6a31ab6..2b19b7ff2 100644 --- a/crates/storage-cassandra/src/migrations/mod.rs +++ b/crates/storage-cassandra/src/migrations/mod.rs @@ -314,6 +314,10 @@ pub fn migration(id: MigrationId) -> Migration { "access_key_id is the primary key of access_keys, and an import writes with IF NOT \ EXISTS, so an ID can be stored once", ), + 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/backup_engine.rs b/crates/storage-mongodb/src/backup_engine.rs index 149adcd15..3d9bb67ab 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,14 @@ 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, with the + /// 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, account_id: &str, @@ -2028,7 +2031,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 +2080,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; +} diff --git a/crates/storage-mongodb/src/data/mod.rs b/crates/storage-mongodb/src/data/mod.rs index d1678862a..1e9ba94fe 100644 --- a/crates/storage-mongodb/src/data/mod.rs +++ b/crates/storage-mongodb/src/data/mod.rs @@ -15,7 +15,10 @@ 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, needs_escape, 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 +37,95 @@ pub fn composite_id(pk_text: &str, sk_text: &str) -> String { encode_netstring_composite(&[pk_text.to_owned(), sk_text.to_owned()]) } +/// 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. 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 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(()) +} + +/// 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 field-name escape undone when the document is marked +/// (`escaped`). +/// +/// 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(if escaped { + unescape_json_keys(json) + } else { + 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,11 +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 - 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()))?; - let mut doc = Document::new(); // Build the _id field @@ -69,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) } @@ -194,10 +283,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()))?; - doc.insert("item_data", item_bson); + insert_item_data(&mut doc, projected)?; Ok(doc) } @@ -256,8 +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: 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, names_escaped(doc))?; let item: Item = serde_json::from_value(json_value) .map_err(|e| StorageError::Internal(format!("JSON to Item conversion error: {e}")))?; @@ -436,6 +521,140 @@ 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())); + 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; + + 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(); + 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"]); + 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 6ecfc7f29..1c5eceacc 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, 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,10 @@ 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 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 { return None; @@ -884,8 +887,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() @@ -1819,7 +1823,15 @@ 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. 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()?; + if names_need_escape(&val_json) { + return None; + } let val_bson = bson::to_bson(&val_json).ok()?; set_doc.insert(field, val_bson); } @@ -2239,8 +2251,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 + // 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 @@ -2248,16 +2262,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)?; @@ -4726,6 +4744,43 @@ transaction_read_concern = "majority""#, assert_eq!(native_attribute_name(&path, &maps), None); } + #[test] + fn native_update_rejects_control_character_literal_attribute_names() { + // 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()); + 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_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 aa87f8480..2f379ba0d 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 a7f4e7e01..f6df0c8fb 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 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. 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,12 @@ 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 +/// 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('$') + !name.contains('.') && !name.starts_with('$') && !needs_escape(name) } /// Whether every key attribute of `key_schema` is a plain path name, so that @@ -173,4 +181,26 @@ mod tests { ); } } + + #[test] + fn a_key_name_with_u0000_or_u0001_leaves_the_native_upsert() { + // 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 + )]))); + 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/migrations/mod.rs b/crates/storage-mongodb/src/migrations/mod.rs index 238e43da6..e79674e37 100644 --- a/crates/storage-mongodb/src/migrations/mod.rs +++ b/crates/storage-mongodb/src/migrations/mod.rs @@ -326,6 +326,11 @@ pub fn migration(id: MigrationId) -> Migration { m0012_unique_access_key_ids::SOURCE, )], }, + MigrationId::EscapeControlChars => Migration::NotApplicable( + "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 616ef7508..57158d6b3 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 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 { @@ -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,42 @@ mod tests { ); } + #[test] + fn nul_attribute_name_is_not_pushable() { + // 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, + 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_engine.rs b/crates/storage-mongodb/src/stream_engine.rs index ea19158a9..504a01fd5 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 c84bbadf9..045b1afb7 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,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()))?; - let json_val: serde_json::Value = - bson::from_bson(record_bson).map_err(|e| StorageError::Internal(e.to_string()))?; + // 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, crate::data::names_escaped(&d))?; serde_json::from_value(json_val).map_err(|e| StorageError::Internal(e.to_string())) }) .collect() diff --git a/crates/storage-mongodb/tests/migrations_fresh.rs b/crates/storage-mongodb/tests/migrations_fresh.rs index fbeb3760c..79d463011 100644 --- a/crates/storage-mongodb/tests/migrations_fresh.rs +++ b/crates/storage-mongodb/tests/migrations_fresh.rs @@ -328,6 +328,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { (10, d.target.catalog.clone()), (11, d.target.catalog.clone()), (12, d.target.catalog.clone()), + (13, d.target.catalog.clone()), ] ); let not_applicable: Vec = report @@ -336,7 +337,7 @@ 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, 7, 8, 9, 11], "{report:?}"); + assert_eq!(not_applicable, [3, 4, 7, 8, 9, 11, 13], "{report:?}"); assert_eq!( d.status().await, CatalogStatus::Current { @@ -360,6 +361,7 @@ async fn a_fresh_store_gets_every_migration_and_the_expected_definitions() { (10, Outcome::Applied), (11, Outcome::NotApplicable), (12, Outcome::Applied), + (13, Outcome::NotApplicable), ] ); assert!( @@ -471,7 +473,7 @@ async fn a_second_run_applies_nothing_and_reconverge_keeps_the_rows() { let reconverged = d.reconverge().await.expect("reconverge"); // Migration 1's steps in the catalog and the data database, and // migrations 5's, 6's, 10's and 12's in the catalog: 2 is not - // convergent, and 3, 4, 7, 8, 9 and 11 do not apply on MongoDB. + // convergent, and 3, 4, 7, 8, 9, 11 and 13 do not apply on MongoDB. let ran: Vec<(u32, String)> = reconverged .applied .iter() @@ -627,24 +629,24 @@ async fn a_changed_checksum_a_newer_catalog_and_an_older_release_are_reported() "notes": "", "applied_at": bson::DateTime::now(), "applied_by": "9.9.9" } }; ledger - .insert_one(row(13, "breaking")) + .insert_one(row(14, "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": 13_i64 }) + .delete_one(doc! { "_id": 14_i64 }) .await .expect("delete"); ledger - .insert_one(row(13, "additive")) + .insert_one(row(14, "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": 13_i64 }) + .delete_one(doc! { "_id": 14_i64 }) .await .expect("delete"); @@ -725,6 +727,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(), 12); + assert_eq!(MigrationId::LATEST.number(), 13); d.drop_databases().await; } diff --git a/crates/storage-mongodb/tests/migrations_locks.rs b/crates/storage-mongodb/tests/migrations_locks.rs index afc0d9734..e23eb051f 100644 --- a/crates/storage-mongodb/tests/migrations_locks.rs +++ b/crates/storage-mongodb/tests/migrations_locks.rs @@ -53,7 +53,7 @@ async fn two_migrators_started_together_apply_once_and_the_other_finds_nothing() applied.sort_unstable(); assert_eq!( applied, - [0, 13], + [0, 14], "one applies every step and the other finds nothing" ); assert_eq!( diff --git a/crates/storage-mongodb/tests/migrations_released.rs b/crates/storage-mongodb/tests/migrations_released.rs index 7d85097ac..02a2d6219 100644 --- a/crates/storage-mongodb/tests/migrations_released.rs +++ b/crates/storage-mongodb/tests/migrations_released.rs @@ -163,7 +163,7 @@ 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(), 13, "{state}"); + assert_eq!(pending.len(), 14, "{state}"); let report = d.migrate().await.expect("migrate"); assert_eq!( (report.from, report.to), diff --git a/crates/storage-postgres/src/backup_engine.rs b/crates/storage-postgres/src/backup_engine.rs index 92442c540..564f5b214 100755 --- a/crates/storage-postgres/src/backup_engine.rs +++ b/crates/storage-postgres/src/backup_engine.rs @@ -31,8 +31,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::{BackupRestoreSource, JobPermit, LegacyBackupReader, RestoreRequest}; use futures::future::BoxFuture; @@ -40,9 +39,10 @@ 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, 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, project_item_for_index, table_storage_relations, + item_has_index_keys, json_to_item, project_item_for_index, table_storage_relations, }; /// Convert a `PostgreSQL` `TIMESTAMPTZ` to epoch seconds as `f64`, keeping the @@ -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, @@ -790,8 +794,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(); @@ -1510,8 +1520,10 @@ impl LegacyBackupReader for PostgresEngine { sqlx::query_as::<_, (String, String)>(sqlx::AssertSqlSafe(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); @@ -2248,8 +2260,10 @@ async fn send_legacy_items( loop { match rows.try_next().await { Ok(Some(item_json)) => { - let item = serde_json::from_str::(&item_json) - .map_err(|e| StorageError::Internal(format!("Parse backup item: {e}"))); + // The stored form carries the escape of `data::item_to_json`. + let item = serde_json::from_str(&item_json) + .map_err(|e| StorageError::Internal(format!("Parse backup item: {e}"))) + .and_then(json_to_item); let parsed = item.is_ok(); if sender.send(item).await.is_err() || !parsed { break None; diff --git a/crates/storage-postgres/src/catalog_json.rs b/crates/storage-postgres/src/catalog_json.rs index f19805c2d..27727d56e 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`, @@ -36,21 +38,22 @@ //! 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 not written through this module. +//! 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 +//! (`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. 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 +68,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 +144,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/data/data_engine.rs b/crates/storage-postgres/src/data/data_engine.rs index 88dd03794..c698c37a1 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 { diff --git a/crates/storage-postgres/src/data/delete_item.rs b/crates/storage-postgres/src/data/delete_item.rs index 3f470dd3f..b941750ff 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 f69b0f1a7..a43c9b207 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::catalog_json::from_catalog_json; use crate::gsi_queue::{GsiApplyContext, GsiIndexDef, PendingApplyContext, enqueue_gsi_pending}; @@ -281,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], @@ -301,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() } @@ -1434,6 +1440,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/index.rs b/crates/storage-postgres/src/data/index.rs index 297a1a533..2657c46ca 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::catalog_json::from_catalog_json; use crate::gsi_queue::{GsiApplyContext, GsiIndexDef, enqueue_gsi_pending}; @@ -569,9 +571,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..b37fe3884 --- /dev/null +++ b/crates/storage-postgres/src/data/key_text.rs @@ -0,0 +1,194 @@ +// 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. 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 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, ScalarAttributeType}; +use extenddb_storage::error::StorageError; +use extenddb_storage::util::{self, SortKeyValue}; + +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> { + let text = util::pk_to_text(value)?; + refuse_nul(&text)?; + Ok(text) +} + +/// 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 text = util::composite_pk_to_text(item, key_schema)?; + refuse_nul(&text)?; + Ok(text) +} + +/// 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) +} + +/// 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')), + ) +} + +/// 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(()) +} + +/// 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, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + 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 a_string_key_with_u0000_is_refused() { + assert_eq!( + refused(pk_to_text(&AttributeValue::S("a\u{0}b".into()))), + MESSAGE + ); + assert_eq!( + refused(parse_sk( + &AttributeValue::S("\u{0}".into()), + ScalarAttributeType::S + )), + MESSAGE + ); + let mut item = Item::new(); + 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 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!( + pk_to_text(&value).unwrap(), + util::pk_to_text(&value).unwrap(), + "{value:?}" + ); + } + 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"), + } + 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, &schema).unwrap(), + "2:a\u{1},1:b," + ); + // 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/mod.rs b/crates/storage-postgres/src/data/mod.rs index bd3c3a543..fdcb962f2 100755 --- a/crates/storage-postgres/src/data/mod.rs +++ b/crates/storage-postgres/src/data/mod.rs @@ -10,6 +10,8 @@ use extenddb_core::types::{AttributeDefinition, Item, KeySchemaElement, ScalarAttributeType}; use extenddb_storage::error::StorageError; +use crate::catalog_json::{from_catalog_json, to_catalog_json}; + /// Prefix of every data relation this backend creates for a table: the base /// table, its secondary indexes and its vector indexes. It keeps them apart /// from the catalog's tables and the data database's queue tables, and it is @@ -68,8 +70,22 @@ 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())) + from_catalog_json(v) +} + +/// 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 { + to_catalog_json(item) } /// Bind a `SortKeyValue` to a positional parameter in a sqlx query and execute it. @@ -143,6 +159,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 e43f8f75e..cc54217bc 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, refuse_nul_index_keys}; 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). @@ -73,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/query.rs b/crates/storage-postgres/src/data/query.rs index f76b13ae4..fcd10d312 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, string_prefix_upper_bound}; +use extenddb_storage::util::{sk_info, string_prefix_upper_bound}; + +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 4330aadbe..0b40c1ac9 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/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/tx_helpers.rs b/crates/storage-postgres/src/data/tx_helpers.rs index 20aec04ef..2573e24ba 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}; /// 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) { @@ -164,8 +164,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) @@ -455,9 +454,10 @@ pub(super) async fn write_stream_record_to_shard_in_tx( // batch adds up that length (`NUMBER_BATCH_BYTES` in stream_engine.rs). // 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. - let record_text = - serde_json::to_string(&record).map_err(|e| StorageError::Internal(e.to_string()))?; + // compressed size. The text is that of the stored form + // (`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/data/update_item.rs b/crates/storage-postgres/src/data/update_item.rs index 375c95fbc..450db69df 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, refuse_nul_index_keys}; 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}; @@ -232,6 +235,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 @@ -244,8 +248,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 8646e1f23..33f2ce62f 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}; use crate::catalog_json::from_catalog_json; /// Read the vector index metadata for a table from the catalog. @@ -405,8 +405,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 11edd4939..113cb44c5 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; @@ -324,17 +324,11 @@ 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 old_json = old_item.map(crate::data::item_to_json).transpose()?; + let new_json = new_item.map(crate::data::item_to_json).transpose()?; // The context carries attribute names, so it is stored in the form of the // catalog documents it was read from (`catalog_json`); the item images - // are item data and are not. + // are stored in the form of `item_data` (`item_to_json`). let context_json = to_catalog_json(context)?; // Route all updates for a given base item to one worker. @@ -590,14 +584,8 @@ 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 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 = from_catalog_json(ctx_json)?; Ok((old_item, new_item, context)) } diff --git a/crates/storage-postgres/src/migrations/backend.rs b/crates/storage-postgres/src/migrations/backend.rs index e4ba2a5f1..666c4bc56 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 13'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 { @@ -102,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. @@ -239,6 +260,7 @@ impl PostgresMigrations { data_watch: None, lock, application, + checks_sessions: false, }, catalog_name, data_name: String::new(), @@ -322,6 +344,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/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/guard.rs b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs new file mode 100644 index 000000000..072b87b7a --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/guard.rs @@ -0,0 +1,135 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The sessions check of migration 13'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(sqlx::AssertSqlSafe(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`, `stream_records` or `stream_pending` holds a row. +/// `stream_pending` is missing while migration 7 is pending in the same run. +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? + || has_row(data, "stream_pending").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 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 \ + {IGNORE_CONNECTIONS_ENV}=1 to skip this check", + others.len(), + described.join("; ") + )]) +} 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 new file mode 100644 index 000000000..5192169de --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0013_escape_control_chars/mod.rs @@ -0,0 +1,400 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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 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.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 +//! 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. +//! +//! 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. +//! +//! 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; + +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}; + +/// 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!("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; + +/// The data body: the data, index and vector index tables, the item images +/// of `gsi_pending`, `stream_records` and `stream_pending`. +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`, `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()); + } + 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, +/// 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}: {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: the jsonb columns that hold its item +/// documents. +struct EscapeWork { + /// Bare (unquoted) table name, e.g. `_ddb_` or `gsi_pending`. + table: String, + 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 notes name a table. + fn label(&self) -> String { + match &self.ddb_name { + Some(ddb) => format!("{} ({ddb})", self.table), + None => self.table.clone(), + } + } +} + +/// 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, + names: &[&str], +) -> Result, MigrationError> { + 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 = 'jsonb' \ + AND column_name::text = ANY($2) \ + ORDER BY ordinal_position", + ) + .bind(table) + .bind(names) + .fetch_all(&mut *conn) + .await + .map_err(|e| db_error(&format!("list the jsonb columns of {table}"), &e)) +} + +/// 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, + names: &[&str], + ddb_name: Option, +) -> Result, MigrationError> { + let columns = jsonb_columns(conn, table, names).await?; + Ok((!columns.is_empty()).then(|| EscapeWork { + table: table.to_owned(), + columns, + ddb_name, + })) +} + +/// The re-encoded form of a stored jsonb value, or `None` when re-encoding +/// 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 = escape::escape_document(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(sqlx::AssertSqlSafe(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(sqlx::AssertSqlSafe(fetch_batch.as_str())) + .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(sqlx::AssertSqlSafe(update_row.as_str())) + .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 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 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())); + } + } + Ok(()) +} + +/// The catalog body on `conn`, the catalog database in the runner's +/// transaction. +pub(crate) async fn escape_catalog(conn: &mut PgConnection) -> Result, MigrationError> { + let mut notes = Vec::new(); + 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`. +pub(crate) async fn escape_data( + catalog: &PgPool, + conn: &mut PgConnection, +) -> Result, MigrationError> { + let mut notes = Vec::new(); + let mut work: Vec = Vec::new(); + + 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) + .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(); + // 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}"))) + .collect(); + let ddb_table = |table_id: &str| { + ddb_tables + .get(table_id) + .cloned() + .unwrap_or_else(|| format!("table id {table_id}")) + }; + + // 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))?; + 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\"", + ) + .fetch_all(catalog) + .await + .map_err(|e| db_error("list vector indexes", &e))?; + 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. + // 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, 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?; + Ok(notes) +} diff --git a/crates/storage-postgres/src/migrations/m0013_guard_tests.rs b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs new file mode 100644 index 000000000..337ceab9a --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0013_guard_tests.rs @@ -0,0 +1,269 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 13's sessions check (`other_sessions`, which both +//! bodies' `detect` call), with the scratch database and the skip convention +//! 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::{ + EscapeBackupItems, IGNORE_CONNECTIONS_ENV, catalog_has_rows, data_has_rows, other_sessions, +}; +use super::m0013_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(sqlx::AssertSqlSafe(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(sqlx::AssertSqlSafe(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. +/// 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() { + 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()); + // A store whose only counted row is a stream record waiting for its + // 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( + "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())", + ) + .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()); + 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_tests.rs b/crates/storage-postgres/src/migrations/m0013_tests.rs new file mode 100644 index 000000000..0fea77034 --- /dev/null +++ b/crates/storage-postgres/src/migrations/m0013_tests.rs @@ -0,0 +1,619 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live checks of migration 13'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::m0013_escape_control_chars::{escape_catalog, escape_data}; + +/// The `application_name` of the scratch pools: a runner's, so the sessions +/// check of migration 13 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(sqlx::AssertSqlSafe(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(sqlx::AssertSqlSafe(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, 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"}, + {"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"); + 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" ( + 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) + ); + 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, 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(sqlx::AssertSqlSafe(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 [ + ( + "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"); + } + 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, \ + 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 13"); + assert_eq!( + notes, + vec![ + "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 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) + .await + .expect("read the data table"); + assert_eq!( + rows, + vec![ + ( + "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}"}}), + ), + ( + "lit".to_owned(), + "s".to_owned(), + json!({"note": {"S": "x\\u0001y"}}), + ), + ( + "plain".to_owned(), + "s".to_owned(), + json!({"pk": {"S": "plain"}}), + ), + ] + ); + + // 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", + ) + .fetch_all(&s.db) + .await + .expect("read the index table"); + assert_eq!( + rows, + vec![ + ( + "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}"}}), + ), + ( + "zz".to_owned(), + "zs".to_owned(), + "plain".to_owned(), + "s".to_owned(), + json!({"gpk": {"S": "zz"}}), + ), + ] + ); + + // 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(sqlx::AssertSqlSafe(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. + 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}": 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"}}}),), + ] + ); + + // 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: 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) + .await + .expect("read backup_items"); + assert_eq!( + rows, + vec![ + ( + "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"}}),), + ] + ); + + 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 13"); + + 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}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}"}}), + "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 dd37a1d5c..cd5878899 100644 --- a/crates/storage-postgres/src/migrations/mod.rs +++ b/crates/storage-postgres/src/migrations/mod.rs @@ -39,6 +39,9 @@ mod m0004_index_table_base_key; #[rustfmt::skip] #[allow(clippy::all, deprecated)] mod m0011_attribute_name_escape; +#[rustfmt::skip] +#[allow(clippy::all, deprecated)] +mod m0013_escape_control_chars; mod postcheck; mod registrar; mod rows; @@ -356,6 +359,24 @@ pub fn migration(id: MigrationId) -> Migration { MigrationId::UniqueAccessKeyIds => Migration::NotApplicable( "access_key_id is the primary key of access_keys, so an ID can be stored once", ), + 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, + &m0013_escape_control_chars::EscapeBackupItems, + m0013_escape_control_chars::SOURCE, + ), + StoreBody::code( + StoreKind::Data, + &m0013_escape_control_chars::EscapeDataRows, + m0013_escape_control_chars::SOURCE, + ), + ], + }, } } @@ -384,7 +405,8 @@ pub(crate) const fn runs_in(id: MigrationId) -> RunsIn { | MigrationId::WarmThroughput | MigrationId::AccountMetrics | MigrationId::AttributeNameEscape - | MigrationId::UniqueAccessKeyIds => RunsIn::Transaction, + | MigrationId::UniqueAccessKeyIds + | MigrationId::EscapeControlChars => RunsIn::Transaction, MigrationId::IndexTableBaseKey => RunsIn::Autocommit, } } @@ -417,6 +439,9 @@ pub struct PostgresTarget { /// Whether a status read covers the catalog store alone, reaching no /// data database ([`PostgresMigrations::open_for_status`]). pub(crate) catalog_store_alone: bool, + /// Whether a run leaves out migration 13's check for other sessions + /// ([`PostgresTarget::with_other_sessions_allowed`]). + pub(crate) other_sessions_allowed: bool, } /// What opens the `data_database_connection_string` row of a catalog with a @@ -473,9 +498,21 @@ impl PostgresTarget { connect_timeout: Duration::from_secs(10), data_key: DataKey::None, catalog_store_alone: false, + other_sessions_allowed: false, } } + /// Leave out migration 13'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 + } + /// Open the connection string row of a catalog with a key ring with the /// key the command read: a KEK, which unwraps the ring at each read. The /// catalog key and no key open no such row. `plaintext_during_switch` is @@ -671,8 +708,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, ) @@ -681,5 +719,9 @@ pub async fn apply_all_migrations( .map_err(|e| format!("{e:?}")) } +#[cfg(test)] +mod m0013_guard_tests; +#[cfg(test)] +mod m0013_tests; #[cfg(test)] mod tests; diff --git a/crates/storage-postgres/src/restore_engine.rs b/crates/storage-postgres/src/restore_engine.rs index 5434bc9dd..21b5a927a 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; 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}")) @@ -162,8 +162,9 @@ impl RestoreEngine for PostgresEngine { let mut applied: u64 = 0; while let Some(item) = items.next().await { let item = item?; - let item_json = serde_json::to_string(&item) - .map_err(|e| StorageError::Internal(format!("item: {e}")))?; + // The stored form of the item, which `insert_restore_rows` + // writes to `item_data` as it is (`data::item_to_json`). + let item_json = item_to_json(&item)?.to_string(); batch_bytes += item_json.len(); batch.push((item, item_json)); if batch.len() == COPY_BATCH_ITEMS || batch_bytes >= COPY_BATCH_BYTES { diff --git a/crates/storage-postgres/src/snapshot_engine.rs b/crates/storage-postgres/src/snapshot_engine.rs index 2a6c3e51d..f05e1e9cd 100644 --- a/crates/storage-postgres/src/snapshot_engine.rs +++ b/crates/storage-postgres/src/snapshot_engine.rs @@ -930,8 +930,7 @@ async fn fetch_page( } let data: String = row.try_get("item").map_err(|e| db_err(&e))?; drop(row); - let item = serde_json::from_str::(&data) - .map_err(|e| StorageError::Internal(format!("Parse item: {e}")))?; + let item = decode_row(&data)?; page.row_bytes.push(data.len()); drop(data); page.items.push(item); @@ -1076,6 +1075,16 @@ fn keyset_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 @@ -1231,4 +1240,23 @@ mod tests { "{after}" ); } + + #[test] + fn a_row_decodes_to_the_item_it_stores() { + use extenddb_core::types::AttributeValue; + + 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 2736442f3..27f1edfbf 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -521,9 +521,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::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 b0d7d2031..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,9 +362,7 @@ impl VectorSearchEngine for PostgresEngine { .bind(partition.into_bytes()) .bind(top_k) .bind(query_norm); - for (name, value) in &filters { - let value_json = serde_json::to_string(value) - .map_err(|e| StorageError::Internal(format!("filter value: {e}")))?; + for (name, value_json) in filters { query = query.bind(name).bind(value_json); } @@ -369,7 +373,7 @@ impl VectorSearchEngine for PostgresEngine { let mut hits = Vec::with_capacity(rows.len()); for (ordered, embedding, item_json) in rows { - let item: extenddb_core::types::Item = serde_json::from_value(item_json) + let item: extenddb_core::types::Item = crate::data::json_to_item(item_json) .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; hits.push(hit( item, 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/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index 706458491..622622207 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -2748,6 +2748,11 @@ async fn a_definition_read_that_loses_its_connection_is_transient() { s.cleanup().await; } +// --- U+0000 and U+0001 in restored keys, indexes and items ---------------------- + +#[path = "backup_restore/control_chars.rs"] +mod control_chars; + // --- the catalog index ----------------------------------------------------------- /// A catalog row for a backup of `table` in `account` minted now, with the diff --git a/crates/storage-postgres/tests/backup_restore/control_chars.rs b/crates/storage-postgres/tests/backup_restore/control_chars.rs new file mode 100644 index 000000000..a26804533 --- /dev/null +++ b/crates/storage-postgres/tests/backup_restore/control_chars.rs @@ -0,0 +1,178 @@ +// 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 +/// 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(sqlx::AssertSqlSafe(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+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 (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() { + 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 mut items: Vec = [ + serde_json::json!({ + "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{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"}}), + ] + .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 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(sqlx::AssertSqlSafe(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()) + .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"); + 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 kept its text and every 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; +} 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 679109766..c38888a80 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. @@ -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 \ @@ -114,8 +156,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(); @@ -281,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 @@ -377,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); +} 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 new file mode 100644 index 000000000..d7bc17052 --- /dev/null +++ b/crates/storage-postgres/tests/fixtures/golden/0013_escape_control_chars.txt @@ -0,0 +1,66 @@ +_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: 10 row update(s) +data notes: +_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 ffd6c6e0a..24d546e87 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, golden, id_names, notes, skip}; use sqlx::PgPool; @@ -400,3 +400,286 @@ 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(sqlx::AssertSqlSafe(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 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`. 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 { + return skip("golden 13"); + }; + let s = Scratch::new(&base, "pgm_g13").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::UniqueAccessKeyIds).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(sqlx::AssertSqlSafe(format!( + "UPDATE \"{table}\" SET {}, item_data = {LEGACY_NOTE}", + keys.join(", ") + ))) + .execute(&data) + .await + .unwrap(); + } + sqlx::query(sqlx::AssertSqlSafe(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, 13).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("0013_escape_control_chars.txt", &out); + catalog.close().await; + data.close().await; +} + +/// The id-13 rows of the ledger of the database `pool` reaches. +async fn ledger_rows_of_13(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM extenddb_migrations WHERE id = 13") + .fetch_one(pool) + .await + .unwrap() +} + +/// A partition key of 2046 bytes, within the service's 2048, made of letters +/// 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(ALNUM[(state % 62) as usize])); + 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(sqlx::AssertSqlSafe(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(sqlx::AssertSqlSafe(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. +#[tokio::test] +async fn migration_13_stops_before_any_write_while_another_session_holds_the_data() { + let Some(base) = base_conn() else { + return skip("migration 13 sessions check"); + }; + let s = Scratch::new(&base, "pgm_g13s").await; + s.load("0.1.14").await; + s.migrate_through(MigrationId::UniqueAccessKeyIds).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_13(&catalog).await, + 0, + "the refused run wrote the catalog ledger" + ); + assert_eq!( + ledger_rows_of_13(&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_name_escape.rs b/crates/storage-postgres/tests/migrations_name_escape.rs index ecc468d6e..53133a2eb 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}; @@ -339,6 +340,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/crates/storage-postgres/tests/migrations_support/mod.rs b/crates/storage-postgres/tests/migrations_support/mod.rs index 633216b83..9f4359a78 100644 --- a/crates/storage-postgres/tests/migrations_support/mod.rs +++ b/crates/storage-postgres/tests/migrations_support/mod.rs @@ -215,7 +215,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 13'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 13'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-postgres/tests/restore_job.rs b/crates/storage-postgres/tests/restore_job.rs index 2b00bc3a7..c91f87f02 100644 --- a/crates/storage-postgres/tests/restore_job.rs +++ b/crates/storage-postgres/tests/restore_job.rs @@ -1799,3 +1799,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..af38479b4 --- /dev/null +++ b/crates/storage-postgres/tests/restore_job/control_chars.rs @@ -0,0 +1,52 @@ +// 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+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") { + 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{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}"}}} + }); + 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(sqlx::AssertSqlSafe(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; +} diff --git a/crates/storage-postgres/tests/table_snapshot.rs b/crates/storage-postgres/tests/table_snapshot.rs index 478a92c29..8e991a8c2 100644 --- a/crates/storage-postgres/tests/table_snapshot.rs +++ b/crates/storage-postgres/tests/table_snapshot.rs @@ -522,6 +522,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-sqlite/src/migrations/mod.rs b/crates/storage-sqlite/src/migrations/mod.rs index 4f27e88cf..343c4ae65 100644 --- a/crates/storage-sqlite/src/migrations/mod.rs +++ b/crates/storage-sqlite/src/migrations/mod.rs @@ -316,6 +316,10 @@ pub fn migration(id: MigrationId) -> Migration { MigrationId::UniqueAccessKeyIds => Migration::NotApplicable( "access_key_id is the primary key of access_keys, so an ID can be stored once", ), + 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/backup_catalog.rs b/crates/storage/src/backup_catalog.rs index 3d752a3e6..0e07e46ff 100644 --- a/crates/storage/src/backup_catalog.rs +++ b/crates/storage/src/backup_catalog.rs @@ -1767,11 +1767,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. diff --git a/crates/storage/src/migrations/registry.rs b/crates/storage/src/migrations/registry.rs index 1844df7da..bf371f94f 100644 --- a/crates/storage/src/migrations/registry.rs +++ b/crates/storage/src/migrations/registry.rs @@ -112,6 +112,10 @@ migration_ids! { /// import stored a second key under an ID that a key already had. UniqueAccessKeyIds = 12, "unique_access_key_ids", "make every access key ID unique, which the MongoDB catalog did not enforce"; + /// Re-encodes the strings a PostgreSQL store holds from an earlier + /// release into the escape that stores U+0000 (#364). + EscapeControlChars = 13, "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 new file mode 100644 index 000000000..c3ae4b019 --- /dev/null +++ b/crates/storage/src/util/control_chars.rs @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! 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 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: +//! +//! | 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, 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. 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; + +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 needs_escape(&k) { 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 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..9391c1d3b 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 text cannot +/// hold U+0000) refuses such a key 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 469a59c27..b3d3a28da 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 prefix; mod scan_segment; @@ -26,6 +27,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/adr/0032-u0000-on-postgresql-and-mongodb.md b/docs/adr/0032-u0000-on-postgresql-and-mongodb.md new file mode 100644 index 000000000..db789552e --- /dev/null +++ b/docs/adr/0032-u0000-on-postgresql-and-mongodb.md @@ -0,0 +1,108 @@ +# ADR-0032: 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 d7d13b1ef..f130bd811 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -56,6 +56,7 @@ decision, write a new ADR. | [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-search-condition-grammar.md) | SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting | Proposed | +| [0032](0032-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 1b1e9368d..be26061ba 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -420,6 +420,29 @@ 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 `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. 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 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 c8f5b4e71..4f1dcd03f 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/getting-started.md b/docs/getting-started.md index cc73cdec3..94ba59634 100755 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -271,7 +271,7 @@ Config: extenddb.toml Catalog database: extenddb_catalog --- Checking catalog migrations... - OK: Current: the catalog is at migration 12 + OK: Current: the catalog is at migration 13 --- Checking catalog connection... OK: Connected to catalog. --- Checking data database... @@ -289,7 +289,7 @@ extenddb runs as a daemon (background process) and logs to syslog. On startup it ```bash ./target/release/extenddb serve --config extenddb.toml -# extenddb 1.1.0 (catalog migration 12) starting on 127.0.0.1:18443 +# extenddb 1.1.0 (catalog migration 13) starting on 127.0.0.1:18443 # storage: postgres (postgresql://extenddb:***@localhost:5432/extenddb_catalog) ``` @@ -1394,7 +1394,7 @@ Each runner requires its tools to be installed. The runner checks prerequisites ```bash ./target/release/extenddb version # extenddb 1.1.0 -# catalog migration 12 (postgres) +# catalog migration 13 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z # test-hooks disabled diff --git a/docs/manuals/04-quickstart-setup-guide.md b/docs/manuals/04-quickstart-setup-guide.md index 64ded1f67..679821a5a 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 1.1.0 -# catalog migration 12 (postgres) +# catalog migration 13 (postgres) # commit abc1234 # built 2026-04-17T12:00:00Z # test-hooks disabled @@ -175,7 +175,7 @@ Config: extenddb.toml Catalog database: extenddb_catalog --- Checking catalog migrations... - OK: Current: the catalog is at migration 12 + OK: Current: the catalog is at migration 13 --- 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 7d8775966..931d06513 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -18,6 +18,8 @@ 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. +1.2.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.2.0: U+0000 in strings on PostgreSQL and MongoDB](#v120-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, 1.0.0 or 1.1.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: - On PostgreSQL, SQLite and MongoDB, CreateBackup writes to the configured store. There it is asynchronous, as on the service. The response is `CREATING`, and the backup becomes `AVAILABLE` when the upload ends. So a client that creates a backup and then deletes it has to poll DescribeBackup first. 0.1.14 and earlier releases returned `AVAILABLE`. @@ -78,7 +80,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 12 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, 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 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 @@ -431,6 +433,26 @@ deployment, even when no catalog migration is required. **Who is affected.** A client that pages a parallel Scan of a SQLite deployment across the upgrade. The start keys that 1.1.0 returned follow the old rule. ExtendDB can refuse such a key as a key from another segment. When ExtendDB accepts it, the later pages follow the new rule, so the client can miss items or get items twice. Start such a Scan again after the upgrade. A Scan that pages across a rollback to 1.1.0 can get the same answers. PostgreSQL, MongoDB and Cassandra are not affected. No catalog migration or configuration change is required. +### v1.2.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 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.** 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: + +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 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. + +**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.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: diff --git a/docs/manuals/08-install-linux.md b/docs/manuals/08-install-linux.md index 3deced7fe..71d372243 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 12 + OK: Current: the catalog is at migration 13 ... === HEALTHY: All checks passed === ``` diff --git a/docs/manuals/09-install-macos.md b/docs/manuals/09-install-macos.md index 975415be9..a0c899d28 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 12 + OK: Current: the catalog is at migration 13 ... === HEALTHY: All checks passed === ``` diff --git a/tests/test_cli_vector_catalog_migration.py b/tests/test_cli_vector_catalog_migration.py index 983bcf289..4fb96b5e4 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 13 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. @@ -128,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: @@ -192,6 +213,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 13 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_13(cli_env): + """Take migration 13 out of both ledgers and set the catalog version back + to 12, 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 = 13") + if database == cli_env["db_name"]: + cur.execute( + "UPDATE settings SET value = '12' 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.""" @@ -356,6 +447,77 @@ 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_13_beside_its_own_sessions(self, cli_env): + """`migrate --yes` applies migration 13 to a deployment holding a table + and a backup, and stops while another session holds the catalog. + + Migration 13 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 13 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) + 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 + ) + pending_output = pending.stdout + pending.stderr + assert pending.returncode == 3, pending_output + assert "13 escape_control_chars (catalog, breaking)" in pending_output, pending_output + assert "13 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 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(), + 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 13 escape_control_chars in {catalog}" in output, output + assert f"Applied 13 escape_control_chars in {data}" in output, output + assert 13 in _ledger_ids(catalog) + assert 13 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 ): diff --git a/tests/test_nul_strings.py b/tests/test_nul_strings.py new file mode 100644 index 000000000..d7fe542ba --- /dev/null +++ b/tests/test_nul_strings.py @@ -0,0 +1,592 @@ +# 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. + +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 string +import time + +import pytest +from botocore.exceptions import ClientError + +from conftest import configured_backend, 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"] + +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": 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): + 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"]] + + +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. 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_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=table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + ) + 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=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}, + } + + @nul_keys + def test_partition_order_is_byte_order_with_nul_first(self, dynamodb_client, nul_table): + table, _ = nul_table + assert _sks(_query(dynamodb_client, table, ConsistentRead=True)) == SORT_KEYS + assert ( + _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=table, Key={"pk": {"S": PK}, "sk": {"S": NUL}}, ConsistentRead=True + )["Item"] + by_text = dynamodb_client.get_item( + 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=table, Key={"pk": {"S": PK_WITHOUT_NUL}, "sk": {"S": NUL}}, ConsistentRead=True + ) + assert "Item" not in resp + 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, table, cond="pk = :p AND sk < :s", values={":s": {"S": " "}}, + ConsistentRead=True, + ) + assert _sks(below_space) == [NUL, SOH] + between = _query( + 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, table, cond="pk = :p AND begins_with(sk, :pre)", + values={":pre": {"S": NUL}}, ConsistentRead=True, + ) + assert _sks(prefix) == [NUL] + text_prefix = _query( + 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, table, **kwargs) + seen += _sks(resp) + if "LastEvaluatedKey" not in resp: + break + kwargs["ExclusiveStartKey"] = resp["LastEvaluatedKey"] + assert seen == SORT_KEYS + + @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=table, + IndexName="gsi1", + KeyConditionExpression="g = :g", + ExpressionAttributeValues={":g": {"S": gsi_key}}, + )["Items"] + + 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=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, 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=table, + Key=RICH_KEY, + 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=table, + Key=UPDATE_KEY, + UpdateExpression="SET touched = :t", + ConditionExpression="attribute_exists(#n)", + ExpressionAttributeNames={"#n": f"n{NUL}n"}, + ExpressionAttributeValues={":t": {"BOOL": True}}, + ) + 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): + table, _ = nul_table + resp = dynamodb_client.update_item( + TableName=table, + Key=UPDATE_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=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=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"] + + @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": table, "Item": t1}}] + ) + got = dynamodb_client.batch_get_item( + RequestItems={ + table: { + "Keys": [{"pk": b1["pk"], "sk": b1["sk"]}, {"pk": t1["pk"], "sk": t1["sk"]}], + "ConsistentRead": True, + } + } + )["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": 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={ + 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): + 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 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(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 + + +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 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") +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_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( + 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"] + first = {**RICH_ITEM} + dynamodb_client.put_item(TableName=name, Item=first) + second = dynamodb_client.update_item( + TableName=name, + 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=RICH_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"] == RICH_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"]