Repository navigation
Conversation
A PutItem whose condition says only that the item must not exist, such as attribute_not_exists(pk), always took the transaction path. For a new item that is four statements: BEGIN, SELECT ... FOR UPDATE, INSERT ... ON CONFLICT DO NOTHING and COMMIT. The PartiQL INSERT statement is also such a put. Every stored item carries its key attributes, so such a condition holds against no item and fails against every item. The key alone decides it. When the put has nothing else to do in a transaction (no secondary or vector index, no stream, no old item to return or to size, and not a slow write), it is now one autocommit INSERT ... ON CONFLICT DO NOTHING: - A row inserted means the item did not exist. - No row means the condition failed. A second statement reads the item for ConditionalCheckFailedException, as the transaction path reports it. That read does not wait for a write in progress on the item; it returns the latest committed item. - If a delete committed between the two statements, the read finds no item and the insert is tried again, up to the existing limit of five inserts for a create race. - After the statement, the put calls fix_up_autocommit, as the unconditional autocommit put does, so a GSI created meanwhile is repaired. extenddb_core::expression::requires_absent_item decides which conditions qualify: attribute_not_exists on a top-level key attribute, through a literal name or a #name; attribute_exists on one under NOT; and AND or OR of such terms when they agree. It is a pure function of the parsed condition, next to removes_only, so another backend can use it too. A #name that does not resolve does not qualify, so its validation error does not change. [storage.postgres] create_only_puts (default true) turns the path off; with false, such puts take the transaction path again. The engine reads it through PostgresEngine::with_create_only_puts, so PostgresConfig does not change. PostgresStorageConfig, which is public, gains the field: a struct literal of it outside this crate needs the field or ..Default::default(), as tests/backup_restore.rs now has. When the item exists, the put is a little slower than before: the insert sends the whole item, and PostgreSQL checks the conflict, where the transaction path stopped at the locking read. Tests: - crates/core: unit tests for requires_absent_item. - tests/create_only_put.rs: absent and present items on a hash table and a hash-and-range table, for each form of the condition (literal name, #name, NOT attribute_exists, AND, OR); a condition on a non-key attribute still overwrites; concurrent create-only puts of one key have one winner, and every loser gets the winner's item; a table with a GSI keeps the transaction path; a delete between the failed insert and the read (forced with a gate trigger and an ACCESS EXCLUSIVE lock) makes the put retry and create the item, on both table shapes, and five such deletes make it give up; with the switch off, a create-only put waits for a row lock again; a micro-benchmark, ignored by default. - tests/gsi_stale_writer.rs: a create-only put that read "no index" and wrote after a GSI build is repaired. - config: create_only_puts defaults to true and accepts a string from an environment override. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: michael parsons <michael@twisp.com>
LeeroyHannigan
left a comment
There was a problem hiding this comment.
Thanks. I checked this against PostgreSQL 16:
- The statement counts match the description. A create-only put of a new key takes 3 statements instead of 6, and one of an existing key takes 4 instead of 5. I counted 300 requests per shape with
pg_stat_statements. - The classifier lets only
attribute_not_existsandattribute_existson key attributes through. I added 25 assertions on edge cases (comparisons,begins_with,size, nested paths, a#namefor a non-key attribute, tautologies), and each one stays on the transaction path. - The crate's tests pass, including your new ones and the create-race tests. The five failures I saw come from a backup-root ownership check on my host, and they fail the same way on main.
- 535 wire tests for conditional puts, the create race and PartiQL
INSERTpass against a server built from this head. - I didn't reproduce the end-to-end throughput tables. They need two release builds and a load driver, which I didn't run on this shared host. The micro-benchmark's ordering matches the description on a debug build.
Before it merges:
- It conflicts with main in
server_components_factory(crates/storage-postgres/src/lib.rs). #1003 replacedPostgresEngine::new(...)withPostgresEngine::open(..., DataConnection::Opened(...))and adrop(data_connection). Please rebase and chain.with_create_only_puts(...)after main'sopen(...). CI hasn't run at this head yet. tests/create_only_put.rsrepeats helpers the crate's tests already have.connect()andopen_gate_fully()match the ones intests/put_create_race.rs, the trigger SQL ingated_tableis the text ofinstall_gate, andbase_conn,shipped_migrationsandscratchexist intests/common/stream_disable_fixture.rs. Please move the gate helpers intotests/common/and use them from both files, or say in the description why you need a second copy.- The admin guide row (
05-admin-guide.md:137) leaves out two cases that keep the transaction path:ReturnConsumedCapacity, and a write that is already slower than 500 milliseconds. It should also say when to turn the switch off: a workload whose create-only puts mostly find the item runs slower with it on.
Optional: a create-only put that succeeds found no item, so ALL_OLD and ReturnConsumedCapacity don't need to keep it on the transaction path. Item 3 then needs no new words. The insert-if-absent statement text is also built twice for each key shape.
One conflict, in server_components_factory (crates/storage-postgres/src/lib.rs): ExtendDB#1003 replaced PostgresEngine::new(...) with PostgresEngine::open(..., DataConnection::Opened(...)) and a drop(data_connection). The factory now has main's open(...) with .with_create_only_puts(...) chained after it, before the drop. tests/key_ring_rows.rs, which main added, builds PostgresStorageConfig as a struct literal. It gets ..Default::default() for the create_only_puts field, as tests/backup_restore.rs has. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P Signed-off-by: michael parsons <michael@twisp.com>
…atement Changes from the review of 19 Nov. A create-only put that asked for the old item (ReturnValues = ALL_OLD or ReturnConsumedCapacity) took the transaction path. A create-only put that succeeds found no old item, so it has none to return or to size. Such a put now takes the one-statement path too. A table with a secondary index, a vector index or a stream, and a write that is already slow (GRACE_WRITE), keep the transaction path as before. The statement that inserts an item only if its key is absent was built in the transaction path and again in insert_absent. One function, insert_if_absent_sql, now builds it for both. Tests: - tests/common/insert_gate.rs has the gate trigger, the gate session, the outside connection and the lock waits. put_create_race.rs and create_only_put.rs both use it, and their own copies are gone. - create_only_put.rs uses the scratch database of common/stream_disable_fixture.rs in place of its own copy. - The create-only tests also run with return_old set: a put that creates the item returns no old item, a put that finds the item fails with it, and a failed put answers while an outside transaction holds the row lock, which the transaction path does not. Docs: the admin guide row for create_only_puts names the cases that keep the transaction path (an index, a stream, a write over 500 ms) and says when to turn the switch off. The design bullet says the same. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P Signed-off-by: michael parsons <michael@twisp.com>
|
Thanks for the review. The changes are at 16858bd. 1. Conflict with 2. Test helpers. The gate is in 3. Admin guide. I took the optional change first: Optional items. Both are done. The eligibility change is above. Tests at 16858bd.
I did not measure throughput again. The requests of the benchmark do not ask for the old item, so they took the same statements before and after the change. CI has not run at this head. |
LeeroyHannigan
left a comment
There was a problem hiding this comment.
I checked this head (16858bd) against PostgreSQL 16.
- You fixed the three items of my last review and took both optional points.
server_components_factorykeeps main'sopen(...)anddrop(data_connection), and chains.with_create_only_puts(...)after it. The gate helpers are intests/common/insert_gate.rs, and both test files use them. The admin guide row names the cases that keep the transaction path, and it says when to turn the switch off. - A create-only put with
ALL_OLDorReturnConsumedCapacitynow takes the one-statement path. At the storage interface it answers as the transaction path does, on both key shapes, with and without a stored item. A new key getsOk(None), and an existing key getsConditionFailedwith the whole stored item. - I ran 24 cases where another transaction updated, deleted or inserted the row and then committed or rolled back. In each case the put waited for it and then answered from the committed row. It wrote nothing on a row that existed, and it created the item only when the row was gone.
- Six writers made 240 create-only puts of one key while other sessions deleted and updated it. I ran three rounds with the switch on and three with it off. No write was lost or overwritten.
- The tests catch all 10 of my mutants of the eligibility check, the moved gate trigger and the classifier.
- On a release build, a create-only put of a new key takes 3 statements, and one of an existing key takes 4. The merge base takes 6 and 5. This holds with
ReturnValues: ALL_OLD,ReturnValuesOnConditionCheckFailure: ALL_OLDandReturnConsumedCapacity(TOTALandINDEXES). I counted 300 requests per shape withpg_stat_statements. - I reran the throughput tables at 1, 32 and 128 in flight. I used the generator from the #954 description, with a mode added for keys that exist. At 32 in flight, server CPU per request for new keys fell 19% for PutItem and 16% for INSERT. PostgreSQL CPU per request fell 27% and 29%. For a key that exists, it rose 9% on the server and 4% on PostgreSQL. The description gives 16% and 14% for the server, 27% for PostgreSQL, and 13% and 5% for a key that exists. On my host (load 15 to 34), requests per second moved more from round to round than the effects. So I can't judge the throughput ratios.
Before it merges, it needs another merge of main. Main moved to sqlx 0.9.1 (#1166), whose query functions take impl SqlSafeStr, so a &String no longer builds. The merge conflicts in crates/storage-postgres/src/data/put_item.rs and tests/put_create_race.rs. Eleven other sites merge without a conflict but don't build: the four statements of insert_absent, one in tests/common/insert_gate.rs and six in tests/create_only_put.rs. The resolution I tried keeps insert_if_absent_sql(...) at both conflict sites and passes it through sqlx::AssertSqlSafe(...). It keeps the gate helpers out of put_create_race.rs, moves main's AssertSqlSafe into install_gate, and wraps the eleven sites the same way. With it the merge builds, and the crate's tests pass, apart from five that fail on my host's backup-root ownership, as they do on main.
CI hasn't run at this head yet.
main moved to sqlx 0.9.1 (ExtendDB#1166), whose query functions take `impl SqlSafeStr`, so a `&String` no longer builds. Conflicts: - crates/storage-postgres/src/data/put_item.rs: both transaction-path inserts keep `insert_if_absent_sql(...)` and pass it through `sqlx::AssertSqlSafe(...)`. - crates/storage-postgres/tests/put_create_race.rs: the gate helpers stay in tests/common/insert_gate.rs; main's `AssertSqlSafe` moves into `install_gate` there. Eleven sites merged without a conflict but did not build, and are wrapped the same way: the four statements of `insert_absent`, one in tests/common/insert_gate.rs and six in tests/create_only_put.rs. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012kcRer5geZYy7TBPP5U5sD Signed-off-by: michael parsons <michael@twisp.com>
|
🤖 Agent: Thanks for the second pass. Main is merged at 64c093c. Merge of
Tests at 64c093c.
I did not run the wire tests or the throughput benchmark at this head. The merge changes how the statement text is passed to sqlx, not the statements. |
navareamol
left a comment
There was a problem hiding this comment.
I ran this head and its merge base 1a04dba, both as release builds on PostgreSQL 16. Counting statements in the PostgreSQL log, a create only PutItem or PartiQL INSERT on a new key takes 3 statements here and 6 at the merge base, and a put on a key that exists takes 4 and 5. With create_only_puts set to false the head goes back to 6 and 5. About 40 request shapes answer the same on both builds, including ALL_OLD, the item returned on a failed condition, ConsumedCapacity for new and existing items, legacy Expected, conditions that stay on the transaction path, and a table with a GSI and a stream. Twenty rounds of 12 writers on one key gave exactly one winner each round, and a delete and create churn on one key produced no 5xx. The PostgreSQL wire suites for conditional writes, the create race and PartiQL writes pass on both builds, so they do not tell the two apart; the statement count does. Clippy with the two feature sets of clippy.yml on 1.97.0 and fmt are clean on this head.
The speed figures in the description are bigger than mine. I measured server CPU per request with a different client at 32 requests in flight, three runs each. PutItem on a new key went from 546, 536 and 538 microseconds to 491, 489 and 488 (9 to 10 percent lower, the description says 16). INSERT went from 582, 579 and 573 to 530, 523 and 524 (9 percent lower, the description says 14). PutItem on an existing key went from 496, 493 and 490 to 526, 518 and 521 (6 percent higher, the description says 13). My client limited the request rate to about 2,900 per second, so I cannot say anything about the throughput numbers. Could you either rerun the CPU figures at this head and replace the table, or say in the description that they were measured at fd8e144 on your host?
I will approve once CI has run green at this head and the CPU figures in the description match a rerun at this head or say which commit they were taken at.
What
On PostgreSQL, a
PutItemwhose condition says only that the item must not exist is now one autocommitINSERT ... ON CONFLICT DO NOTHING, when the table has no index and no stream to maintain. Before, it always took the transaction path:BEGIN,SELECT ... FOR UPDATE, the insert andCOMMIT.crates/core/src/expression/ast.rs:requires_absent_item(condition, key_schema, maps), a pure function next toremoves_only. It answers true when the key alone decides the condition:attribute_not_existson a top-level key attribute (literal name or#name),NOT attribute_existson one, andANDorORof such terms when they agree. A#namethat does not resolve answers false, so the request keeps the path that reports the validation error. Another backend can use it too.crates/storage-postgres/src/data/put_item.rs: the decision input_item_impland one method,insert_absent, for both key shapes. A row inserted means the item did not exist. No row means the condition failed, and an autocommit read fetches the item forConditionalCheckFailedException, as the transaction path reports it. If that read finds no item, a delete committed between the two statements, and the insert is tried again, up to the existingMAX_CREATE_RACE_ATTEMPTS(5). After the insert the put callsfix_up_autocommit, as the unconditional autocommit put does. One function,insert_if_absent_sql, builds the insert statement for this path and for the transaction path.GRACE_WRITE, 500 ms).ReturnValues = ALL_OLDandReturnConsumedCapacitydo not keep it on the transaction path, as they do for an unconditional put: a create-only put that succeeds found no old item, so it has none to return or to size.[storage.postgres] create_only_puts, defaulttrue:falsekeeps these puts on the transaction path.PostgresStorageConfiggets the field (string values accepted, for environment overrides), the server factory passes it toPostgresEngine::with_create_only_puts, andPostgresConfigdoes not change. Theinittemplate has a commented line, and the admin guide's[storage.postgres]table has a row, which names the cases that keep the transaction path and says when to turn the switch off.docs/design/02-high-level-design.md, section 6.3: a bullet on create-only puts.The answers do not change. An insert of a key that another transaction is inserting or deleting waits for it, so one of several concurrent create-only puts of a key wins, as before. One difference in timing: when the condition fails, the read does not wait for a write in progress on the item, as the locking read does. It returns the latest committed item, and the put orders at that read.
Why
Closes #986
Create-only puts are the usual way to create an item only if it is new, and the PartiQL
INSERTstatement is one. For a new item they did twice the statements of an unconditional put.Measured on
mainat fd8e144 against this branch's first revision on fd8e144. I did not measure again after the merge ofmainat 44cd436 or after the change forALL_OLDandReturnConsumedCapacity: the requests of this benchmark ask for neither, so they took the same statements before and after it. Release builds (cargo build --release --locked -p extenddb) in a Debian 12 container, PostgreSQL 16 in a second container (fsync,synchronous_commitandfull_page_writesoff,shared_buffers2 GB, pool size 20), on a 24-core x86_64 Linux host that also ran other work. A fresh deployment for each measurement, three measurements of each build, in turns. The load: a table keyed on two binary attributes with no index and no stream, items of about 300 bytes,PutItemwithattribute_not_exists(#pk)on new keys, the same on keys that exist (each fails its condition), and PartiQLINSERTon new keys. Ten seconds for each step. CPU is the server process's and the PostgreSQL container's, divided by the requests; statements are frompg_stat_statements.32 requests in flight:
PutItem, new keymainINSERT, new keymainPutItem, key existsmainThe statements on
mainfor a new key:BEGIN, two catalog reads (indexes, vector indexes),SELECT ... FOR UPDATE, the insert andCOMMIT; on the branch, the two catalog reads and the insert.Other concurrency levels, requests/s per measurement:
PutItem, new keymainINSERT, new keymainPutItem, key existsmainPutItemand PartiQLINSERT. Server CPU per request fell by 14% to 16%, PostgreSQL CPU by 27%.create_only_puts = false.The micro-benchmark in
tests/create_only_put.rs(ignored by default, likettl_bench.rs) measures the two paths in one binary on one database:attribute_not_exists(pk) AND attribute_not_exists(zz)gives the same answer asattribute_not_exists(pk), but its second term is not a key attribute, so it keeps the transaction path. On this branch:Testing done
crates/core: unit tests forrequires_absent_item: the forms that qualify, and the ones that do not (a non-key attribute, a nested path, an unresolved#name, terms that disagree, other functions and comparisons).crates/storage-postgres/tests/create_only_put.rs(new, needsEXTENDDB_TEST_PG_CONNECTION_STRING; CI's storage step runs it through--tests):attribute_not_existson a non-key attribute still overwrites.BEFORE INSERTtrigger parks the insert on an advisory lock while a winner commits. Another session asks forACCESS EXCLUSIVEon the table, which queues behind the parked insert and then holds the put's read until it deletes the winner. The put retries and creates the item, on both table shapes. Five such deletes in a row make it give up with the create-race error and write nothing.create_only_putsoff, it waits for the lock, as on the transaction path.tests/common/insert_gate.rs, andput_create_race.rsuses it too. The scratch database is the one oftests/common/stream_disable_fixture.rs.put_create_race.rskeeps the scratch copy that it has onmain.tests/gsi_stale_writer.rs: the driver also sends a create-only put of a new item, which writes without a transaction when the pause is before the statement, and is repaired after a GSI build passed it.config.rs:create_only_putsdefaults totrueand accepts"false"from an environment override.fix_up_autocommit; no retry bound; the switch ignored;NOTnot negating (the core unit tests). At 16858bd, three more: a request for the old item sent back to the transaction path (the row-lock test fails); a gate trigger that does not wait (seven gate tests fail, three increate_only_put.rsand four input_create_race.rs);insert_if_absent_sqlwithoutON CONFLICTon the range shape (nine tests fail in the two files).mainat 44cd436 merged in):cargo test --locked -p extenddb-core -p extenddb-storage-postgresagainst PostgreSQL 16: 1,619 passed, 2 failed, 6 ignored. The two arecatalog_nul_backup_jobscases that fail the same way onmainon this host: the filesystem backup store refuses its root because the checkout's parent directories are group-writable.devtools/run-tests --extenddb --pytest --filter <word>) against a release build of 16858bd, on a fresh deployment, for the filtersconditional,put_item,consumed_capacity,item_operationsandpartiql: 72, 89, 25, 129 and 3,135 passed, with no failure. One test errored in its setup:test_metrics_accounts.py, which theconditionalfilter selects by a parameter name, needs thethrottling_enabledsetting, and my deployment has it off.mainand of this branch, on fresh deployments. In the files for items, conditions, PartiQL (other than authorization), batches, transactions, concurrency, queries, scans, updates, deletes, streams and indexes (62 files): 3,867 passed on both, and the same 2 failed on both (test_gsi_asyncpropagation-delay tests). No test of the data path differed. I did not repeat the whole suite at 16858bd.cargo test --workspaceor the dual-target conformance runs against Amazon DynamoDB.With
-W clippy::pedanticat 16858bd, the changed files have no new warnings, but two functions that were already over thetoo_many_lineslimit grew:put_item_implfrom 340 to 346 lines andserver_components_factoryfrom 111 to 116.Checklist
cargo test --workspace): not run locally; the crates that change pass at 16858bd, except the twocatalog_nul_backup_jobscases above, which fail the same way onmainon this hostcargo fmt --check)cargo clippy -- -W clippy::pedantic): no new warnings, apart from the two longer functions above; theclippy.ymlcommands pass with-D warningsStoragetrait, auth model, on-diskformat, or public CLI surface, an RFC has been accepted or is linked
below. Otherwise, an ADR captures the decision (link below).
ADR / RFC: n/a. One backend's write path for one class of condition; no wire, trait, auth, on-disk or CLI change. The new
[storage.postgres] create_only_putskey is in the admin guide. If you want an ADR for the default, I will add one.Breaking changes
None for the wire or for deployments: the answers are the same, and existing configuration files work unchanged. For Rust code that uses the crate:
extenddb_storage_postgres::PostgresStorageConfig, which is public, has a new field, so a struct literal of it needscreate_only_putsor..Default::default()(astests/backup_restore.rsandtests/key_ring_rows.rsnow have).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.
🤖 Generated with Claude Code
https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P