Skip to content

fix(storage): plan an LSI query as an index walk on PostgreSQL and SQLite - #432

Merged
LeeroyHannigan merged 10 commits into
mainfrom
fix/lsi-query-order-by
Nov 24, 2026
Merged

LeeroyHannigan merged 10 commits into
mainfrom
fix/lsi-query-order-by

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

What

  • crates/storage-postgres/src/data/query_scan.rs: order_by_columns puts base_pk between the index sort key columns and the base sort key for every index with a sort key. The is_lsi parameter is gone from it, from build_pagination_where and from query_impl. Every index cursor binds the start key's base partition key as base_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::BaseSkOnly removed (no remaining user).
  • crates/storage-sqlite/src/data/query_scan.rs: the same column change in query_order_columns. append_query_pagination and the new query_statement take no is_lsi, and every index cursor binds the start key's base partition key. The statement builder moves from query_impl into query_statement with no behaviour change, so tests can run EXPLAIN QUERY PLAN on the statement a Query sends. Cursor unit tests updated. New plan_tests module in crates/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 from pg_stat_activity and 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 with lsk = :l, and a resumed page with each of those and with lsk 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 the ORDER BY columns. It skips without a connection string and below PostgreSQL 16 (EXPLAIN (GENERIC_PLAN)), and fails in both cases when EXTENDDB_TEST_PG_REQUIRED is set. A guard in crates/storage-postgres/tests/lsi_query_plan/scratch.rs drops its scratch database when the test ends, a failed assertion included. Its scratch database builder repeats the one in crates/storage-postgres/tests/common/stream_disable_fixture.rs, which has no drop guard and drops a stream foreign key. One shared builder in tests/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 attributes a, b and c, a module of lsi_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 runs cargo 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 LastEvaluatedKey shape do not change.

Merge after #428

This branch merges after #428. The LSI paragraph in docs/design/04-component-storage.md depends on the section 7 text #428 introduces (the **... Query:** headings, explicit ASC and DESC, 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:

  1. Conflict hunk in section 7: take this branch's LSI Query: paragraph and SQL block in place of docs(design): describe the query cursor as the row comparison the code emits #428's LSI Query: paragraph. Keep docs(design): describe the query cursor as the row comparison the code emits #428's GSI with more than one RANGE attribute:, Hash-only index: and Index Scan: paragraphs and the "On a base table without a sort key" paragraph. Apply edit 4 to the Index Scan: paragraph.
  2. Section 7 intro: replace "the Scan, base table Query, GSI and hash-only index shapes below" with "every shape below". Replace "For a GSI it is the ordering index" with "For a GSI or LSI it is the ordering index".
  3. Section 5.1: replace "A GSI Query cursor there is served in one seek, by the ordering index, or by the primary key on a hash-only GSI (section 7 has the LSI and Scan cases)." with "A GSI or LSI Query cursor there is served in one seek, by the ordering index, or by the primary key on a hash-only GSI (section 7 has the Scan cases)."
  4. Index Scan: paragraph: replace "The LSI Scan keeps base_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."
  5. Section 7, the paragraph that starts "The plans here are for the statements shown": replace "With an equality on the index sort key, PostgreSQL planned a Sort on every page (over a Bitmap Index Scan on a GSI, over the Index Scan on an LSI) while a BETWEEN kept 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. A BETWEEN kept 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_plan passes 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 are order_by_columns and build_pagination_where, and on SQLite query_order_columns and append_query_pagination. They take the queried key schema's RANGE attributes as a slice in place of the first one, and keep is_lsi. This change removes is_lsi from the same functions, so both query_scan.rs files 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, then base_pk, then the base sort key. That is the column order of its ordering index after pk. 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_statement now holds #429's statement code, which applies each RANGE condition to the column of the attribute it names. .github/workflows/integration.yml, query.rs and the design doc merged without a conflict.

The plan tests now cover a GSI with RANGE attributes a, b and c. On PostgreSQL that is crates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs, a module of the lsi_query_plan test. On SQLite it is a fourth plan_tests case. Each runs the partition alone, an equality on a, an equality on a with b 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 Limit 7 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 into query_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, so query_scan.rs is 920 lines here (883 on main).

Merged main

