Skip to content

fix(storage): store U+0000 in strings on PostgreSQL and MongoDB - #368

Open
LeeroyHannigan wants to merge 38 commits into
mainfrom
fix/nul-in-strings
Open

LeeroyHannigan wants to merge 38 commits into
mainfrom
fix/nul-in-strings

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Changes since the last review

Before 17979e3, two merges of main brought the branch up to date. GitHub showed it in conflict with main.

41d76ef merges main at 44cd436. The commits after it answer the review of 19 Nov:

  • c62aa6e keeps the PostgreSQL key columns in the form main stores them. The escape made a key one byte longer for each U+0000 and U+0001. A 2046-byte partition key with 682 U+0001, which DynamoDB and main store, became 2728 bytes, over PostgreSQL's btree entry limit of 2704. Its PutItem answered 500. The queue held a GSI key of that shape and never indexed it. Now a key value that holds U+0000 gets a 400 ValidationException that names the PostgreSQL limitation. That is the second option [Bug] PostgreSQL and MongoDB: an item containing U+0000 returns InternalServerError; the service accepts it #364 gives for a backend that cannot store the byte. The item documents keep the escape. The same commit makes migration 13 rewrite the item documents only. With no key column rewrite, the 2046-byte key no longer stops the data body after the catalog body commits. The composite key rebuild, the row-by-row order for unique keys and the recompute of gsi_pending.worker_partition are gone. The commit adds the tests for the vector index rewrite, the DELETING and missing-table skips and the catalog body's detect.
  • 3be8ff5 makes the MongoDB backend escape the field names of a document only when a name holds U+0000, and mark that document. The decoder reads only a marked document, so the names that main wrote read back as written. c\x01 and c\x01\x02 stay two attributes, and the next UpdateItem keeps both.
  • c8d852f leaves the TTL attribute name as written on PostgreSQL and MongoDB. ExtendDB's UpdateTimeToLive accepts only [A-Za-z0-9._-] (validate_ttl_attribute_name), so the escape never changed the name.
  • 48ee608 replaces the fixed sleep(1) of the CLI migration test with a wait on pg_stat_activity.
  • d5c27dc adds ADR-0031 for the stored form, lists the key refusal in the differences document, and gives the upgrade manual a v1.1.0 entry. Since 6ec490a they are ADR-0032 and a v1.2.0 entry.
  • 37fc130 builds the key of the two long-key tests from letters and digits. PostgreSQL cannot compress such a key below the btree entry limit once escaped, so the tests fail without c62aa6e.

The body now follows the template. It names the other PRs that add migration 13. The "Related behaviour" section is gone, because #833 and #830 fixed U+0000 in key schema attribute names and in table names on main.

What

DynamoDB accepts the character U+0000 anywhere a string appears. The measurements below are from a scratch table on the service, on 2026-09-18. PutItem accepts it inside a partition key, a sort key, a GSI key and a non-key value. It accepts it in a string in a list, a map key, and a top-level attribute name. GetItem returns each byte-identical. It sorts as the byte 0x00 ahead of every other character. It is a different key 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. The service also accepts it in key schema attribute names, and rejects it in table and index names by the usual pattern.

ExtendDB's PostgreSQL backend returned 500 InternalServerError for every one of the item cases, and for a Query whose key value contains it. TEXT rejects the byte in key columns, and jsonb rejects the \u0000 escape in item_data. The MongoDB backend returned 500 when the character appeared in an attribute name or map key (BSON field names are C strings). SQLite and Cassandra already matched the service.

After this change:

  • PostgreSQL stores U+0000 in values, attribute names and map keys and returns it unchanged. Its key columns cannot hold the byte. A request whose table key or index key value holds U+0000 gets 400 ValidationException. The message is "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."
  • MongoDB stores U+0000 in attribute names and map keys and returns it unchanged.

Shared escape

crates/storage/src/util/control_chars.rs adds an escape: U+0000 is stored as U+0001 U+0001, U+0001 as U+0001 U+0002, every other character unchanged. Strings without either character are stored exactly as before, so ordinary data does not change on disk. Unit tests enumerate every string up to length 5 over the alphabet {U+0000, U+0001, U+0002, a}. They check that the escape round-trips and never holds U+0000. Every string up to length 4 is checked for collisions.

