Repository navigation
fix(storage): plan an LSI query as an index walk on PostgreSQL and SQLite - #432
Conversation
8a6404d to
736d171
Compare
|
Rebased on main at abf8082; conflicts in .github/workflows/integration.yml, resolved by keeping both test entries: the PostgreSQL storage-level step runs gsi_online_build, gsi_stale_writer and lsi_query_plan, and its comment describes both. The earlier merge of main is folded into the one commit. crates/storage-postgres (lsi_query_plan included, on PostgreSQL 16) and crates/storage-sqlite tests pass. |
736d171 to
e9d3045
Compare
…Lite DynamoDB returns a Query on a local secondary index ordered by the index sort key, with the items that share an index sort key value in one deterministic order, and a reverse Query as the exact mirror of the forward one (measured 2026-10-21; the order inside such a group differs from ExtendDB's byte order and is tracked in #425). ExtendDB orders an LSI partition by the index sort key, then the base table sort key, and pages through it with a cursor over the same columns. Every index table whose index has a sort key has an ordering index on (pk, sk, base_pk, base_sk) on the PostgreSQL and SQLite backends, with one sk column per RANGE attribute. A GSI Query orders by its RANGE columns in key-schema order, then base_pk and base_sk, which is that index without the constant pk, so both databases walk the index and stop at the page limit. An LSI Query ordered by (sk, base_sk) and its cursor compared the same two columns. Neither planner can tell that base_pk is constant inside an LSI partition, so the index served the index sort key only. PostgreSQL planned an Incremental Sort over the index scan when the key condition left several index sort key values and a Sort when an equality left one; SQLite used a temporary B-tree for the last term of the ORDER BY, and seeked a resumed page on the index sort key alone. On an LSI partition of 50,000 items with 50 items per index sort key value, a PostgreSQL page with Limit 100 read 151 rows and 154 buffers to return 101, and a page resumed inside a group read 130 rows and 133 buffers. The LSI ORDER BY and cursor now list base_pk between the index sort key and the base sort key, the same columns a GSI with one RANGE attribute uses, so the ORDER BY is the ordering index without pk. Every row of an LSI partition stores the queried partition key as base_pk. The cursor binds the queried partition key for it, not the start key's partition key, so base_pk compares equal on every row and the base sort key orders the rows as before. The rows, their order, the page boundaries and the LastEvaluatedKey and ExclusiveStartKey shapes do not change. On SQLite the statement builder moves out of query_impl into query_statement so the plan tests can explain the statement a Query sends. Measured on servers built from this branch and from main, on the same 52,000 items: the LSI pages plan as an Index Scan or Index Scan Backward on the ordering index with the cursor in the Index Cond and no sort node, in both directions, in the custom and the generic plan, reading 101 rows and 103 to 105 buffers. SQLite plans SEARCH USING INDEX idx_order_* with no temporary B-tree and seeks a resumed page on (sk_s, base_pk, base_sk_s). The GSI plans and buffer counts are unchanged. The items and LastEvaluatedKey of every measured page are identical before and after on both backends. crates/storage-postgres/tests/lsi_query_plan.rs reads the statement the engine sent from pg_stat_activity and asserts that its generic and custom plans have no Sort or Incremental Sort node and no Filter under the index scan, for a first page and a resumed page with the partition alone, with lsk = :l, and with lsk BETWEEN, in both directions. It also checks the page rows and that a start key naming another partition returns the same page. It skips below PostgreSQL 16, which added EXPLAIN (GENERIC_PLAN). CI runs it in the PostgreSQL storage-level step. The SQLite plan tests (crates/storage-sqlite/src/data/query_scan/plan_tests.rs) assert no temporary B-tree for the same LSI shapes and for GSI pages, and page through an LSI in both directions. The cursor unit tests on both backends assert the new LSI fragment and bind. A GSI with several RANGE attributes orders by every RANGE column (#429). crates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs, a module of the lsi_query_plan test, and a fourth SQLite plan_tests case run such a GSI with RANGE attributes a, b and c for the partition alone, an equality on a, an equality on a with b BETWEEN, and equalities on all three, first and resumed pages in both directions, and assert the same index walk; both also check the rows of the pages. Their plan checks pass on main. With the ORDER BY cut to the first RANGE column, the SQLite case sorts in a temporary B-tree and the PostgreSQL case returns the first page out of order. With a condition applied to the first RANGE column instead of the one it names, the SQLite case returns no rows for a = :a AND b BETWEEN. With base_pk removed from the LSI ORDER BY, the PostgreSQL plan test and the SQLite LSI plan test fail on the sort node; the SQLite GSI plan test and paging test pass, as the rows do not change. With base_pk removed from the LSI cursor comparison, the PostgreSQL plan test fails on the Filter under the index scan and the SQLite cursor unit tests fail on the fragment; the paging tests pass. With the start key's partition key bound instead of the queried one, the PostgreSQL other-partition page check and the SQLite bind test fail. tests/test_query_scan.py and tests/test_multipart_gsi.py pass on both backends. docs/design/04-component-storage.md describes the LSI cursor and ORDER BY and the sort step they avoid. Closes #366
e9d3045 to
16a1b92
Compare
.github/workflows/integration.yml conflicted. Main runs every test target of extenddb-storage-postgres with --tests, so the step no longer lists the LSI query plan test by name. The comment keeps this branch's sentence on what that test reads. Main removed crate::schema::apply from extenddb-storage-sqlite. The SQLite plan tests now create their schema with crate::migrations::apply_for_tests, as main's other unit tests do.
Main's migrations no longer seed the control_plane_delay_seconds row in settings, so the UPDATE that set it to zero in these tests changed no row. The engine kept its default delay, CreateTable left the table CREATING, and table_key_info then returned TableNotFound. The tests now insert the row or update it, as main's own tests do.
demohan
left a comment
There was a problem hiding this comment.
On the wire, this head answers as the merge-base does, and on PostgreSQL 16 and SQLite the LSI query no longer has the sort step the issue describes.
Four statements in the body do not match this head:
- An LSI start key from another partition gets 400 ValidationException, not a resumed page.
- The CI step already ran
--tests, so no--test lsi_query_planwas added. - With
lsk = :lor BETWEEN, SQLite seeks onsk_sand applies the cursor as a filter (SEARCH ... (pk=? AND sk_s=?)), with no temporary B-tree. - The gate tallies are for 16a1b92 and 03d9c72e3.
Two items need to change before merge: the merged tree must compile, and the plan tests must honour EXTENDDB_TEST_PG_REQUIRED. The Minor items inline go in the same pass.
| .map(s_attr) | ||
| .collect(), | ||
| billing_mode: Some(BillingMode::PayPerRequest), | ||
| global_secondary_indexes: Some(vec![GsiInput { |
There was a problem hiding this comment.
Main added warm_throughput to GsiInput in #474, so this literal no longer compiles after a merge of main: error[E0063]: missing field 'warm_throughput' in initializer of 'GsiInput' at 46:45. With warm_throughput: None, added, cargo test -p extenddb-storage-postgres --tests on the merged tree passes (38 binaries, 460 passed).
There was a problem hiding this comment.
Merged main in 6f06bfe, with warm_throughput: None in this literal. The merged tree builds, and both plan tests pass on it against PostgreSQL 16.15.
| } | ||
| out | ||
| } | ||
|
|
There was a problem hiding this comment.
skip returns success whether or not EXTENDDB_TEST_PG_REQUIRED is set, and the version check at 469 does the same. With EXTENDDB_TEST_PG_REQUIRED=1 and no connection string, both tests print SKIP and report 2 passed; against PostgreSQL 15 they do the same. gsi_stale_writer.rs:75 fails in that case. The same applies to multi_range_gsi.rs:202 and :209.
There was a problem hiding this comment.
Fixed in c74e307. With EXTENDDB_TEST_PG_REQUIRED set, both tests now fail when there is no connection string or the server is older than 16, as gsi_stale_writer.rs does without a connection string. Without it they still skip. Both tests take the two checks from one helper, now in lsi_query_plan/scratch.rs (83198b8).
| } | ||
|
|
||
| /// The plan for `statement` with `values` bound, as the first executions get. | ||
| async fn custom_plan(db: &PgPool, statement: &str, values: &[&str]) -> Vec<String> { |
There was a problem hiding this comment.
custom_plan is given four values for every resumed page. With the cursor reverted to (sk_s, base_sk_s), the statement has three parameters, and the test fails on the bind count, not on the plan. Bound with its own three values, that statement plans Index Cond: ... ROW(sk_s, base_sk_s) > ROW($2, $3) with no Filter and no Sort, and reads 85 buffers, the same as the new cursor. The test does not detect a cursor that omits base_pk.
There was a problem hiding this comment.
Reproduced: the reverted cursor plans ROW(sk_s, base_sk_s) > ROW($2, $3) as an index condition, so the plan checks passed and the test failed on the bind count. At 50 items per lsk value both cursors read 90 buffers here. With 20,000 items that share one value, the reverted cursor read 180 buffers for a page near the end of the group. The cursor with base_pk read 4. Since c74e307 a resumed page's plan must hold the cursor as one index condition over the ORDER BY columns. The reverted cursor fails that check on the generic plan of the first resumed page.
| // partitions and can also share a base SK. An LSI binds the | ||
| // queried partition key, which every row of the partition | ||
| // carries as its base_pk. base_pk then compares equal on every | ||
| // row, and only the base SK separates a row from the cursor. |
There was a problem hiding this comment.
Request validation already refuses an LSI start key from another partition. validate_query_start_key_bounds in crates/engine/src/start_key.rs returns 400 ValidationException "The provided starting key is outside query boundaries based on provided conditions" here, as the service does. The same comment is at crates/storage-sqlite/src/data/query_scan.rs:508 and lsi_query_plan.rs:593.
There was a problem hiding this comment.
Removed in cb90d04. handle_query runs validate_query_start_key_bounds before storage reads anything, so no request reaches this branch with a start key from another partition. Both backends now bind the start key's partition key as base_pk, as a GSI does. The SQLite bind test and this test's check for such a key are gone. Measured on DynamoDB on 2026-11-20, twice per shape: the partition alone gets the sentence you quote. With lsk = :l or BETWEEN the answer is "The query can return at most one row and cannot be restarted", which the validation also returns.
| //! them. | ||
| //! | ||
| //! Each test builds its own throwaway database, applies the shipped migrations | ||
| //! to it, and drops it when it passes. A failing test leaves its database behind |
There was a problem hiding this comment.
A failing run keeps its eddb_lsip_* database. After four failing runs, six remained on the server. The repository guide asks tests to clean up even on failure. A drop guard would remove the database, and the failure message already prints the statement and the plan.
There was a problem hiding this comment.
Fixed in c74e307: a guard drops the scratch database when the test ends, a failed assertion included. With the cursor mutated so that both tests fail, the server had the same number of eddb_lsip_* databases before and after the run.
| @@ -0,0 +1,501 @@ | |||
| use super::*; | |||
There was a problem hiding this comment.
This file has no // Copyright 2026 ExtendDB contributors and // SPDX-License-Identifier: Apache-2.0 header. The other new files in this change have one.
| OR (base_pk = $base_pk AND base_sk_n > $base_sk)))) | ||
| ``` | ||
|
|
||
| **LSI Query:** an LSI cursor compares the index sort key, then `base_pk`, then |
There was a problem hiding this comment.
This paragraph says the LSI cursor runs in the same order and direction as the GSI cursor above. The paragraph above says a reverse GSI cursor keeps the base key ascending in an expanded OR form. The code emits one (sk_s, base_pk, base_sk_n) < (...) comparison with every column DESC. Read together, the two paragraphs describe a reverse query wrongly until #428 replaces the reverse paragraph.
Main added the warm_throughput field to GsiInput (#474). The GSI literal in the multi-RANGE plan test had no value for it, and the merged tree did not compile (E0063 at multi_range_gsi.rs:46). The literal now sets warm_throughput to None, as the other storage tests do.
The other files this change adds start with the copyright line and the SPDX license identifier. plan_tests.rs had neither.
The LSI paragraph said the cursor runs in the same order and direction as the GSI cursor above it. The reverse GSI paragraph above describes an expanded OR form with the base key ascending. The code emits one row comparison, with every column in the direction of ScanIndexForward. The LSI paragraph now states that rule itself: `>` and ASC forward, `<` and DESC in reverse. Its long sentences are split, with no change to what they say.
The LSI cursor bound the queried partition key as base_pk, so that a start key from another partition resumed inside the queried one. No request reaches storage with such a key: handle_query runs validate_query_start_key_bounds before the read, and it refuses the key with a ValidationException. Measured on DynamoDB on 2026-11-20, twice per shape, the service answers the same way: - the partition alone, either direction: "The provided starting key is outside query boundaries based on provided conditions". - lsk = :l or lsk BETWEEN: "The query can return at most one row and cannot be restarted". Both backends now bind the start key's base partition key for every index, as a GSI does. On an LSI that is the queried partition key. The change removes is_lsi from the PostgreSQL query_impl, from the SQLite query_statement and from append_query_pagination. It also removes the partition key argument of append_query_pagination and the SQLite bind test for a start key from another partition. The PostgreSQL plan test no longer checks such a key.
…tests The two plan tests reported a skip and passed with EXTENDDB_TEST_PG_REQUIRED set, both with no connection string and on a server older than PostgreSQL 16. Both cases now fail under that variable, as in gsi_stale_writer.rs. One helper, which both tests call, holds the two checks. A failing test kept its scratch database on the server. A guard now drops the database when the test ends, a failed assertion included. A resumed page's plan must now hold the cursor as one index condition over the ORDER BY columns. A cursor without base_pk is still an index condition, ROW(sk_s, base_sk_s), so the plan checks passed on it. The test failed only because the custom plan got four values for a statement with three parameters. With 20,000 items that share one lsk value, that cursor read 180 buffers for a page near the end of the group. The cursor over (sk_s, base_pk, base_sk_s) read 4. The LSI and multi-RANGE tests now share one assert_index_walk.
…module lsi_query_plan.rs grew to 677 lines with the database guard and the EXTENDDB_TEST_PG_REQUIRED checks. The scratch database code (Scratch, its guard, the connection string and version checks, and the migrations) moves unchanged to lsi_query_plan/scratch.rs. Only the visibility of Scratch, its fields and scratch_or_skip changes, so that the test files can use them. lsi_query_plan.rs is now 500 lines.
…heck The SQLite walk over LSI pages had no page limit, so a cursor that repeats a page kept the test running until the job's timeout. It now fails when the walk needs more pages than there are items. With the base_pk bind emptied, the test fails in place of hanging. base_conn asserted EXTENDDB_TEST_PG_REQUIRED before it returned None. Its one caller then calls skip, which asserts the same setting with the test's name, so base_conn now returns None only. The comment above the PostgreSQL index cursor binds points to the PaginationBinds::BasePkAndSk doc in place of a copy of it.
|
Item by item:
|
demohan
left a comment
There was a problem hiding this comment.
The items from the earlier review are resolved at c85f014.
- An LSI start key from another partition answers 400 ValidationException on the service, on SQLite and on PostgreSQL 16, in 7 request shapes with 2 start keys each, sent twice. With only the partition key in the condition it is "The provided starting key is outside query boundaries based on provided conditions". With
lsk =,BETWEEN,>or the legacy EQ it is "The query can return at most one row and cannot be restarted". - The cursor now binds the start key's partition key. 2341 checks over LSI walks with S, N and B partition keys, both directions, Limit 1 to 7, five key conditions, with and without a filter, pass on both backends: every paged walk equals the unpaged result. A start key of
1.00resumes a walk queried as1.0. With an empty partition key bound instead, 688 of the checks fail. - The SQLite plans for a resumed
lsk = :land forBETWEENare index searches with no temporary B-tree.lsi_query_planruns in CI withEXTENDDB_TEST_PG_REQUIRED=1and fails on PostgreSQL 15 or with no connection string. With the cursor reduced to three columns, the plan test fails on the index condition. No scratch databases remain after a failing run. - CI is green on 58 of 58 checks.
#432 added base_pk to the LSI Query cursor and to its ORDER BY on PostgreSQL and SQLite. Three passages of this branch still described the cursor without it. - Section 5.1 names the LSI Query cursor beside the GSI one. Section 7 keeps the Scan cases. - The section 7 introduction says that a key index serves every shape below, and that for a GSI or LSI it is the ordering index. - The plan paragraph gives the LSI plans of the plan test that #432 added. Both plans of each page with an equality are an Index Scan at Limit 10. At Limit 101 the custom plan of the first page is a Sort over a Bitmap Heap Scan.
Main is at 6aef346, 2 commits after the last merge (#432 and #468). No file has a conflict. Three files changed on both sides, and git merged each of them with no overlap: docs/differences-from-dynamodb.md, crates/storage/src/lib.rs and crates/storage-cassandra/tests/direct_integration.rs. #468 adds a Streams section to the differences page, a method to the StreamEngine trait and a test module to the Cassandra direct tests. This branch changes the index key validation row, the transact exports and the token test module.
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.
…e emits (ExtendDB#428) * docs(design): describe the query cursor as the row comparison the code emits The reverse GSI cursor example in docs/design/04-component-storage.md showed an expanded OR with an ascending base-key tiebreaker under a descending sort key. The PostgreSQL and SQLite query builders emit one row comparison for every cursor shape, with every column, tiebreaker included, following ScanIndexForward, so a reverse page is the exact mirror of the forward one as it is on the service. The base table Scan examples in the same section showed an OR form too; the Scan cursor is the row comparison (pk, sk) > ($pk, $sk) and Scan has no reverse direction. Section 7 states the rule (cursor columns equal the ORDER BY columns, same order, same direction, > forward and < reverse, a plain comparison when the cursor has one column), shows the Scan, base table Query, forward GSI and reverse GSI statements with their ORDER BY, and describes the LSI shape (index sort key then base sort key, which the ordering index does not serve without a sort step because it carries base_pk between them), the hash-only index shape, and the forms on a base table without a sort key. The section 5.1 sentence on collation now limits the one-seek claim to GSI cursors. Closes ExtendDB#370 * docs(design): qualify the cursor plans by collation and show the index Scan cursor Section 7 of docs/design/04-component-storage.md now names the index that serves each cursor shape and the tables it holds on. The no-sort statement applies to tables created with the collated key columns. The Scan on an index with more than one RANGE attribute still sorts. On older PostgreSQL tables the indexes do not serve a COLLATE "C" predicate. The statements put COLLATE "C" on base_pk and on every string sort key column. Where the first cursor column other than pk is one of these, PostgreSQL reads the rows through the pk prefix of the key index. It sorts them on every page (technical debt C-11). A hash-only index has no ordering index, so its page comes from the primary key or from the base-key index. The LSI paragraph now says that the database applies the cursor while it reads the index. It then sorts the rows that share an index sort key value and applies the LIMIT. EXPLAIN (ANALYZE) on PostgreSQL 16.15 shows the row comparison in the Index Cond under an Incremental Sort with Presorted Key sk_s. EXPLAIN QUERY PLAN on SQLite shows SEARCH (pk=? AND sk_s>?) and then a temporary B-tree for the last ORDER BY term. The section gains three blocks. The cursor of a GSI with more than one RANGE attribute, which ExtendDB#429 added to main. The index Scan cursor (pk, sk, base_pk, base_sk) with its ORDER BY. The hash-only base table cases: the Scan cursor is pk > $last_pk, and a Query with an ExclusiveStartKey returns no items without a statement. The intro names the PostgreSQL and SQLite backends, because MongoDB and Cassandra do not translate the cursor to SQL. Each plan statement comes from EXPLAIN on tables the server created and on copies whose key columns keep the database collation. The SQLite plans come from EXPLAIN QUERY PLAN on the database the server created. * docs(storage-sqlite): describe the pagination cursor as the row comparison the code emits The README listed OR-expansion for pagination as a difference from the PostgreSQL backend, because SQLite lacked row-value comparison. The SQLite builder emits the same row comparison as PostgreSQL, with ? placeholders and no COLLATE, in scan_impl and append_query_pagination of crates/storage-sqlite/src/data/query_scan.rs. The line now says so. * docs(design): limit the cursor plan statements to the statements shown Section 7 said the primary key serves "the Scan", which covered index Scans. The ordering index serves a GSI or LSI Scan. It now says the base table Scan and Query. The plan statements hold for the statements shown, which carry no sort key condition. A paragraph after the intro says what PostgreSQL and SQLite plan with one. PostgreSQL planned a Sort on every page with an equality on the index sort key, and SQLite seeks on the condition's terms. The legacy-table text gains the case where a later cursor column carries the collation (an Incremental Sort). The reverse GSI paragraph states the rule for the tiebreaker in place of the history of a fixed defect. Section 5.1 named four collated columns and said the ordering index serves every GSI cursor in one seek. A hash-only GSI has no ordering index, and the numbered sort key columns carry the collation too. The sentence now names the text key columns and both indexes. * docs(design): say that a Query resuming on a table without a sort key is refused Section 7 said that a Query with an ExclusiveStartKey on a table without a sort key returns no items and runs no statement. The engine refuses it before storage: start_key.rs answers ValidationException with The provided exclusive start key is invalid. The sentence now says so. * docs(design): describe the LSI cursor main has since ExtendDB#432 ExtendDB#432 added base_pk to the LSI Query cursor and to its ORDER BY on PostgreSQL and SQLite. Three passages of this branch still described the cursor without it. - Section 5.1 names the LSI Query cursor beside the GSI one. Section 7 keeps the Scan cases. - The section 7 introduction says that a key index serves every shape below, and that for a GSI or LSI it is the ordering index. - The plan paragraph gives the LSI plans of the plan test that ExtendDB#432 added. Both plans of each page with an equality are an Index Scan at Limit 10. At Limit 101 the custom plan of the first page is a Sort over a Bitmap Heap Scan.
What
crates/storage-postgres/src/data/query_scan.rs:order_by_columnsputsbase_pkbetween the index sort key columns and the base sort key for every index with a sort key. Theis_lsiparameter is gone from it, frombuild_pagination_whereand fromquery_impl. Every index cursor binds the start key's base partition key asbase_pk. On an LSI that is the queried partition key, because request validation refuses any other. Cursor unit tests updated.crates/storage-postgres/src/data/query.rs:PaginationBinds::BaseSkOnlyremoved (no remaining user).crates/storage-sqlite/src/data/query_scan.rs: the same column change inquery_order_columns.append_query_paginationand the newquery_statementtake nois_lsi, and every index cursor binds the start key's base partition key. The statement builder moves fromquery_implintoquery_statementwith no behaviour change, so tests can runEXPLAIN QUERY PLANon the statement a Query sends. Cursor unit tests updated. Newplan_testsmodule incrates/storage-sqlite/src/data/query_scan/plan_tests.rs.crates/storage-postgres/tests/lsi_query_plan.rs: new storage-level plan test. It reads the statement the engine sent frompg_stat_activityand asserts that the generic plan and the custom plan are an index walk. That means no Sort or Incremental Sort node and no Filter under the index scan. The assertion covers a first page with the partition alone and withlsk = :l, and a resumed page with each of those and withlsk BETWEEN, in both directions. It checks the page rows, and that the plan of a resumed page holds the cursor as one index condition over theORDER BYcolumns. It skips without a connection string and below PostgreSQL 16 (EXPLAIN (GENERIC_PLAN)), and fails in both cases whenEXTENDDB_TEST_PG_REQUIREDis set. A guard incrates/storage-postgres/tests/lsi_query_plan/scratch.rsdrops its scratch database when the test ends, a failed assertion included. Its scratch database builder repeats the one incrates/storage-postgres/tests/common/stream_disable_fixture.rs, which has no drop guard and drops a stream foreign key. One shared builder intests/common/would change the stream-disable tests too, so it is a follow-up after merge.crates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs: the same plan check for a GSI with RANGE attributesa,bandc, a module oflsi_query_plan..github/workflows/integration.yml: the comment on the PostgreSQL storage-level step (pgvector/pgvector:pg16) names the LSI plan test. The step already runscargo test --release -p extenddb-storage-postgres --tests, which includes it, so the change adds no target.docs/design/04-component-storage.md: the LSI Query paragraph in section 7, with the statement, the bind, and the sort step the ordering index avoids.The cursor token format and the
LastEvaluatedKeyshape do not change.Merge after #428
This branch merges after #428. The LSI paragraph in
docs/design/04-component-storage.mddepends on the section 7 text #428 introduces (the**... Query:**headings, explicitASCandDESC, the hash-only and no-base-sort-key paragraphs). Merged on top of #428, this branch replaces #428's LSI paragraph. If this branch merges first, #428 meets the same hunk at its rebase. Either way the merge needs the five edits below, checked against #428's head 8187363. The conflict is one hunk, plus five #428 sentences that merge cleanly but describe the LSI cursor or the LSI plan this change removes:LSI Query:paragraph and SQL block in place of docs(design): describe the query cursor as the row comparison the code emits #428'sLSI Query:paragraph. Keep docs(design): describe the query cursor as the row comparison the code emits #428'sGSI with more than one RANGE attribute:,Hash-only index:andIndex Scan:paragraphs and the "On a base table without a sort key" paragraph. Apply edit 4 to theIndex Scan:paragraph.Index Scan:paragraph: replace "The LSI Scan keepsbase_pk, which the LSI Query drops, so the ordering index serves it with no sort step." with "The ordering index serves the LSI Scan with no sort step."BETWEENkept the Index Scan, and SQLite seeks on the condition's terms and applies the cursor as a filter." with "With an equality on the index sort key, PostgreSQL planned a Sort over a Bitmap Index Scan on every GSI page. ABETWEENkept the Index Scan. On an LSI with 50 items per sort key value, both plans of each page with an equality were an Index Scan at Limit 10. At Limit 101, the custom plan of the first page was a Sort over a Bitmap Heap Scan. SQLite seeks on the condition's terms and applies the cursor as a filter."The LSI sentences of edit 5 come from the plan test's table at this head, on PostgreSQL 16.
lsi_query_planpasses at its Limit 10. With its page size raised to 100 (Limit 101), it fails on the custom plan of the first forward page.This branch also changes the comment above the PostgreSQL storage-level step in
.github/workflows/integration.yml, and #550 changes the same comment. #598 and #599 branch from #550 and carry the same hunk. The second of these to merge keeps the sentence each one adds.Rebase on #429
This branch rebased on main at
f49c5f82(#429) on 1 November. #429 orders a Query on a GSI with several RANGE attributes over every RANGE column. On PostgreSQL the functions areorder_by_columnsandbuild_pagination_where, and on SQLitequery_order_columnsandappend_query_pagination. They take the queried key schema's RANGE attributes as a slice in place of the first one, and keepis_lsi. This change removesis_lsifrom the same functions, so bothquery_scan.rsfiles conflicted.The resolved functions take #429's slice and drop
is_lsi. An index with a sort key orders by its RANGE columns in key-schema order, thenbase_pk, then the base sort key. That is the column order of its ordering index afterpk. Since cb90d04 an LSI cursor binds the start key's partition key, as a GSI cursor does. Request validation refuses a start key from another partition. GSI columns are the same as on main, with one RANGE attribute or several. Only the LSI columns differ from main, as they did before the rebase.On SQLite,
query_statementnow holds #429's statement code, which applies each RANGE condition to the column of the attribute it names..github/workflows/integration.yml,query.rsand the design doc merged without a conflict.The plan tests now cover a GSI with RANGE attributes
a,bandc. On PostgreSQL that iscrates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs, a module of thelsi_query_plantest. On SQLite it is a fourthplan_testscase. Each runs the partition alone, an equality ona, an equality onawithb BETWEEN, and equalities on all three. It runs first and resumed pages in both directions. It asserts a walk of the ordering index with no sort step.Both also check the rows of the pages. The PostgreSQL test checks every page it plans. The SQLite case checks every page of each shape read with
Limit7 in both directions. Their plan checks pass on main too, because main already orders such a GSI over every RANGE column. They stay because this change edits the column builder that GSI and LSI statements share. It also moves #429's statement code intoquery_statement. The cases check that GSI plans and rows do not change. The SQLite plan tests are in their own file,crates/storage-sqlite/src/data/query_scan/plan_tests.rs, soquery_scan.rsis 920 lines here (883 on main).Merged main
The branch merged main (6f06bfe, 2026-11-20). The multi-RANGE test's
GsiInputliteral setswarm_throughput: None, the field #474 added.Why
Closes #366.
What the service does
The measurement of 2026-10-21 used a DynamoDB (pk, sk) table with an LSI on (pk, lsk) and 9 items in three groups of equal
lsk. A Query on the LSI returns the items ordered bylsk. The service returns the items inside a group in one deterministic order (the same across two tables). A reverse Query is the exact mirror of the forward one. Page boundaries andLastEvaluatedKey({lsk, pk, sk}) follow that order.The order inside a group is not byte order of the base sort key. That difference is #425.
What ExtendDB did
Every index table whose index has a sort key has an ordering index on
(pk, sk, base_pk, base_sk)on PostgreSQL and SQLite, with oneskcolumn per RANGE attribute. A GSI Query orders by its RANGE columns in key-schema order, thenbase_pkandbase_sk((sk, base_pk, base_sk)with one RANGE attribute). Those are the ordering index's columns without the constantpk, so the database walks the index and stops at the Limit. An LSI Query ordered by(sk, base_sk)with a cursor over the same columns.The planners cannot tell that
base_pkis constant inside an LSI partition, so the index servedskonly. PostgreSQL added an Incremental Sort over the index scan (a Sort whenlsk = :lleft one value). SQLite added a temporary B-tree for the last ORDER BY term and seeked a resumed page onskalone. On a 50,000-item partition with 50 items perlskvalue, a Limit 100 page read 151 rows and 154 buffers on PostgreSQL to return 101. A page resumed inside a group read 130 rows and 133 buffers.Related behaviour
ExclusiveStartKeywhose partition key differs from the queried partition: the service returns HTTP 400ValidationException(measured 2026-11-20, twice per shape). With the partition alone, in either direction, the message isThe provided starting key is outside query boundaries based on provided conditions. Withlsk = :lor BETWEEN it isThe query can return at most one row and cannot be restarted. Request validation (validate_query_start_key_bounds, fix(query): refuse a Query ExclusiveStartKey the key condition cannot reach #483) answers the same before storage reads anything.Limiton the last item of a partition. For that Query, the service returns the page with aLastEvaluatedKeyon some calls and without one on others (Query on an index returns a LastEvaluatedKey on the page that holds the last item; the service does so for base tables only #434, measured 2026-10-23). ExtendDB returns the key and then an empty page.(sk, base_pk, base_sk). It resumes an LSI page with up to three statements over that order (sk = :s AND base_pk = :p AND base_sk > :b,sk = :s AND base_pk > :p,sk > :s), so its rows return in clustering order.Testing done
Verification
The servers ran a build of the pre-rebase head
e9d30451e, against PostgreSQL 16.15 and SQLite in memory. The plans come from the servers' own statements: PostgreSQLEXPLAIN (ANALYZE, BUFFERS) EXECUTEandEXPLAIN (GENERIC_PLAN), and SQLiteEXPLAIN QUERY PLAN. The rebase changed no LSI statement, and these rows did not run again on03d9c72e3.=,>,<,<=,>=,begins_with,BETWEEN, engine chunks), both directionsSEARCH ... USING INDEX idx_order_*, no temporary B-tree (was a temporary B-tree). A resumed page with no condition onlskseeks on(sk_s, base_pk, base_sk_s)(wassk_sonly): 1,196 VM opcodes per LIMIT 98 page, was 2,892. Withlsk = :l, BETWEEN,begins_with, or>and>=on a forward page, SQLite seeks on thesk_scondition ((pk=? AND sk_s=?),(pk=? AND sk_s>? AND sk_s<?)). It applies the cursor as a filter, on main and on this branch. The last three were measured with SQLite 3.50.4, not the bundled 3.46.0. #1256 tracks it.LastEvaluatedKey)Count,LastEvaluatedKeykeystest_item_operations.py,test_table_operations.py,test_put_item_create_race.pyThe rows below are for the rebased head. The servers (SQLite and PostgreSQL 16) and the PostgreSQL tests ran on
03d9c72e3. That is the rebased commit before the SQLite plan tests moved into their own file and the multi-RANGE case gained its row check. The SQLiteplan_testsand cursor unit test rows ran on16a1b92f1:tests/test_query_scan.py+tests/test_multipart_gsi.pytests/test_gsi_multi_range_query.py,tests/test_read_paging.py,tests/test_vector_index_query_scan.pytests/python/test_query_scan.pycrates/storage-postgres/tests/lsi_query_plan.rs(20 LSI plans, 32 multi-RANGE GSI plans)plan_tests(12 LSI statements, 4 GSI statements, 16 multi-RANGE GSI statements, the rows of the multi-RANGE GSI pages, LSI paging both directions)After
03d9c72e3, cb90d04 made every index cursor bind the start key's partition key, and later commits changed the PostgreSQL tests. At 83198b8,tests/test_query_scan.pywithtests/test_read_paging.pygave 131 passed on SQLite and on PostgreSQL 16.15.Negative controls
On the pre-rebase head
e9d30451e: each mutation applied to the committed tree, the tests run, the file restored withgit checkout,crates/clean afterwards. The cursor unit test counts are that head's. Since then, main added one test per backend.base_pkfiltered out of the LSI ORDER BY (all shapes)lsi_query_plans_as_an_index_walk_in_both_directions:first page, forward=true, generic plan: the plan sorts the rows the index scan reads(Incremental Sort)base_pkfiltered out of the LSI ORDER BY only when the key condition has a sort key conditionlsk = :l, first page, forward=true, generic plan: the plan sorts the rows the index scan reads(Sort, Sort Key: base_sk_s)base_pkreplaced by its bound value in the LSI cursor comparisonresumed page, forward=true, generic plan: the plan filters rows after the index scan instead of seeking on them(Index Condsk_s >= $2, Filter on the row comparison)base_pkfiltered out of the LSI ORDER BY (all shapes)plan_tests::lsi_query_walks_the_ordering_index_without_a_sort:LSI pk only forward=true resumed=false: the plan sorts in a temporary B-treebase_pkfiltered out of the LSI ORDER BY only with a sort key conditionLSI lsk = :l forward=true resumed=false: the plan sorts in a temporary B-treebase_pkremoved from the LSI cursor columns and bindlsi_cursor_compares_the_ordering_index_columns,order_by_columns_match_the_cursor_columns_for_every_shapeOn 83198b8, each mutation applied to the committed tree, the tests run, the files restored with
git restore:base_pk,ORDER BYunchangedlsi_query_plans_as_an_index_walk_in_both_directions:resumed page, forward=true, generic plan: the cursor is not one index condition over ROW(sk_s, base_pk, base_sk_s). The multi-RANGE test fails on its rows.base_pkbase_pklsi_cursor_compares_the_ordering_index_columnsand four other cursor unit tests, andmulti_range_gsi_query_walks_the_ordering_index_without_a_sorton its rows.lsi_query_pages_follow_the_index_order_in_both_directionsrepeats its pages and does not end.EXTENDDB_TEST_PG_REQUIRED=1and no connection string2 passedbefore the change)EXTENDDB_TEST_PG_REQUIRED=12 passedbefore the change)With both plan tests failing under the first mutation, the server had as many
eddb_lsip_*databases after the run as before it.On
03d9c72e3, the mutation cut theORDER BYof an index with several RANGE attributes to its first RANGE column and left the cursor untouched.plan_tests::multi_range_gsi_query_walks_the_ordering_index_without_a_sortfails withmulti-RANGE GSI h only forward=true resumed=false: the plan sorts in a temporary B-tree(USE TEMP B-TREE FOR LAST 2 TERMS OF ORDER BY).multi_range_gsi_query_plans_as_an_index_walk_in_both_directionsfails on the rows of the first page:(a0, b1, c1, ..)where the test expects(a0, b0, c0, ..). The other plan tests pass.On
16a1b92f1, the mutation made SQLite'squery_statementapply the sort key condition to the first RANGE column instead of the one it names.plan_tests::multi_range_gsi_query_walks_the_ordering_index_without_a_sortfails on rows (multi-RANGE GSI a = :a AND b BETWEEN forward=true: rows, no items where the test expects 60). The other 167 SQLite--libtests pass.The plan tests also ran against main alone. For the SQLite run, main's tree carried one extra change: the statement builder moved into
query_statement, which the tests call. On mainlsi_query_plans_as_an_index_walk_in_both_directionsfails on the first page with anIncremental Sortover the index scan (presorted keysk_s).lsi_query_walks_the_ordering_index_without_a_sortfails withUSE TEMP B-TREE FOR LAST TERM OF ORDER BY. The GSI cases and the LSI paging test pass there.The second Verification table, the Gates and the
03d9c72e3and16a1b92f1paragraphs above are the rebased head's, on the commits they name. The first Verification table and thee9d30451emutation table are the pre-rebase head's.Gates
On 83198b8, with main merged in at 6f06bfe:
cargo +1.97.0 fmt --all -- --checkis clean.cargo +1.97.0 clippy --locked -p extenddb-storage-postgres -p extenddb-storage-sqlite --all-targets -- -D warningsis clean.cargo +1.91.1 check --locked -p extenddb-storage-postgres -p extenddb-storage-sqlite --all-targetsbuilds.cargo test -p extenddb-storage-sqlite --lib: 319 passed, 1 ignored, 3 failed. Two are backup catalog lock tests that need a backup root whose parent directories the test user owns. The third is storage-sqlite: a restore slot test checks the slot before the copy frees it #872.EXTENDDB_TEST_PG_REQUIRED=1 cargo test -p extenddb-storage-postgres --tests --no-fail-fastagainst PostgreSQL 16.15: 38 binaries, 454 passed, 2 ignored, 6 failed. Five are backup store tests with the same backup root requirement.gsi_online_build::a_held_base_row_does_not_hold_up_its_queue_partitionfailed once and passed in three runs of its own.lsi_query_plan: 2 passed.On c85f014:
cargo test -p extenddb-storage-sqlite --lib query_scan: 12 passed.cargo test -p extenddb-storage-postgres --test lsi_query_planwith no connection string: both tests fail withEXTENDDB_TEST_PG_REQUIRED=1, and both skip without it.No dependency change.
Checklist
cargo test --workspace)cargo fmt --check)cargo clippy -- -W clippy::pedantic)Storagetrait, 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
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.