The branch merged main (6f06bfe, 2026-11-20). The multi-RANGE test's GsiInput literal sets warm_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 by lsk. 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 and LastEvaluatedKey ({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 one sk column per RANGE attribute. A GSI Query orders by its RANGE columns in key-schema order, then base_pk and base_sk ((sk, base_pk, base_sk) with one RANGE attribute). Those are the ordering index's columns without the constant pk, 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_pk is constant inside an LSI partition, so the index served sk only. PostgreSQL added an Incremental Sort over the index scan (a Sort when lsk = :l left one value). SQLite added a temporary B-tree for the last ORDER BY term and seeked a resumed page on sk alone. On a 50,000-item partition with 50 items per lsk value, 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

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: PostgreSQL EXPLAIN (ANALYZE, BUFFERS) EXECUTE and EXPLAIN (GENERIC_PLAN), and SQLite EXPLAIN QUERY PLAN. The rebase changed no LSI statement, and these rows did not run again on 03d9c72e3.

Check PostgreSQL SQLite
LSI pages, 21 request shapes (first, resumed, FilterExpression, =, >, <, <=, >=, begins_with, BETWEEN, engine chunks), both directions Index Scan or Index Scan Backward on the ordering index, cursor in the Index Cond, no sort node, custom and generic plan; rows read equal the LIMIT (was Incremental Sort or Sort, up to 130 rows for LIMIT 98) SEARCH ... USING INDEX idx_order_*, no temporary B-tree (was a temporary B-tree). A resumed page with no condition on lsk seeks on (sk_s, base_pk, base_sk_s) (was sk_s only): 1,196 VM opcodes per LIMIT 98 page, was 2,892. With lsk = :l, BETWEEN, begins_with, or > and >= on a forward page, SQLite seeks on the sk_s condition ((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.
GSI, base table Query and Scan plans unchanged unchanged
Pages of the 52,000-item table before and after (every item key and LastEvaluatedKey) identical identical
9-item probe against the service output: items per page, group order, Count, LastEvaluatedKey keys match on every query; order inside a group differs (#425) same
LSI cases in test_item_operations.py, test_table_operations.py, test_put_item_create_race.py 3 passed 3 passed
key-type matrix (pk, lsk, sk in N, B, S combinations; full, paged, BETWEEN, COUNT queries both directions) 0 problems 0 problems, output identical to PostgreSQL

The 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 SQLite plan_tests and cursor unit test rows ran on 16a1b92f1:

Check PostgreSQL SQLite
tests/test_query_scan.py + tests/test_multipart_gsi.py 126 passed 126 passed
tests/test_gsi_multi_range_query.py, tests/test_read_paging.py, tests/test_vector_index_query_scan.py 90 passed, 1 skipped (the case for a backend that refuses a condition past the first RANGE attribute) 90 passed, 1 skipped
tests/python/test_query_scan.py 27 passed 27 passed
crates/storage-postgres/tests/lsi_query_plan.rs (20 LSI plans, 32 multi-RANGE GSI plans) 2 passed n/a
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) n/a 4 passed
cursor unit tests 9 passed 9 passed

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.py with tests/test_read_paging.py gave 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 with git checkout, crates/ clean afterwards. The cursor unit test counts are that head's. Since then, main added one test per backend.

Mutation Fails Passes
PostgreSQL: base_pk filtered 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) 8 cursor unit tests
PostgreSQL: base_pk filtered out of the LSI ORDER BY only when the key condition has a sort key condition same test: lsk = :l, first page, forward=true, generic plan: the plan sorts the rows the index scan reads (Sort, Sort Key: base_sk_s) 8 cursor unit tests
PostgreSQL: base_pk replaced by its bound value in the LSI cursor comparison same test: resumed page, forward=true, generic plan: the plan filters rows after the index scan instead of seeking on them (Index Cond sk_s >= $2, Filter on the row comparison) 8 cursor unit tests
SQLite: base_pk filtered 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-tree 10 (GSI plan test, paging test, cursor unit tests)
SQLite: base_pk filtered out of the LSI ORDER BY only with a sort key condition same test: LSI lsk = :l forward=true resumed=false: the plan sorts in a temporary B-tree 10
SQLite: base_pk removed from the LSI cursor columns and bind lsi_cursor_compares_the_ordering_index_columns, order_by_columns_match_the_cursor_columns_for_every_shape 8, the paging test among them: the rows do not change

On 83198b8, each mutation applied to the committed tree, the tests run, the files restored with git restore:

Mutation Fails
PostgreSQL: the cursor of every index with a sort key without base_pk, ORDER BY unchanged lsi_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.
PostgreSQL: an empty string bound as the cursor's base_pk both plan tests on the rows of the first resumed page
SQLite: an empty string bound as the cursor's base_pk lsi_cursor_compares_the_ordering_index_columns and four other cursor unit tests, and multi_range_gsi_query_walks_the_ordering_index_without_a_sort on its rows. lsi_query_pages_follow_the_index_order_in_both_directions repeats its pages and does not end.
PostgreSQL plan tests with EXTENDDB_TEST_PG_REQUIRED=1 and no connection string both tests (2 passed before the change)
PostgreSQL plan tests with the version threshold raised to 170000, EXTENDDB_TEST_PG_REQUIRED=1 both tests (2 passed before 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 the ORDER BY of 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_sort fails with multi-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_directions fails 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's query_statement apply 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_sort fails on rows (multi-RANGE GSI a = :a AND b BETWEEN forward=true: rows, no items where the test expects 60). The other 167 SQLite --lib tests 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 main lsi_query_plans_as_an_index_walk_in_both_directions fails on the first page with an Incremental Sort over the index scan (presorted key sk_s). lsi_query_walks_the_ordering_index_without_a_sort fails with USE 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 03d9c72e3 and 16a1b92f1 paragraphs above are the rebased head's, on the commits they name. The first Verification table and the e9d30451e mutation table are the pre-rebase head's.

Gates

On 83198b8, with main merged in at 6f06bfe:

  • cargo +1.97.0 fmt --all -- --check is clean.
  • cargo +1.97.0 clippy --locked -p extenddb-storage-postgres -p extenddb-storage-sqlite --all-targets -- -D warnings is clean.
  • cargo +1.91.1 check --locked -p extenddb-storage-postgres -p extenddb-storage-sqlite --all-targets builds.
  • 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-fast against 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_partition failed once and passed in three runs of its own. lsi_query_plan: 2 passed.

On c85f014:

  • The fmt, clippy and 1.91.1 commands above give the same results.
  • cargo test -p extenddb-storage-sqlite --lib query_scan: 12 passed.
  • cargo test -p extenddb-storage-postgres --test lsi_query_plan with no connection string: both tests fail with EXTENDDB_TEST_PG_REQUIRED=1, and both skip without it.

No dependency change.

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: 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.

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

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.

…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
@navareamol navareamol added the v1 Needed for the 1.0 release label Nov 3, 2026
@navareamol navareamol added this to the 1.0 milestone Nov 3, 2026
.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 demohan self-assigned this Nov 19, 2026

@demohan demohan 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.

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_plan was added.
  • With lsk = :l or BETWEEN, SQLite seeks on sk_s and 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 {

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.

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).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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
}

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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> {

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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::*;

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in 61a2393.

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

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 3bb61d3. The LSI paragraph now states its own direction: one row comparison, > and ASC forward, < and DESC in reverse. It refers to the GSI cursor above only for the columns, so it reads the same before and after #428.

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.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Item by item:

@demohan demohan 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.

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.00 resumes a walk queried as 1.0. With an empty partition key bound instead, 688 of the checks fail.
  • The SQLite plans for a resumed lsk = :l and for BETWEEN are index searches with no temporary B-tree. lsi_query_plan runs in CI with EXTENDDB_TEST_PG_REQUIRED=1 and 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.

@LeeroyHannigan
LeeroyHannigan added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit 055785f Nov 24, 2026
58 checks passed
@LeeroyHannigan
LeeroyHannigan deleted the fix/lsi-query-order-by branch November 24, 2026 12:34
LeeroyHannigan added a commit that referenced this pull request Nov 24, 2026
#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.
LeeroyHannigan added a commit that referenced this pull request Nov 24, 2026
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.
LeeroyHannigan added a commit that referenced this pull request Nov 24, 2026
Merges main at 6aef346, two commits past 44cd436: #432 (LSI query
plan on PostgreSQL and SQLite) and #468 (AT_TIMESTAMP shard iterator).
No conflicts. Neither commit changes a file of this branch.
LeeroyHannigan added a commit that referenced this pull request Nov 24, 2026
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.
rlunar pushed a commit to rlunar/extenddb that referenced this pull request Nov 25, 2026
…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.
@hitesh96db hitesh96db mentioned this pull request Nov 26, 2026
6 of 8 tasks
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] SQL backends: LSI Query plans a sort step because the ORDER BY skips base_pk

3 participants