PostgreSQL

  • Item documents: item_to_json and json_to_item in data/mod.rs apply and reverse the escape on every string in the tree (names, map keys, values). Every item_data write in the crate goes through it (put, update, transactions, index rows, vector index rows). So do stream records, queued index updates and their contexts in gsi_pending, both vector search readers, and the snapshot reader that feat(storage): SnapshotEngine, a consistent table snapshot on every backend [backup/restore 4/4] #395 added. The reader for a search with a condition is the path of feat: SearchVectors inequality filters #1449. snapshot_engine.rs parsed item_data::text straight into an item. It now decodes through json_to_item like every other reader of the column.
  • Key columns: data/key_text.rs wraps the shared pk_to_text, composite_pk_to_text and parse_sk. The column text is what the shared helpers give, as main stores it, so every key that main accepts keeps its bytes and its length. A string key value that holds U+0000 gets the ValidationException above. Every site in the crate that produces key text imports the wrappers. A write, a read, a Query key condition and a start key therefore treat such a key the same way. So do an index row and the lock order of a transaction. A write is also refused before its first statement when its key for one of the table's indexes holds U+0000. PutItem and UpdateItem check it beside the index key type checks, and TransactWriteItems in its key pre-pass. A transacted Update that computes such a key cancels with a ValidationError reason carrying the same message. gsi_build::indexable leaves such an item out of an index, as it leaves out an item whose key has another type. The online backfill of a new index and the queue therefore skip an item written before the index existed. A restore leaves it out of the index too.
  • SQL that addresses an attribute by name inside item_data uses the escaped name: the equality filters of a vector search (name and value), on both paths.
  • Catalog migration 13, escape_control_chars. Documents written before this change hold their strings raw. A raw U+0001 followed by U+0001 or U+0002 would read back differently under the new decoder (a lone U+0001 reads back unchanged). Migration 13 has two code bodies on PostgreSQL (crates/storage-postgres/src/migrations/m0013_escape_control_chars/). The catalog body rewrites backup_items.item_data. The data body rewrites item_data of every data, index and vector index table, the item images of gsi_pending and the records of stream_records and stream_pending. The key columns are not rewritten. The tables are listed from the catalog rows. A row whose table is DELETING or whose physical table is missing is skipped with a note. Only documents containing U+0001 change. Each body reads its tables once, so it takes time proportional to data size. Legacy rows never contain U+0000, since PostgreSQL refused them. The candidate predicate spells its backslash as chr(92) so it reads the same under either value of standard_conforming_strings. Migration 11 (fix(storage-postgres): store attribute names containing U+0000 in the catalog #833) escapes gsi_pending.index_context with the same mapping, so migration 13 leaves that column to it. Since fix(storage-postgres): number stream records after their writes commit #819 a write first stores its stream record in stream_pending. Migration 13 re-encodes stream_pending.record_data as well, and the sessions check counts a row there.
  • Migration 13 in the runner. The escape is not idempotent. An escaped U+0001 is stored as U+0001 U+0002, which is also a legal legacy sequence. The migration therefore cannot tell a row this build wrote from a legacy row. Each body runs in the runner's transaction and commits with its store's ledger row. A run that stops leaves that store as it was, and a recorded store is never rewritten again. The migration is Kind::Breaking and not convergent. A binary that does not carry migration 13 refuses the migrated catalog. A 0.1.x binary refuses it as it refuses every migrated catalog, and extenddb migrate --yes --reconverge skips it. A server of this release refuses a store where migration 13 is pending. extenddb init applies it to a new store, which has nothing to rewrite. Because a server refuses a store where migration 13 is pending, the migration only ever sees rows written by earlier releases. CONTRIBUTING.md asks for an idempotent run. Migration 13 relies instead on the runner's transaction and on not being convergent. extenddb migrate --forget 13 followed by a run would escape the strings this release wrote a second time.
  • A failed data body. No index entry and no constraint covers the strings of a document. A rewrite therefore 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 then leaves the catalog store at 13 and the data store at 12. extenddb migrate reports the data store behind the catalog store. A server of this release refuses to start because the data store is behind, and a server of an earlier release refuses the catalog. extenddb migrate --yes runs the data body alone. The upgrade manual says so.
  • Other sessions. migrate --yes waits for the servers that hold the runner's serving key, which a 0.1.x server does not take. The runner calls each body's detect for every pending code body before a run's first write. detect stops the run with exit 5 while another session is connected to the database that body rewrites. For the data body that is the data database whenever the catalog lists a table or gsi_pending, stream_records or stream_pending holds a row. For the catalog body it is the catalog database whenever backup_items holds a row. The item names each session by role, client address and application name. The runner's own sessions (extenddb migrate run <id>), the migration lock's session (extenddb migrate) and status sessions (extenddb status) are left out by application_name. The runner sets those names over any application_name in the connection string. The migrator connects as the application role, which is not a superuser, and PostgreSQL hides backend_type on other roles' sessions from it. The filter therefore counts any session with a role whose type is client backend or hidden. An operator's psql or a server under another role is counted, while autovacuum workers are not. A status read does not look for sessions, so the preview still runs beside a server and reports migration 13 as pending. EXTENDDB_MIGRATE_IGNORE_CONNECTIONS=1 skips the check for idle pooler connections. The test harnesses whose own sessions hold their scratch databases (apply_all_migrations, and Scratch::target in tests/migrations_support) build their target with PostgresTarget::with_other_sessions_allowed. That constructor is compiled only with test-util or test-hooks, so every path an operator runs keeps the check.
  • SQLite, Cassandra and MongoDB record migration 13 as not applicable, each with its reason.

MongoDB

BSON string values are length-prefixed and already held the character. Field names could not. item_to_document and index_document escape the field names of an item only when one of them holds U+0000, and then mark the document with the top-level field names_escaped. document_to_item decodes only a marked document. No earlier release could store such a name, so every document that main wrote is unmarked and reads back as written. Stream records follow the same rule, and GetRecords carries the mark through its aggregation. The native update paths do not read the document, so they cannot tell which form its names take. An update whose attribute name, or a field name inside its value, holds U+0000 or U+0001 takes the session path. Names containing . or starting with $ already take it. Conditions with such names take it too. The native $setOnInsert upsert from #473 writes the key attributes as item_data.<name> paths. A table whose key attribute name contains either character therefore takes the session path too, through the same is_plain_path_name check that already routed names containing . or $.

The MongoDB ledger records migration 13 as not applicable.

Documentation

ADR-0032 records the stored form: the document escape, the key refusal on PostgreSQL, the MongoDB mark and migration 13. It takes 0032 because main has ADR-0031 (#1449), #954 adds ADR-0030, and #529 and #536 add ADR-0028. docs/differences-from-dynamodb.md lists the key refusal. docs/design/04-component-storage.md describes the escape beside key and item storage. docs/manuals/07-upgrade-manual.md documents migration 13 in a v1.2.0 entry under Behavior Changes. The entry covers the upgrade order, the sessions check, a failed data body, the rollback and the MongoDB mark. The install and quickstart guides show a new deployment at migration 13.

Why

Closes #364.

PostgreSQL and MongoDB answered 500 to items that DynamoDB stores. #364 accepts either of two answers: store the character, or refuse it with a ValidationException that names the limitation where a backend cannot store it. This change stores it everywhere it can. On PostgreSQL that is everywhere but the key columns. An escape in the key columns would make some keys that main stores too long for the btree entry limit. bytea key columns would change every key column, bind site and comparison (ADR-0032).

Other PRs that add migration 13

#874 adds BulkOperations = 13 and #542 adds GsiPendingTableClaim = 13. Whichever of the three merges first keeps 13, and the others renumber.

Second copy

Migration 13 keeps its own copy of the escape (m0013_escape_control_chars/escape.rs). CONTRIBUTING.md asks that the functions that define what a migration does live in its module, so that the module's checksum covers them. Migration 11 keeps its own copy for the same reason.

Follow-up

Testing done

The first bullet lists the runs on d559e2a on 3 Dec 2026, with Rust 1.97.0 and the dev profile. They ran against pgvector/pg16, MongoDB 7 and Cassandra 4.1 containers. Every other run below is on 24 Nov 2026, with Rust 1.97.0, against pgvector/pg16 and MongoDB 7 containers. The second bullet lists the runs on deff98f, the head before 17979e3. The other bullets ran on 37fc130, the head before the merges of 24 Nov. Their wire tests ran against a PostgreSQL server and a MongoDB server built from that head. Those merges change none of this PR's test files.

  • On d559e2a:
    • cargo +1.97.0 fmt --all -- --check is clean. The two clippy commands of clippy.yml with -D warnings are clean on the workspace. cargo +1.94.0 check --locked --all-targets on the five crates this PR changes is clean. Since fix(deps): move to sqlx 0.9.1 for the SQLite fix of RUSTSEC-2026-0459 #1166 the rust-version of the workspace is 1.94.0.
    • Lib tests: extenddb-storage (304), extenddb-storage-postgres (103), extenddb-storage-mongodb (205, and 88 ignored), extenddb-storage-cassandra (194) and extenddb-storage-sqlite (335, and 1 ignored) pass. The two SQLite backup_catalog::write_lock_tests fail (storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414).
    • cargo test -p extenddb-storage-postgres --tests --no-fail-fast in the dev profile, live on a pgvector/pg16 server, with EXTENDDB_TEST_PG_REQUIRED=1 and EXTENDDB_EXPECT_VECTORS=1: 517 pass and 2 are ignored. Five fail with the message they give on deff98f: three store_identity tests in backup_restore.rs and two tests in catalog_nul_backup_jobs.rs. Each opens a filesystem backup store, which refuses a root under a directory owned by another user. The tests that pass include a_filtered_vector_search_reads_control_characters_as_written and the tests of feat: SearchVectors inequality filters #1449 in vector_search_filter.rs (4) and vector_search_filter_pages.rs (2).
    • Two controls keep the new test, and each puts back one half of main's code for the path. With the equality filters bound as the request gives them, the test fails with SQLSTATE 22P05: error returned from database: unsupported Unicode escape sequence. With the candidates decoded by serde, the search returns 0 hits, where the test expects 1.
    • extenddb-storage-mongodb, on a one-node replica set: the ignored records_live (7), data_engine::live_tests:: (22) and backup_engine::live_tests:: (57) tests pass. With EXTENDDB_TEST_MONGODB_REQUIRED=1 and the snapshot_engine:: tests left out, every test target passes (290, and 88 ignored). CI runs the snapshot_engine:: tests beside a second, standalone server.
    • extenddb-storage-cassandra, on Cassandra 4.1 with PasswordAuthenticator: --test migrations (33) and --test migrations_stopped (8) pass.
    • cargo test -p extenddb-wasm-adapter: its 3 unit tests and the parity corpus test pass. cargo test -p extenddb-storage-postgres --test doc_version_literals: 3 pass. The clippy step of .github/workflows/wasm.yml is clean. This host has no clang, so the run used a stand-in C compiler and archiver.
    • tests/test_nul_strings.py: on a SQLite server built from d559e2a, 20 pass and the PostgreSQL refusal test skips. On a PostgreSQL server, 12 pass and 9 parametrized cases skip. The SearchVectors test files of feat: SearchVectors inequality filters #1449 (test_search_vectors_condition_limit.py, test_search_vectors_deep_conditions.py, test_search_vectors_expression_maps.py, test_search_vectors_inequality_filters.py and test_search_vectors_metrics.py, 83 tests): on each server 82 pass, and the test for a backend without vector search skips.
    • tests/test_cli_vector_catalog_migration.py with the PostgreSQL binary: 5 pass. pytest --collect-only collects tests/ (7326) and tests/python (820) with no error.
  • On deff98f:
    • cargo +1.97.0 fmt --all -- --check is clean. The two clippy commands of clippy.yml with -D warnings, limited to the five crates this PR changes, are clean. cargo +1.91.1 check --all-targets on the five crates is clean.
    • Lib tests: extenddb-storage (295), extenddb-storage-postgres (96), extenddb-storage-mongodb (198, and 86 ignored), extenddb-storage-cassandra (181) and extenddb-storage-sqlite (325) pass. The two SQLite backup_catalog::write_lock_tests fail (storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414).
    • extenddb-storage-postgres, live: the seven test files this PR changes, migrations_fresh, migrations_released, and main's catalog_check, key_ring_rows, lsi_query_plan and stream_at_timestamp. 245 pass and 2 are ignored. 5 fail: three store_identity tests in backup_restore.rs and two tests in catalog_nul_backup_jobs.rs. Each opens a filesystem backup store, which refuses a root under a directory owned by another user. The same five fail with the same message on main at 89fc971.
    • extenddb-storage-mongodb, on a one-node replica set: migrations_fresh, migrations_guards, migrations_locks and migrations_released (40) pass. The ignored live tests of data_engine_live_tests_control_names.rs and backup_live_tests_control_chars.rs and the seven records_live tests pass. The records_live tests include the AT_TIMESTAMP seek of feat(streams): AT_TIMESTAMP shard iterator on all four backends #468.
    • tests/test_nul_strings.py: on a SQLite server built from this head, 20 pass and the PostgreSQL refusal test skips. On a PostgreSQL server, 12 pass and 9 parametrized cases skip.
    • tests/test_cli_vector_catalog_migration.py with the PostgreSQL binary: 5 pass.
    • pytest --collect-only collects tests/ (6659) and tests/python (672) with no error.
  • tests/test_nul_strings.py: 18 wire tests. On PostgreSQL 12 pass and 9 parametrized cases skip, the ones that put U+0000 in a key value. On MongoDB 20 pass and the PostgreSQL refusal test skips. test_postgresql_refuses_nul_in_a_key_value sends 13 request shapes whose key value holds U+0000 and checks the status, the code and the message of each by equality. The shapes are PutItem on each key and on a GSI key, UpdateItem that sets a GSI key, GetItem and DeleteItem. The rest are three Query shapes, BatchWriteItem, BatchGetItem, TransactWriteItems and TransactGetItems. It then sends a transacted Update that computes such a GSI key and checks the ValidationError reason, and that the table holds no item. test_a_long_key_holding_u0001_is_stored puts a 2046-byte partition key with 682 U+0001 between random letters and digits, and a GSI key of the same shape. Both PutItems return 200, GetItem returns the item and the GSI Query returns the other. With the escape put back in key_text.rs, the first PutItem answers 500 InternalServerError. The escaped key is 2728 bytes, and PostgreSQL refuses the btree entry with index row size 2752 exceeds btree version 4 maximum 2704. Without the TransactWriteItems key pre-pass, the TransactWriteItems shape answers 500 instead of 400. The stream test passes: INSERT, MODIFY and REMOVE records for an item whose key holds U+0001 and whose names, map keys and values hold U+0000.
  • Unit tests: 9 cover the shared escape. They cover the round trip and the absence of U+0000 over every string up to length 5, and collisions up to length 4. They cover the lenient legacy decode and the JSON tree variants. 2 cover the PostgreSQL key text wrappers. They check the refusal of U+0000 in a partition key, a sort key and a composite key, by message. U+0001, numbers and binaries stay as the shared helpers give them. indexable leaves out a string key holding U+0000 and keeps one holding U+0001. In the MongoDB crate, a_document_without_the_mark_reads_back_its_names_as_written reads an unmarked document with c\x01, c\x01\x02, a\x01\x02 and the map key k\x01\x01 back as written and writes it back unmarked. An item with U+0000 in a top-level name, in a nested map key and in a map key inside a list round-trips. Its document carries the mark. The pushdown, native update and native upsert tests send such names to the session path. With the decoder applied to every document, the first of them reads 4 names for 5.
  • MongoDB live, against a one-node replica set: live_names_an_earlier_release_stored_read_back_and_survive_an_update stores a document as main wrote it, with c\x01 = "one" and c\x01\x02 = "two". GetItem returns both. An UpdateItem on the session path and one on the native path keep both and leave the document unmarked. With the decoder applied to every document, GetItem returns only c\x01 = "two". The lib tests of extenddb-storage-mongodb with --include-ignored (283) and its six migration test files (51) pass.
  • Migration 13 in crates/storage-postgres/src/migrations/m0013_tests.rs and m0013_guard_tests.rs, live on scratch databases. reencodes_legacy_rows seeds a data table, an index table, a vector index table, gsi_pending, stream_records, stream_pending and backup_items with raw U+0001 rows, a literal-backslash row and plain rows. Its catalog also lists a DELETING table with an index and a table with no physical table. It checks the ledger notes by equality, the three skip notes among them. It checks that every document is re-encoded once, that every key column keeps its text, and that the deleting table's row is unchanged. With the vector index tables left out of the data body, or with the DELETING check removed, the notes differ and the test fails. the_catalog_body_stops_a_run_while_another_session_holds_the_catalog calls EscapeBackupItems.detect on the stores of a run. It gets nothing while backup_items is empty, the item that names the session once it holds a row, and nothing once the session closes. With detect returning nothing, it fails.
  • Migration 13 through the runner, in tests/migrations_golden.rs over two databases. migration_13_escapes_the_strings_an_earlier_release_stored loads the 0.1.14 fixture and migrates it through 12. It gives every row of seed_tbl's table, GSI and LSI and of the backup's backup_items a raw U+0001 in its key columns and in its document. It migrates through 13 and compares the rows and the ledger notes of both stores with tests/fixtures/golden/0013_escape_control_chars.txt. The documents are re-encoded and the key columns are as they were. migration_13_applies_over_a_long_key_holding_u0001 stores the 2046-byte key of the wire test in seed_tbl's table and requires migration 13 in both ledgers with the key's bytes unchanged. With the key column replace() put back in the data body, the run stops with re-encode "_ddb_<id>".pk: ... index row size 2752 exceeds btree version 4 maximum 2704. migration_13_stops_before_any_write_while_another_session_holds_the_data is unchanged.
  • Backup and restore: restore_keeps_control_characters_in_keys_indexes_and_items (tests/backup_restore/control_chars.rs) stores items with U+0001 in key and index key values and U+0000 in names, map keys and values. It adds one item whose GSI key holds U+0000, stored as a write before the GSI existed stores it. The restore reproduces the source's stored rows, and the restored items read back equal. Without the restore's filter, the restore fails and the target never becomes ACTIVE. bulk_load_stores_control_characters_through_the_escape (tests/restore_job/control_chars.rs) covers the restore job's bulk load. crates/storage-mongodb/src/backup_live_tests_control_chars.rs covers the MongoDB backup. migrations_11_and_13_escape_a_queued_index_update_once (tests/migrations_name_escape.rs) covers the queued index update that both migrations touch. an_item_with_control_characters_streams_as_written (tests/table_snapshot.rs) covers the snapshot reader.
  • Migration 13 through the CLI, in tests/test_cli_vector_catalog_migration.py (5 pass). test_migrate_applies_migration_13_beside_its_own_sessions makes a deployment with this binary's init and creates a table, an item and a backup through the server. It then takes migration 13 out of both ledgers. The preview exits 3. migrate --yes exits 5 while another session holds the catalog database and records migration 13 in neither ledger. Once the session closes it exits 0 and applies migration 13 in both stores. The test waits on pg_stat_activity for the server's and the other session's connections to go instead of sleeping.
  • Gates: cargo fmt --all -- --check is clean. Clippy with -D warnings is clean over all targets of extenddb-storage, extenddb-storage-postgres, extenddb-storage-mongodb, extenddb-storage-sqlite and extenddb-storage-cassandra, with extenddb-storage-cassandra/test-hooks and extenddb-storage-mongodb/test-hooks turned on, as clippy.yml runs it. cargo +1.91.1 check --locked --all-targets on the same crates is clean. The lib tests of extenddb-storage (293) and extenddb-storage-postgres (93) pass. The 36 integration test files of extenddb-storage-postgres, live: 471 pass and 2 are ignored. 6 fail on this host before and after this round's commits, for reasons outside this change. The five that write a filesystem backup store refuse a root under a directory owned by another user (storage-sqlite: the two write_lock_tests fail when an ancestor of the Cargo target directory is owned by another user #1414). a_role_that_does_not_own_the_tables_is_told_what_to_run expects the superuser to be named postgres. None of the six touches the escape or the key text. pytest --collect-only over tests/ (6613) and tests/python (672).

Checklist

  • I have read CONTRIBUTING.md
  • All tests pass (cargo test --workspace)
  • Code is formatted (cargo fmt --check)
  • Clippy is clean (cargo clippy -- -W clippy::pedantic)
  • I have added or updated tests for new functionality
  • I have updated documentation if behavior changed
  • Breaking changes are noted below (if any)
  • If this changes the wire protocol, Storage trait, auth model, on-disk
    format, or public CLI surface, an RFC has been accepted or is linked
    below. Otherwise, an ADR captures the decision (link below).

ADR / RFC: ADR-0032

Breaking changes

  • PostgreSQL deployments upgrade in this order. Stop every server that uses the deployment, including servers of earlier releases. Run extenddb migrate --yes with the new binary. Start the new servers. While the deployment holds a table or a backup, migrate --yes stops with exit 5 if another session holds the data database or the catalog database. It stops before it writes anything, and it names the sessions. The new server refuses to start while migration 13 is pending. A server of an earlier release refuses the migrated catalog. Downgrading means restoring both databases from pre-migration backups. Fresh deployments are unaffected.
  • On PostgreSQL, a request whose table key or index key value holds U+0000 gets 400 ValidationException where an earlier release answered 500 InternalServerError.
  • Documents that an earlier release wrote read back as before on MongoDB. A MongoDB deployment runs extenddb migrate --yes once to record migration 13 as not applicable.

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

@robinnsc robinnsc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One blocking item (the connection guard's coverage, inline on migrations.rs), one strong question on the downgrade hazard, one non-blocking question on the MongoDB asymmetry. The escape design itself checks out: I traced the order/prefix/collision argument, the migration's non-idempotence handling (per-table transaction plus progress marker, with the startup gate guaranteeing only legacy rows are ever scanned), and the backup path — create-backup copies stored rows verbatim from the data tables, so escaped form flows through backup_items transitively and there is no unescaped write path I could find.

Comment thread crates/storage-mongodb/src/data/mod.rs Resolved
jcshepherd
jcshepherd previously approved these changes Sep 21, 2026
@jcshepherd
jcshepherd added this pull request to stack #369 September 21, 2026 21:32
Base automatically changed from fix/hash-only-gsi-reverse-cursor to main September 21, 2026 22:12
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Rebased on main at abf8082; conflicts in crates/storage-postgres/src/gsi_queue.rs, resolved by keeping #401's queue code and decoding its rows through json_to_item and stored_json_to.

#401's queue apply builds the base key text in key_from_item (crates/storage-postgres/src/data/gsi_build.rs) with the unescaped shared helpers. With this branch's escaping, a GSI write on a key holding U+0000 then failed in the worker with SQLSTATE 22021 and test_gsi_holds_the_item_with_a_nul_key failed. key_from_item now uses the key_text wrappers, and tests/test_nul_strings.py passes on PostgreSQL.

The merge of main that was on this branch is folded into the first commit with its resolutions unchanged (migration 004, catalog 0.0.5).

@navareamol navareamol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this, Lee. The escape design is really nice: order, prefixes and the jsonb and BSON paths all hold up as far as I could trace them, and moving every key-text site in storage-postgres onto key_text makes the change easy to follow.

I found two things, both on the upgrade path for rows written before this change:

  1. 004 breaks the netstring length prefix on GSI pk when the index has more than one HASH attribute (details inline on migrations.rs).
  2. Rows still queued in gsi_pending keep their old worker_partition after the hash changes (details inline on gsi_queue.rs).

A test for each that seeds the legacy form and fails without the fix would be great.

I also checked the description against the code at 9ae7a01, and a few parts have drifted since the rebase:

  1. The catalog numbers are from before #384 merged. The description says catalog 0.0.4 and migrations/003_control_chars_encoding.sql, and that #384 and #335 also claim 0.0.4. The code has 004_control_chars_encoding.sql and CATALOG_VERSION 0.0.5, and #384 is on main. The "Upgrade path" and "Deploy note" sections still say 0.0.4 and quote expected 0.0.3, found 0.0.4. The upgrade manual already says 0.0.5, so only the description is behind.
  2. The end-to-end upgrade run in "Gates" was done before the renumbering. Your 24 Oct reply says the old binary was not run again against a migrated deployment after the merge. Could you rerun it, or note which revision it covers?
  3. "Composite partition keys escape each part before netstring joining" holds for writes and queries, but 004 does not do it for legacy rows (point 1). Likewise, "the propagation queue agree[s] on the stored form" holds for the queued documents but not for worker_partition (point 2).
  4. "All three backends" reads as if there are only three. Cassandra runs tests/test_nul_strings.py in CI and passes, so it would be worth naming it.

With 1 and 2 fixed and the description brought up to date, I will approve.

DynamoDB accepts the character U+0000 anywhere a string appears: keys, index
keys, values, strings in lists, map keys, attribute names (measured against the
service 2026-09-18; it sorts as the byte 0x00 and is a different key from the
six-character text "\u0000"). PostgreSQL TEXT rejects the byte and jsonb
rejects the escape, so the backend answered 500 for every such item and for a
Query whose key value carried it. BSON field names are C strings, so MongoDB
answered 500 when the character appeared in an attribute name or map key.

Shared escape (crates/storage/src/util/control_chars.rs): U+0000 is stored as
U+0001 U+0001, U+0001 as U+0001 U+0002, everything else unchanged. Exhaustive
tests over every string up to length 4 on {U+0000, U+0001, U+0002, a} pin round
trip, UTF-8 byte order, prefix preservation, and distinctness, so COLLATE "C"
comparisons, BETWEEN, begins_with, and the row-comparison page cursors return
the rows the raw text would.

PostgreSQL: item documents go through item_to_json/json_to_item (every
item_data write, stream records, gsi_pending rows and contexts, vector rows,
and the rows the snapshot engine's cursor stream reads); key column text goes
through data/key_text.rs wrappers at every producing site; the TTL index and
sweep and the vector search filters address attributes by the escaped name.
Migration 004_escape_control_chars re-encodes rows written by earlier releases
that contain U+0001, one table per transaction with a per-table progress
marker, only rows containing U+0001 touched, predicate independent of
standard_conforming_strings. The server refuses to start on a data database
that does not record the migration (rows this build writes are
indistinguishable from legacy rows to the migration) and extenddb init records
it on fresh deployments.

Catalog 0.0.5 (migrations/004_control_chars_encoding.sql) changes no schema; it
moves the version so that a binary from an earlier release, which reads escaped
rows as literal data and reports nothing, refuses a migrated deployment through
the version check it already performs. The two gates close both directions.

extenddb migrate refuses to run 004 while any other session holds the data
database or, when the catalog is a separate database, the catalog database
(backup_items lives there). The check runs before the first write, so a refusal
leaves the catalog version where it was, and again inside the migration. The
command connects as the application role, for which pg_stat_activity hides
backend_type on other roles' sessions; the filter counts any session with a role
whose type is client backend or hidden, so an operator's psql or a server under
another role is counted and autovacuum workers are not. The test-hooks entry
point apply_all_migrations, which the live test harness runs on scratch
databases it created and holds alone, runs 004 without that check; every path
an operator runs keeps it.

MongoDB: item_to_document and its inverse escape object keys only (BSON string
values already hold the byte); conditions and native updates on names with
these characters use the existing in-process fallback paths, as names with "."
or "$" already do; the native $setOnInsert upsert writes key attributes as
item_data.<name> paths, so a table whose key attribute name holds either
character takes the session path through the same is_plain_path_name check;
field paths with no fallback use the escaped name. Legacy field names are read
through the decoder without a migration; the decoder's documentation states the
exposure (a name containing U+0001 followed by U+0001 or U+0002) and points at
the upgrade manual.

Tests: tests/test_nul_strings.py (14 wire cases passing against DynamoDB and
on PostgreSQL, SQLite, MongoDB and Cassandra, plus a stream record case on
ExtendDB servers); unit tests on the escape, the key wrappers, the MongoDB
document conversion and predicates, the migration count and version; live
migration tests for re-encoding, the second-run skip, the
standard_conforming_strings setting, the startup gate, the connection guard on
the data database, on a separate catalog database, and from a non-superuser
pool against another role's session; a live snapshot test that streams an item
with U+0000 in an attribute name and U+0001 in a value as it was written;
tests/test_cli_vector_catalog_migration.py covers 0.0.2 to 0.0.5 and the gate
in both directions. Docs: storage design, upgrade manual, version literals.

Closes #364
…m the decoded item

Main's restore (#384) reads each backup_items document as text, parses it
into an Item and writes the text into the target's item_data unchanged. On
this branch that text carries the control-character escape, and the key
columns and index rows are built by helpers that escape their input, so
the parsed item was escaped a second time: a restored table whose items
hold U+0000 or U+0001 got key columns and index rows in a form the read
path does not produce. The item is now decoded with json_to_item before
the key helpers see it, and the key helpers are the escaping ones from
key_text, so every column is escaped exactly once; the item_data text is
still copied as it is. The backup copy sizes each item from the decoded
form for the same reason.

The parallel Scan cross-segment check (#203) hashes the candidate key's
text and compares it with the hash of the stored pk column; it now uses
the escaping pk_to_text so both sides hash the same text for keys with
control characters.

A storage-level test restores a table whose keys, index keys, attribute
names and nested values hold U+0000 and U+0001 and compares the stored
rows of the base table and both index tables with the source's, then
reads each item back.
This merge brings in 13 commits of main through 44cd436. One of them,
#1194, changes two files of this branch: it adds ClaimSession::unlock to
crates/storage-postgres/src/backup_engine.rs, and it adds the
migrations_support module and a test to
crates/storage-postgres/tests/backup_restore.rs. Both files merge without a
conflict.
…000 in a key

The escape of U+0000 and U+0001 made a stored key one byte longer for each
of those characters. A 2046-byte partition key with 682 U+0001, which
DynamoDB and main store, became 2728 bytes, over the btree entry limit of
2704. Its PutItem answered 500. The queue held a GSI key of that shape
and never indexed it. Migration 13 stopped on such a row after the catalog
body committed.

The key columns now hold the key text that main stores. Every site that
produces key text calls the key_text wrappers. They refuse a string key
value that holds U+0000 with a ValidationException naming the PostgreSQL
limitation. Writes check index keys too. PutItem, UpdateItem and the
TransactWriteItems pre-pass refuse a write whose key for one of the
table's indexes holds U+0000, before its first statement. A transacted
Update that computes such a key cancels with a ValidationError reason.
gsi_build::indexable leaves such an item out of an index, as it leaves out
an item whose key has another type. The queue, the backfill and a restore
skip it.

Migration 13 rewrites the item documents alone. The key column rewrite,
its row-by-row order (order.rs), the composite key rebuild (keys.rs) and
the recompute of gsi_pending.worker_partition are gone. gsi_queue goes back
to main's partition code. The migration keeps its own copy of the escape
(escape.rs), so that its checksum covers what it writes.
transactions.rs takes pk_to_text from key_text.

Tests:
- test_nul_strings.py: the tests that put U+0000 in a key skip on
  PostgreSQL. test_postgresql_refuses_nul_in_a_key_value checks the refusal
  on 13 request shapes and on a transacted Update.
  test_a_long_key_holding_u0001_is_stored stores the two 2046-byte shapes.
- migration_13_applies_over_a_long_key_holding_u0001 requires migration 13
  in both ledgers over such a key.
- reencodes_legacy_rows adds a vector index table, a DELETING table with an
  index and a table with no physical table, and checks their notes.
- the_catalog_body_stops_a_run_while_another_session_holds_the_catalog
  calls the catalog body's detect.
- The restore test adds an item with U+0000 in its GSI key, which the
  restore leaves out of the index.
item_data_to_json decoded the field names of every document. Names that
main wrote with U+0001 followed by U+0001 or U+0002 read back changed.
c\x01 and c\x01\x02 became one attribute, and the next UpdateItem stored
the item without the other.

A write now escapes the field names of a document only when one of them
holds U+0000, which main could not store. It marks that document with the
top-level field names_escaped. The decoder reads only a marked document,
so every document that main wrote reads back as written. Stream records
follow the same rule, and GetRecords carries the mark through its
aggregation. The native update paths do not read the document. A value
whose field names hold U+0000 or U+0001 therefore takes the session path,
as such an attribute name already did.

A live test stores a document as main wrote it, with c\x01 and c\x01\x02.
GetItem returns both, and an UpdateItem on the session path and one on the
native path keep both. A unit test reads such names and a map key back as
written.
UpdateTimeToLive accepts only [A-Za-z0-9._-] in the attribute name
(validate_ttl_attribute_name), so the escape never changed the TTL name.
On PostgreSQL the fence of the index build bound the escaped name, while
update_ttl stores the raw one. A name that the escape changes would never
match. PostgreSQL and MongoDB now run main's TTL code.
test_migrate_applies_migration_13_beside_its_own_sessions slept 1 s after
it stopped the server, and ran migrate --yes right after it closed the
other session. Both runs count the other sessions on the databases, and
PostgreSQL removes a closed session from pg_stat_activity a moment after
the close returns. The test now polls pg_stat_activity until no client
session holds either database, for at most 30 s.
ADR-0031 records the stored form: the escape of the item documents, the
refusal of U+0000 in a PostgreSQL key, the MongoDB mark, and migration 13.
0031 is the first number that no open PR claims: #529 and #536 add 0028,
and #954 adds 0030.

- differences-from-dynamodb.md lists the refusal of U+0000 in a key on
  PostgreSQL.
- The upgrade manual's entry is now a v1.1.0 entry. It says what an
  operator sees when the data body fails after the catalog body committed,
  and describes the MongoDB mark. The Current Status paragraph about 1.0.0
  and migrations 1 to 12 is as main has it.
- 04-component-storage.md and the escape module's comment no longer say
  that the key columns hold escaped text. The escape's byte order and
  prefix tests go with that claim. map_json checks a key with needs_escape.
test_a_long_key_holding_u0001_is_stored and
migration_13_applies_over_a_long_key_holding_u0001 built their 2046-byte
key from lowercase letters. PostgreSQL compresses a btree entry over
about 2 KB when the compression saves a quarter of it. With each U+0001
stored as two bytes, such a key compresses enough to fit the 2704-byte
entry limit. The two tests therefore passed with the key escape in place.
A key of letters and digits does not compress that far. Its escaped form fails
the insert with "index row size 2752 exceeds btree version 4 maximum
2704", measured on pgvector/pg16 with the DDL of data/ddl.rs. The tests
now fail without the fix and pass with it.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

The four blocking items are answered in the threads. The key length is in the key_text.rs thread, the migration that stops after the catalog commit in the order.rs thread, and the MongoDB names in the data/mod.rs thread. The queued GSI key is the first item below. The merge of main in 48ca715 (20 Nov) brought migrations 1 to 12 as released, and 7a10917 leaves gsi_pending.index_context to migration 11 of #833. 41d76ef merges main again, at 44cd436. The other items of the review body:

  • The GSI worker stall. A GSI key of that shape is now stored at its own length, so its row applies: test_a_long_key_holding_u0001_is_stored queries the GSI and gets the item. A GSI key that holds U+0000 is refused at write time, and gsi_build::indexable leaves such an item out of the index (c62aa6e). Neither the queue nor the backfill therefore meets a row it cannot apply for this reason. A row whose apply fails every time still blocks the later rows of its partition, which this PR does not change: PostgreSQL: a gsi_pending row whose apply always fails holds up every later row of its worker partition #1417.
  • The sleep(1) in test_migrate_applies_migration_13_beside_its_own_sessions. 48ee608 waits instead until pg_stat_activity shows no client session on either database, for at most 30 s. It waits after the server stops and after the other session closes.
  • stream_engine.rs:156. That edit left the PR in the merge of main in 48ca715, which took main's stream_engine.rs after fix(storage-postgres): number stream records after their writes commit #819 moved the write path to tx_helpers.rs. The only change left in stream_engine.rs is the GetRecords decode through from_catalog_json, which test_stream_records_carry_nul_names_and_values reads through.
  • transactions.rs:15. c62aa6e imports pk_to_text from key_text, so the lock order takes the key text that every other key text site takes.

Main is at 018715e, seven commits after the last merge (#432, #468,
#503, #526, #690, #765 and #774). One file conflicted:
crates/storage-postgres/src/data/mod.rs. #690 adds
STORAGE_RELATION_PREFIX where this branch imports from_catalog_json and
to_catalog_json. The merge keeps both.

Main changed seven other files this branch changes, and git merged them
with no overlap. The PostgreSQL query and query_scan modules keep this
branch's import of parse_sk and pk_to_text from data::key_text. So the
LSI index walk of #432 refuses a key that holds U+0000 as the other
reads do. The AT_TIMESTAMP seek of #468 reads sequence numbers only, so
the record escape does not apply to it. Main adds no catalog migration,
so migration 13 keeps its number.
Main is at 89fc971, one commit after the last merge (#1280). It changes
one file, crates/storage-mongodb/tests/migrations_guards.rs, which this
branch does not change, so the merge had no conflict.

#1280 ends the killed holder's lease in
a_lock_left_by_a_killed_holder_is_taken_once_it_expires by moving the lock
document's expires_at behind the server clock. It imports LOCK_ID from the
MongoDB migrations module. That module keeps the constant, and this branch
adds only the EscapeControlChars arm to it. The test reads the ledger
version through MigrationId::LATEST, so migration 13 needs no change to
it.
Main is at 14ade59 (#864), ten commits after the last merge. Two files
conflicted:

- docs/manuals/07-upgrade-manual.md: #398 and this branch each add a
  v1.1.0 entry at the top of "Behavior Changes by Release". The merge
  keeps both entries whole, the #398 entry first and this branch's U+0000
  entry after it.
- crates/storage-postgres/src/data/query.rs: #588 adds
  string_prefix_upper_bound to the extenddb_storage::util import, and
  this branch imports parse_sk and pk_to_text from super::key_text. The
  merge imports sk_info and string_prefix_upper_bound from util and keeps
  the key_text import. bind_sk_condition computes the begins_with bound
  of #588 from the value that key_text::parse_sk returns. So a prefix
  that holds U+0000 still gets the ValidationException of this branch
  before the statement runs.

The other files that both sides change merged without a conflict. In
each one the two sides change different lines:

- crates/storage-postgres/src/data/query_scan.rs: #588 passes the
  expression maps to build_sk_sql, and this branch imports from key_text.
- crates/storage/src/util/mod.rs: the prefix module of #588 and the
  control_chars module of this branch.
- crates/storage-cassandra/src/migrations/mod.rs and
  crates/storage-sqlite/src/migrations/mod.rs: #1173 and #1009 change
  imports and module declarations, and this branch adds the
  EscapeControlChars arm.
- crates/storage/src/backup_catalog.rs: #1009 adds clippy allows, and
  this branch changes a doc comment.
- CONTRIBUTING.md, docs/design/04-component-storage.md and
  docs/differences-from-dynamodb.md: each side changes its own sections.

Main adds no catalog migration, so migration 13 keeps its number.
Main is at db8a90d. This branch last had main at 14ade59 (#864).
Since then, 35 commits merged into main. Among them, #1514 released
v1.1.0 without this branch, #1166 moved to sqlx 0.9.1, and #1449 added
the SearchVectors inequality filters.

Four files conflicted:

- crates/storage-postgres/src/vector_search.rs: #1166 passes the search
  statement through sqlx::AssertSqlSafe, and #1449 moves the vector
  attribute of a hit into hit(). This branch decodes the stored item
  through json_to_item. The merge keeps the wrapper and hit() of main
  and the decode of this branch.
- docs/adr/README.md: #1449 adds ADR-0031, the search condition grammar,
  where this branch lists its own ADR-0031. The ADR of this branch is
  now ADR-0032, the next number that no ADR on main and no open PR uses.
- docs/getting-started.md and docs/manuals/04-quickstart-setup-guide.md:
  #1514 shows version 1.1.0 in the sample output, and this branch shows
  catalog migration 13. The merge shows both.

The upgrade manual merged with no conflict, but the U+0000 entry of this
branch was a v1.1.0 entry. It is now a v1.2.0 entry after the v1.2.0
entries of main, because v1.1.0 shipped without this change. The
sentence that links to the entry names 1.2.0. It also adds 1.1.0 to the
releases whose deployments run extenddb migrate --yes once for
migration 13.

sqlx 0.9 takes SQL that is not a &'static str only in
sqlx::AssertSqlSafe (#1166). The merge passes the SQL of the 18 queries
that this branch adds in migration 13 and in its PostgreSQL tests in it.
The SQL text does not change. m0013_tests.rs runs the migration files
with raw_sql(*text), as the runner of main does.

Git merged the other files that both sides change at other lines. Main
adds no catalog migration, so migration 13 keeps its number.
A SearchVectors request whose condition the equality filters cannot
express takes the filtered path of #1449. That path bound each equality
filter with the name and the JSON text that the request gives. It also
decoded each candidate item from item_data with serde. This branch
stores the strings of item_data through the escape, so the path read
the stored form. A filter value that holds U+0000 failed the jsonb
cast, and the condition read the escaped strings.

The search now builds the stored form of the equality filters once, for
the filtered path and the other path. The filtered path decodes each
candidate through json_to_item before it evaluates the condition, as
the other path decodes each hit.

a_filtered_vector_search_reads_control_characters_as_written in
crates/storage-postgres/tests/catalog_nul_index_writes.rs searches with
an equality filter on an inline filter attribute and with a condition.
The names and the values hold U+0000 and U+0001. The test checks that
the search returns the one item that matches both, as PutItem wrote it.
With the filters bound as the request gives them, the search fails with
SQLSTATE 22P05 (unsupported Unicode escape sequence). With the items
decoded by serde, it returns no item. The new helper vector_table builds
the table of this test and of a_vector_index_keeps_its_attribute_names.
Main is at 44a7b79, four commits past db8a90d: #1466, #1087, #768
and #1296. #1087 adds its v1.2.0 entry to
docs/manuals/07-upgrade-manual.md after the other v1.2.0 entries of
main, where this branch has its entry. That is the one conflict. The
merge keeps both entries without change: the entry of #1087 first, then
the entry of this branch, before the v1.1.0 entries.

Git merged three other files with no conflict:

- CONTRIBUTING.md: #1466 describes devtools/freeze-migrations in the
  step that freezes the released bodies. This branch gives the example
  migration the id 14 and adds migration 13 to the list of ids in use.
- crates/storage-mongodb/src/data_engine.rs: #1087 computes the
  parallel Scan segment with scan_segment in scan_key_in_segment and in
  scan_impl. This branch changes other functions.
- crates/storage/src/util/mod.rs: #1087 declares and exports
  scan_segment, and this branch declares and exports control_chars.

This branch has not been deployed

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

Labels

v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] PostgreSQL and MongoDB: an item containing U+0000 returns InternalServerError; the service accepts it

6 participants