Skip to content

docs(design): describe the query cursor as the row comparison the code emits - #428

Merged
LeeroyHannigan merged 10 commits into
mainfrom
docs/reverse-query-cursor
Nov 25, 2026
Merged

LeeroyHannigan merged 10 commits into
mainfrom
docs/reverse-query-cursor

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changes since the last review

The review of 24 November read fc0083a.

The merge 8189010 and 2cf975e make the five edits that #432's description gives for this merge.

Changes between the review of 19 November and fc0083a

  • a8841ce docs(storage-sqlite): crates/storage-sqlite/README.md line 22 said the SQLite backend uses OR-expansion for pagination because SQLite lacks row-value comparison. It now describes the row comparison the builder emits.
  • fc0083a docs(design): section 7 names the base table Scan and Query as the shapes the primary key serves. A paragraph after the intro limits the plan statements to the statements shown, which carry no sort key condition. It says what PostgreSQL and SQLite plan with one. The legacy-table text adds the case where a later cursor column carries the collation. The reverse GSI paragraph states the tiebreaker rule in place of the history of a fixed defect. Section 5.1 names the text key columns that carry the collation and the index that serves a hash-only GSI cursor.

What

  • Section 7 of docs/design/04-component-storage.md states the rule. The cursor columns are the ORDER BY columns, in the same order and direction, compared with > forward and < reverse. With one cursor column, the cursor is a plain comparison.
  • The section shows the statements with their ORDER BY, as the code emits them. They are the Scan, base table Query, forward GSI, reverse GSI, multi-RANGE GSI, LSI Query and index Scan statements. The LSI Query paragraph and its statement are fix(storage): plan an LSI query as an index walk on PostgreSQL and SQLite #432's.
  • The section names the index that serves each shape. That is the primary key, the ordering index, or for a hash-only index the primary key or the base-key index. The no-sort statement covers tables created with the collated key columns. On older PostgreSQL tables the indexes do not serve a COLLATE "C" predicate. PostgreSQL then reads the partition through the pk prefix and sorts on every page (technical debt C-11). Where a later cursor column carries the collation, it seeks on the leading columns and sorts the rest.
  • The plan statements are for the statements shown, which carry no sort key condition. One paragraph says what the two databases plan with one. With an equality on the index sort key, PostgreSQL planned a Sort on every GSI page. On an LSI with 50 items per sort key value, both plans of each page were an Index Scan at Limit 10 (fix(storage): plan an LSI query as an index walk on PostgreSQL and SQLite #432's plan test). At Limit 101 the custom plan of the first page was a Sort. SQLite seeks on the condition's terms and applies the cursor as a filter.
  • The section states the hash-only index cursor and the forms on a base table without a sort key. There the Scan cursor is pk > $last_pk, a Query with an ExclusiveStartKey is refused with ValidationException before it reaches storage, and an LSI cannot exist (validation refuses it).
  • The section 5.1 sentence on collation names the text key columns that carry it on index tables created with the collated key columns. It names the index that serves a GSI or LSI Query cursor there in one seek. That is the ordering index, or the primary key on a hash-only GSI.
  • crates/storage-sqlite/README.md line 22 listed OR-expansion for pagination as a difference from the PostgreSQL backend. It now says the cursor is the same row comparison as on PostgreSQL, with ? placeholders and no COLLATE.

Why

Closes #370.

Section 7 of docs/design/04-component-storage.md described the reverse GSI pagination cursor as an expanded OR with an ascending base-key tiebreaker under a descending sort key. It described the base table Scan cursor as an OR form. The PostgreSQL and SQLite query builders emit one row comparison for every cursor shape, with every column following ScanIndexForward. On PostgreSQL that is build_pagination_where and order_by_columns in crates/storage-postgres/src/data/query_scan.rs. On SQLite it is append_query_pagination and query_order_columns in crates/storage-sqlite/src/data/query_scan.rs. So the doc described a form the code no longer has. The SQLite README stated the OR form too.

Overlaps with other PRs

Testing done

I read every sentence and SQL fragment against the two query_scan.rs files as main had them after #429. At 8189010 I read the LSI sentences again against the two files as #432 left them. The plan statements come from EXPLAIN (ANALYZE) on PostgreSQL 16.15 and from EXPLAIN QUERY PLAN on SQLite. The plans in this paragraph are from before #432. The PostgreSQL plans cover tables the server created and copies whose key columns keep the database collation. Except for two shapes, every Query and Scan shape is one index scan with the row comparison in the index condition and no sort node. The LSI Query had the row comparison in the index condition under an Incremental Sort (Presorted Key: sk_s) on PostgreSQL and a temporary B-tree on SQLite. #432 removed both, and its plan tests show the LSI Query as an index walk with no sort step. The Scan on an index with more than one RANGE attribute has an Incremental Sort (Presorted Key: pk, sk_s) on PostgreSQL and a temporary B-tree on SQLite. On the legacy-collation copies with string sort keys, every Query shape reads the partition through pk, with a Bitmap Index Scan or an Index Scan. It then filters and sorts. The Scan shapes there are an Index Scan from the cursor's pk, a filter and an Incremental Sort. On a copy of a base table with a numeric sort key, the plans are those of the collated table. With an equality on the index sort key and the cursor, PostgreSQL planned a Sort over a Bitmap Index Scan on a GSI. On an LSI it planned a Sort over the Index Scan. A BETWEEN on the GSI sort key kept the Index Scan. The LSI plans of the doc since 2cf975e are #432's.

What pins each fragment. The test names are as main has them at 6aef346. The mutant counts were measured before #432 merged, which added the LSI plan tests.

  • The cursor strings, in both directions, for every shape: base table, GSI over a composite or hash-only base, LSI, hash-only index, multi-RANGE GSI. PostgreSQL: base_table_cursor_is_a_single_comparison, forward_gsi_cursor_is_a_row_comparison_over_the_full_base_key, reverse_gsi_cursor_is_the_mirror_row_comparison, gsi_on_a_hash_only_base_table_uses_base_pk_as_the_tie_breaker, lsi_cursor_compares_the_ordering_index_columns_in_both_directions, hash_only_index_cursor_is_a_row_comparison_over_the_base_key, hash_only_index_reverse_cursor_follows_the_direction, multi_range_gsi_orders_and_resumes_over_every_range_attribute. SQLite: base_table_cursor_is_a_single_comparison_in_both_directions, gsi_cursor_is_a_row_comparison_over_the_full_base_key_in_both_directions, gsi_on_a_hash_only_base_table_uses_base_pk_as_the_tie_breaker, lsi_cursor_compares_the_ordering_index_columns, hash_only_index_cursor_follows_the_direction, missing_sort_key_attributes_bind_as_the_empty_string, multi_range_gsi_orders_and_resumes_over_every_range_attribute.
  • That the cursor columns and the ORDER BY columns come from one function: order_by_columns_match_the_cursor_columns_for_every_shape in both crates. On PostgreSQL it takes its expectation from that function, so it does not pin the column set on its own. On SQLite it also checks the bind count, so it fails when base_pk leaves the columns but not the binds. Removing base_pk from the GSI columns fails four PostgreSQL tests and five SQLite tests, that test included.
  • The ORDER BY direction and the number of ORDER BY columns the query emits: no unit test. Forcing the direction to ASC, or keeping only the first ORDER BY column, passes every unit test in both crates. The wire tests pin the direction. In tests/test_query_scan.py and tests/test_read_paging.py, selected with -k "revers or Pagin or Mirror or paging", 23 of 66 cases fail under the ASC mutation, on SQLite and on PostgreSQL. The wire selection pins the column count on PostgreSQL only. With the first ORDER BY column alone, 11 or 12 of 66 cases fail there and none on SQLite. The twelfth, test_index_pagination_uses_base_key_schema_for_tiebreaker, fails in some runs only. With one ORDER BY column, the order of the rows that tie on it is not defined. On PostgreSQL the cursor then skips some of them and repeats others.
  • The base table Scan cursor form: no unit test. Rewriting it to the OR form passes every unit test in both crates (84 PostgreSQL and 318 SQLite tests). Two SQLite tests, write_lock_tests::a_put_during_a_writers_hold_passes_on_the_beat_parked_behind_it and write_lock_tests::a_writer_holding_the_lock_past_two_periods_delays_the_beat_and_ends_no_job, fail on my machine with or without the change. Their backup root sits under the Cargo target directory, and FilesystemStore::open refuses a root with an ancestor directory that another user owns. The wire tests return the same rows. Only a plan distinguishes the two forms.
  • The index Scan cursor: no unit test. Changing its > to >= in scan_impl passes every unit test in both crates. On the wire I put that change into the two SQLite scan_impl branches for an index over a base table with a sort key. Then 2 of the 131 cases of tests/test_read_paging.py and tests/test_query_scan.py fail, both in tests/test_query_scan.py: test_index_scan_pagination_uses_base_key_schema (15 items for 12) and test_scan_paginate_returns_all (13 for 7). test_gsi_scan_pagination_exactly_once in tests/test_read_paging.py passes with the change. Its index and its base table are hash-only, so its cursor is the (pk, base_pk) branch, which the change does not touch. The 131 cases pass on the unchanged server.

On the merge 6482fb5 (main at 44cd436), the lib tests of the two crates: PostgreSQL 84 passed. SQLite 316 passed, 2 failed (the two write_lock_tests above), 1 ignored. This branch changes no Rust file. CI runs the workspace tests on the merge with #432.

Open: #1253, #1254 and #1256. The Scan of a multi-RANGE index sorts each page (#1253). No unit test pins the ORDER BY or the Scan cursor forms (#1254). On SQLite a resumed index Query with a sort key condition seeks on the condition (#1256).

No code or test change. No other file in the repository states the old form.

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

Breaking changes

None.


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.

…e 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 #370
@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
@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.

Section 7 now shows the row comparison the PostgreSQL and SQLite builders emit for the base Query, GSI, reverse GSI, LSI and hash-only shapes, and #370 is addressed. Live DynamoDB returns the forward order reversed on GSI ties, hash-only GSIs, LSI ties and the base Query, with Limit 1, Limit 2 and no limit, on two fresh table sets (112 forward and reverse pairs, 0 mismatches), so the mirror statement holds. Five items remain. Once they are done, it merges.

  1. Rebase on main. #429 puts every RANGE attribute of a multi-attribute GSI into the cursor and ORDER BY ahead of the base key, and section 7 shows one sort key column. This comes from main moving under the branch.
  2. The LSI paragraph places the sort before the cursor. The plans apply the cursor first.
  3. "No sort step" and "one seek" do not hold on tables created before the key columns carried COLLATE "C".
  4. The index Scan cursor is not shown.
  5. The verification paragraph says the unit tests pin the fragments. They pin the cursor strings, but not the ORDER BY direction or columns and not the base table Scan cursor.

On item 5: Forcing the ORDER BY direction to ASC, or keeping only its first column, passes every unit test in both crates. Rewriting the base table Scan cursor to the OR form passes all 45 PostgreSQL and 100 SQLite lib tests. order_by_columns_match_the_cursor_columns_for_every_shape passes with base_pk removed from the GSI columns, because it takes its expectation from the same function. The wire tests pin the direction (23 of 61 selected cases fail under the ASC mutation). Please name what pins each fragment, and name the SQLite tests.

key as a tiebreaker, in the cursor and in the `ORDER BY`:
```sql
WHERE pk = $gsi_pk
AND (sk_s COLLATE "C", base_pk COLLATE "C", base_sk_n) > ($gsi_sk, $base_pk, $base_sk)

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 main, #429 adds one column per RANGE attribute ahead of the base key: order_by_columns emits (sk_s COLLATE "C", sk2_n, sk3_s COLLATE "C", base_pk COLLATE "C", base_sk_s COLLATE "C") (test multi_range_gsi_orders_and_resumes_over_every_range_attribute). Live DynamoDB orders a GSI with RANGE r1 (S), r2 (N) by r1, then r2 numerically, and main matches. Please add the multi-RANGE form after a rebase, for example (sk_s COLLATE "C", sk2_n, base_pk COLLATE "C", base_sk_n).

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 (#429 included) in a6fd620. The section now has a "GSI with more than one RANGE attribute" block with the (sk_s COLLATE "C", sk2_n, base_pk COLLATE "C", base_sk_n) cursor and its ORDER BY. I ran EXPLAIN on a GSI with RANGE r1 (S) and r2 (N) over a base table with a numeric sort key. The plan is one Index Scan on the ordering index (pk, sk_s, sk2_n, base_pk, base_sk_n). That holds forward and backward. The row comparison sits in the Index Cond and there is no sort node.

Comment thread docs/design/04-component-storage.md Outdated
`(sk_s COLLATE "C", base_sk_n) > ($lsi_sk, $base_sk)` forward and `<` in
reverse. The ordering index on the LSI table is `(pk, sk_s, base_pk, base_sk_n)`,
so after the fixed `pk` the index orders by `sk_s` only and the database sorts
the rows that share an index sort key value before it can apply 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.

The cursor is applied before the sort. PostgreSQL 16, 100,000 rows sharing one LSI sort key value: Index Cond: ((pk = 'p1'::text) AND (ROW(sk_s, base_sk_n) > ROW('same'::text, '100'::numeric))) under Incremental Sort, Presorted Key: sk_s, 99,899 rows into the sort, 40.6 ms for a 101-row page. SQLite: SEARCH ... (pk=? AND sk_s>?), then USE TEMP B-TREE FOR LAST TERM OF ORDER BY. The first page sorts the same way. Suggested: "The database applies the cursor while it reads the index, then sorts the rows that share an index sort key value by the base sort key before it applies the LIMIT."

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 a6fd620. The paragraph now says the database applies the cursor while it reads the index. It then sorts the rows that share an index sort key value by the base sort key, and applies the LIMIT after that. The first page sorts the same way. EXPLAIN (ANALYZE) on PostgreSQL 16.15 shows Index Cond: ((pk = 'p1') AND (ROW(sk_s, base_sk_n) > ROW('same', 1500))) under an Incremental Sort with Presorted Key: sk_s. SQLite shows SEARCH ... (pk=? AND sk_s>?) and then USE TEMP B-TREE FOR LAST TERM OF ORDER BY.

Comment thread docs/design/04-component-storage.md Outdated
the same columns the statement's `ORDER BY` sorts on, in the same order and in
the same direction, so the predicate is one row comparison, `>` for a forward
page and `<` for a reverse one (a plain comparison when the cursor has one
column). For the Scan, base table Query, GSI and hash-only index shapes below,

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 a table whose key columns keep the database collation (created before TEXT_KEY, technical debt C-11), PostgreSQL 16 plans Bitmap Index Scan on pk, a filter on the sort key and Sort (top-N heapsort) for the base Query and the GSI Query in both directions, and a full Sort for the LSI. Suggested: "On tables created with the collated key columns, the ordering index serves the page in order with no sort step. On older tables PostgreSQL reads the partition and sorts it on every page (technical debt C-11)."

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 a6fd620. The intro limits the no-sort statement to tables created with the collated key columns. For older PostgreSQL tables it says the indexes do not serve a COLLATE "C" predicate or ORDER BY. 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 then filters the cursor and sorts the rest on every page (technical debt C-11). Measured on copies of the tables whose key columns keep the database collation (en_US.utf8), with pk = 'p1' selective. On the string-key copies, every Query shape plans a Bitmap Index Scan on pk, a Filter on the cursor and a Sort (top-N heapsort). That covers the base Query and the GSI Query in both directions, the LSI Query and the hash-only GSI Query. On a copy of a base table with a numeric sort key, the plans are those of the collated table.

Comment thread docs/design/04-component-storage.md Outdated
columns on index tables (`pk`, `sk_s`, `base_pk`, `base_sk_s`) carry the
collation, so a GSI or LSI cursor is a row comparison the ordering index
serves in one seek.
collation, so a GSI cursor is a row comparison the ordering index serves

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.

Same qualifier as on line 699: index tables created before TEXT_KEY keep the database collation, and a GSI cursor there plans a Bitmap Index Scan on pk and a Sort. Suggested: "On index tables created with the collated key columns, the same columns carry the collation, so a GSI cursor is a row comparison the ordering index serves in one seek."

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 a6fd620. The sentence now reads "On index tables created with the collated key columns, the same columns (pk, sk_s, base_pk, base_sk_s) carry the collation. A GSI cursor there is a row comparison the ordering index serves in one seek (the LSI case is in section 7)." On the legacy-collation copy the GSI cursor plans a Bitmap Index Scan on pk and a Sort.

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.

The sentence changed again in fc0083a. A hash-only GSI has no ordering index (section 7), so the primary key serves its Query cursor. The numbered sort key columns carry the collation too. It now reads: "On index tables created with the collated key columns, the text key columns (pk, sk_s, base_pk, base_sk_s and their numbered variants) carry the collation. 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)."

placeholders and without `COLLATE`, because its text columns already compare by
byte value.

**Base table Scan:**

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.

scan_impl on an index compares the full index row key, (pk, sk_s COLLATE "C", base_pk COLLATE "C", base_sk_n) > (...) with the same ORDER BY, and (pk, base_pk COLLATE "C", base_sk_n) on a hash-only index. The LSI Scan includes base_pk, which the LSI Query drops, and PostgreSQL serves it from the ordering index with no sort node. Please add an "Index Scan" block.

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 a6fd620 as an "Index Scan" block. It shows (pk, sk_s COLLATE "C", base_pk COLLATE "C", base_sk_n) > (...) with the same ORDER BY for a GSI or LSI with one sort key, and (pk, base_pk COLLATE "C", base_sk_n) > (...) for a hash-only index. It notes that the LSI Scan keeps base_pk. EXPLAIN: the LSI Scan is one Index Scan on the ordering index with no sort node. The hash-only index Scan is one Index Scan on the primary key. The block also records that a Scan on an index with more than one RANGE attribute orders by the first RANGE column only. The ordering index does not serve that order without a sort step (Incremental Sort on PostgreSQL, temporary B-tree on SQLite). That is a code gap, filed separately.

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.

The code gap is #1253. No unit test pins the index Scan cursor. Changing its > to >= in scan_impl passes every unit test in both crates. On the wire I put that change into the two SQLite scan_impl branches for an index over a base table with a sort key. Two cases of tests/test_query_scan.py then fail: test_index_scan_pagination_uses_base_key_schema (15 items for 12) and test_scan_paginate_returns_all (13 for 7). test_gsi_scan_pagination_exactly_once in tests/test_read_paging.py passes with the change. Its index and base table are hash-only, so its cursor is the (pk, base_pk) branch, which the change does not touch. #1254 now lists the index Scan cursor with this measurement.

Comment thread docs/design/04-component-storage.md Outdated
The storage backend translates this to a SQL `WHERE` clause:

**Base table pagination (forward scan):**
The storage backend translates this to a SQL `WHERE` clause. The cursor compares

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.

MongoDB builds a $or filter and a sort document, and Cassandra issues CQL queries per page, so neither translates this to SQL. Suggested: "The PostgreSQL and SQLite backends translate this to a SQL WHERE clause."

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 a6fd620: "The PostgreSQL and SQLite backends translate this to a SQL WHERE clause." The MongoDB cursor is a $or filter with a sort document (storage-mongodb/src/data_engine.rs), and the Cassandra backend runs one or two CQL queries per page (storage-cassandra/src/data/query.rs).

(PostgreSQL adds an Incremental Sort node, SQLite a temporary B-tree); the
result and page boundaries are unchanged by that step.

**Hash-only index:** there is no index sort key, so the cursor is the base

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 hash-only index has no ordering index. create_index_data_table creates it only when the index declares a sort key. The primary key (pk, base_pk, base_sk_*) serves this page (Index Scan using _ddb_hgsi_pkey).

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 a6fd620. The intro now says a hash-only index has no ordering index, because create_index_data_table creates one only when the index declares a sort key. Its page comes from the primary key (pk, base_pk, base_sk_*) or from the base-key index (base_pk, base_sk_*) with a filter on pk. On the tables the server created here, PostgreSQL chose the base-key index with Filter: (pk = 'h1'), and SQLite the primary key. Neither plan has a sort node.

Comment thread docs/design/04-component-storage.md Outdated
primary key alone, `(base_pk COLLATE "C", base_sk_n) > ($base_pk, $base_sk)`
forward and `<` in reverse.

On a base table without a sort key the `base_sk_*` column drops out of every

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 a base table without a sort key, the Scan cursor is pk > $last_pk with ORDER BY pk, and a Query with ExclusiveStartKey returns no items without running a statement (query_scan.rs 218 to 221). Please state both here.

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 a6fd620. The paragraph now states both. On a base table without a sort key the Scan cursor is pk > $last_pk with ORDER BY pk. A Query with an ExclusiveStartKey returns no items and runs no statement, because the key condition fixes the only key column. That is the early return before the pagination clause in query_scan.rs, in both backends.

…x 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 #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.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Thanks for the plans. All five items are in a6fd620 (one commit after the merge of main).

  1. Merged main (fix(query): classify and order key conditions on a multi-attribute GSI the way the service does #429 included) and added the multi-RANGE GSI block with the (sk_s, sk2_n, base_pk, base_sk_n) cursor.
  2. The LSI paragraph now says the database applies the cursor during the index read. The sort of the rows sharing an index sort key value comes after it, before the LIMIT, on the first page too.
  3. The no-sort statement now covers tables created with the collated key columns only. For older PostgreSQL tables the doc names the cursors that sort there: those whose first column other than pk is base_pk or a string sort key column. PostgreSQL reads their rows through the pk prefix and sorts on every page (C-11). Measured on legacy-collation copies with string sort keys: Bitmap Index Scan on pk, Filter, Sort for every Query shape. A base table with a numeric sort key plans as on a collated table.
  4. An "Index Scan" block shows the (pk, sk, base_pk, base_sk) and (pk, base_pk, base_sk) cursors with their ORDER BY.
  5. Reproduced the four mutations. ASC forced, and first ORDER BY column only: every unit test passes in both crates. Scan cursor in the OR form: every unit test passes. base_pk removed from the GSI columns: order_by_columns_match_the_cursor_columns_for_every_shape passes on PostgreSQL and fails on SQLite (its bind count check). Four PostgreSQL and five SQLite string tests fail under that mutation. The wire selection fails 23 of 66 cases under the ASC mutation, on SQLite and on PostgreSQL. Under the first-column mutation it fails 11 of 66 on PostgreSQL and none on SQLite. The PR body now names what pins each fragment, SQLite tests included. It also says which fragments no unit test pins: the ORDER BY direction and column count, and the base table Scan cursor form.

Also fixed the hash-only index sentence: there is no ordering index, so the primary key or the base-key index serves the page. I fixed the hash-only base table cases and the backend sentence (PostgreSQL and SQLite) too.

…rison 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.
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.

@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, except one sentence that the earlier review asked for (inline). The measurements below were taken at a6fd620; the commits since then change documentation and merge main.

  • On a GSI with RANGE r1 S and r2 N, the service and this head return the same order on SQLite and PostgreSQL in 12 of 12 shapes, forward and reverse, Limit 1 to 3, with the same LastEvaluatedKey.
  • The multi-RANGE and LSI cursors in the doc match the SQL the servers ran. PostgreSQL applies the row comparison in the Index Cond with no Sort node on collated tables. SQLite searches with the same row comparison. On tables with the old collation, the shapes the doc names get a filter and a Sort.
  • The index Scan cursors, the hash-only index without an ordering index, and the base table Scan cursor pk > $last_pk match the code on both backends.
  • CI is green on 51 of 51 checks.

I will approve once the sentence below is corrected.

PR body

Optional. The first-column mutation fails 12 of 66 wire cases on PostgreSQL in two runs, not 11. test_index_pagination_uses_base_key_schema_for_tiebreaker is the twelfth, and it also failed once under the ASC mutation, so the count varies by one between runs.

Comment thread docs/design/04-component-storage.md Outdated
SQLite a temporary B-tree.

On a base table without a sort key, the Scan cursor is `pk > $last_pk` with
`ORDER BY pk`. A Query with an `ExclusiveStartKey` on such a table returns no

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 earlier review asked for this sentence, and it does not hold on the wire. {"KeyConditionExpression": "pk = :p", "ExpressionAttributeValues": {":p": {"S": "h1"}}, "ExclusiveStartKey": {"pk": {"S": "h1"}}} on a table without a sort key returns 400 ValidationException: The provided exclusive start key is invalid from the service, SQLite and PostgreSQL, twice each. A missing partition, another partition, Limit 1 reverse and the legacy KeyConditions form answer the same. crates/engine/src/start_key.rs:162 refuses it before storage, and the PostgreSQL log shows no statement. "is refused with ValidationException (The provided exclusive start key is invalid) before it reaches storage, as the service refuses it" would match.

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 8187363. The sentence now reads: "A Query with an ExclusiveStartKey on such a table is refused with ValidationException (The provided exclusive start key is invalid) before it reaches storage (crates/engine/src/start_key.rs), because the key condition fixes the only key column." The body's count is now 11 or 12 of 66, with test_index_pagination_uses_base_key_schema_for_tiebreaker named as the case that fails in some runs only.

… 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.
#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.

@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 0d18433. The sentence on a Query with an ExclusiveStartKey on a table without a sort key matches the code (start_key.rs:65 and :167, checked in query.rs before the storage read) and the service: six shapes, two sends each in two runs, to the service in us-east-1 and to SQLite and PostgreSQL servers built from this head, all answer 400 ValidationException The provided exclusive start key is invalid, and 200 without the start key. The body's first-column count holds: the .take(1) mutant fails 11 of 66 in two runs, and the unmutated head passes 66 of 66 twice.

The fix commits add #432's LSI cursor text, which matches the code: the statement the PostgreSQL server sends is the doc's LSI block character for character, 12 of 12 LSI shapes keep sort key byte order and page to the unlimited result on both backends, and every resumed LSI page plans as one Index Scan on the ordering index (an index SEARCH with no temporary B-tree on SQLite). A start key from another partition is refused as the doc says, on the service and both backends. Head merges into main b0d1c64 cleanly, section 7 renders as intended, and CI is green on 58 of 58 checks.

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

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.

Optional. "Limit 10" here counts the Query Limit (GROUP_PAGE in lsi_query_plan.rs:71, sent as SQL LIMIT 11), and "Limit 101" counts the SQL LIMIT of a Query Limit of 100. Both plans hold as measured. "Query Limit 10" and "Query Limit 100" would use one unit.

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 #1485, since this PR merged first. The sentence now names Query Limit 10 and Query Limit 100. The plans stay as measured.

@LeeroyHannigan
LeeroyHannigan added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit e96a60f Nov 25, 2026
58 checks passed
@LeeroyHannigan
LeeroyHannigan deleted the docs/reverse-query-cursor branch November 25, 2026 10:16
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main at e96a60f (#398 and #428 are the newest commits). Three files conflicted. Each one keeps main's text with this branch's formatting:

- docs/cassandra-setup.md: the keyspace_prefix bullet from #1173 (the 27-character limit and the lower-casing rule). A colon after the setting name replaces the em dash. The replication_factor bullet gets the same colon.
- docs/manuals/06-developer-test-guide.md: main's "core is sync Rust" wording, with a colon in place of the em dash.
- docs/versioning.md: main's two bullets (the experimental backend tier, and the WebAssembly build from #1009). Both README links are GitHub URLs, like every other link outside docs/ on this branch. The relative form of the WebAssembly link does not resolve in the strict site build.

Main's new docs/rfcs/0000-credential-encryption-key.md gets an entry in the RFCs sidebar, so the page is reachable from the site and not only by URL.

Main's new lines in docs/design/02-high-level-design.md (three) and docs/design/03-component-core.md (one) carry em dashes. They stay as main has them: #530's dash sweep covers those files.

The strict site build passes on the merged tree.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 80490c6, eight commits after the last merge (#596, #1173,
#398, #428, #544, #567, #584 and #588). One file conflicted:
crates/engine/src/query.rs.

#544 moves the Limit check and the parameter mix check of Query into
validate_query_request_body, which reads the raw body before
deserialization. This branch moves the same two checks to the start of
the handler, after deserialization. The merge keeps the checks of #544
and drops the copies of this branch, which no request can reach. It
keeps has_cond_op for the ConditionalOperator check.

The conflict hunks in handle_query:

- At the old Limit check, both sides remove the check. The merge keeps
  the comment of #544.
- Next, this branch keeps the variables of the mix check, and main
  keeps the index key schema. The merge keeps the key schema where this
  branch has it. It drops the mix check variables, which nothing reads
  now, and keeps the comment of #544 and has_cond_op.
- Before the ExclusiveStartKey check, this branch removes the filter
  operand checks, because its semantic pass runs them at parse time.
  #544 adds validate_key_condition_types there. The merge keeps the
  type check and drops the filter checks.

#544 refuses a begins_with value that is not an S or a B ahead of an
unused value (rows q5 and p4 of tests/test_query_key_value_types.py,
measured 2026-11-06). This branch checks unused values before the
table lookup, so the merged code gave the unused value message for
those two rows. The merge calls refuse_begins_with_on_number after the
key condition parse and removes the later call. The values of legacy
KeyConditions pass validate_legacy_conditions before that point.

Git merged four other files that both sides change, with no overlap:
crates/core/src/expression/key_condition.rs, crates/engine/src/lib.rs,
crates/storage-cassandra/tests/common/mod.rs and
docs/differences-from-dynamodb.md.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 80490c6, six commits after the last merge (#398, #428,
#544, #567, #584 and #588). Two files conflicted.

crates/engine/src/lib.rs: this branch adds query_key_size_tests and
#544 adds query_key_values to the module list. The merge keeps both in
name order.

crates/engine/src/query.rs, two hunks in handle_query:

- This branch moves validate_query_select_index_support after the start
  key checks, and #544 replaces the Limit check with a comment. The
  merge removes the early Select check and keeps the comment of #544.
- Before the ExclusiveStartKey check, this branch adds
  validate_query_key_sizes and #544 adds validate_key_condition_types.
  The merge runs the type check first, because the key size comment
  records a wrong-typed key value ahead of the size (measured
  2026-10-23). On a single-attribute key schema #544 checks the type
  there and not in resolve_key_schema_with, so the key size comment now
  says "checked above".
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 80490c6, six commits after the last merge (#398, #428,
#544, #567, #584 and #588). One file conflicted:
crates/engine/src/query.rs.

This branch moves the table lookup, the index lookup and the index key
schema below the request-stage checks. #544 moves the Limit check and
the parameter mix check into validate_query_request_body, which reads
the raw body before deserialization. Three conflict hunks in
handle_query follow from this:

- After deserialization, this branch keeps the Limit check and main
  keeps the table lookup. The merge keeps the lookup where this branch
  has it and puts the comment of #544 in place of the Limit check.
- Next, this branch keeps the variables of the mix check and main keeps
  the index key schema. The merge keeps the key schema where this
  branch has it. It drops the mix check variables, which nothing reads
  now, and keeps the comment of #544 and has_cond_op.
- Before the ExclusiveStartKey check, this branch removes the filter
  operand checks, because its semantic pass runs them at parse time.
  #544 adds validate_key_condition_types there. The merge keeps the
  type check and drops the filter checks.

#544 refuses a begins_with value that is not an S or a B ahead of an
unused value (rows q5 and p4 of tests/test_query_key_value_types.py,
measured 2026-11-06). This branch checks unused values before the
table lookup, so the merged code gave the unused value message for
those two rows. The merge calls refuse_begins_with_on_number after the
key condition parse and removes the later call. The values of legacy
KeyConditions pass validate_key_conditions before that point.

Git merged four other files that both sides change, with no overlap:
crates/core/src/expression/key_condition.rs, crates/engine/src/lib.rs,
docs/differences-from-dynamodb.md and crates/engine/src/decimal_digits.rs,
which both sides add with the same content.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 14ade59. This branch last had main at 018715e, through
fix/query-key-value-types. Since then, these eleven commits merged
into main: #1280, #1009, #596, #1173, #398, #428, #544, #567, #584,
#588 and #864.

#544 is the squash of fix/query-key-value-types, which was the base
branch of this PR. This branch already holds the last head of that
branch, 31c5f3d. Main has the same version of each conflicted file as
31c5f3d. So each conflict hunk has the lines of #544 on one side.
The other side has the change of this branch to the same lines. The
merge keeps the version of this branch in each file:

- crates/engine/src/query_key_values.rs: this branch makes two
  constants and four functions pub(crate) for the Scan checks, and
  re-exports three functions of unreadable.rs. It reads a number in
  Segment and TotalSegments as it reads one in Limit, with the dates
  in the doc comment of shape_fault_first. It passes
  validate_no_parameter_mix to unreadable_value_checks.
- crates/engine/src/query_key_values/unreadable.rs: this branch makes
  three functions pub(crate). unreadable_value_checks takes the
  parameter mix check as a parameter, so this branch deletes the
  import of validate_no_parameter_mix.
- crates/server/src/request_helpers.rs: this branch runs the Scan
  request checks before the IAM decision, as main does for Query.
- tests/test_query_leading_keys_values.py: this branch moves the setup
  of TestLeadingKeysWithAnInvalidKeyValue to the base class
  ManagementPrincipals, which
  tests/test_scan_checks_before_authorization.py imports.

Git merged crates/engine/src/lib.rs with no conflict. Main compiles
three modules only off wasm32 (backup, import_export_io and
private_fs), and adds the modules backup_requests and pre_dispatch.
This branch adds the module scan_request and changes the doc comment
of validate_enum_fields.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 14ade59. This branch last had main at 018715e, through
fix/query-key-value-types. Since then, these eleven commits merged
into main: #1280, #1009, #596, #1173, #398, #428, #544, #567, #584,
#588 and #864.

#544 is the squash of fix/query-key-value-types, which was the base
branch of this PR. This branch already holds the last head of that
branch, 31c5f3d. Main has the same version of each conflicted file as
31c5f3d. So each conflict hunk has the lines of #544 on one side.
The other side has the change of this branch to the same lines. The
merge keeps the version of this branch in each file:

- crates/engine/src/query_key_values.rs: the dates and the order in
  the module and function doc comments, the call of
  validate_condition_value_numbers, and the two functions
  validate_condition_value_numbers and refuse_first_fault.
- crates/engine/src/query_key_values/request_order_tests.rs: the
  import of Value and the test
  legacy_condition_values_get_the_number_check.
- tests/test_query_key_value_types.py: the dates in the docstring, the
  nn_table fixture and the helpers eq, N1, KC_ABC and QF_BOB. The merge
  also keeps the rows k1 to k16, and nn_table in the tables fixture and
  the control test.

Git merged crates/engine/src/lib.rs with no conflict. This branch
changes that file only through the commits of #544, so the merged file
is the file of main.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
Main is at 14ade59. This branch last had main at 018715e, through
fix/query-key-value-types. Since then, these eleven commits merged
into main: #1280, #1009, #596, #1173, #398, #428, #544, #567, #584,
#588 and #864.

#544 is the squash of fix/query-key-value-types, which was the base
branch of this PR. This branch already holds the last head of that
branch, 31c5f3d. Main has the same version of each conflicted file as
31c5f3d. So each conflict hunk has the lines of #544 on one side.
The other side has the change of this branch to the same lines. The
merge keeps the version of this branch in each file:

- crates/core/src/partiql/params.rs: this branch deletes the two
  base64 imports, because decode_base64 replaces check_base64.
- crates/core/src/types/attribute_value.rs: this branch adds
  BASE64_TEXTS, decode_base64 and is_base64_refusal after the two
  constants that #544 makes public.
- crates/core/src/types/mod.rs: this branch adds decode_base64 and
  is_base64_refusal to the names that #544 re-exports.
- tests/test_query_leading_keys_values.py and
  tests/test_query_value_shapes.py: this branch moves _raw_query to
  tests/raw_signed_request.py as client_post, and calls client_post in
  its place. No other test file on main calls _raw_query.

Git merged crates/engine/src/lib.rs with no conflict. Main compiles
three modules only off wasm32 (backup, import_export_io and
private_fs), and adds the modules backup_requests and pre_dispatch.
This branch adds serialization_exception and calls it from
deserialize_error.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
The base merges main at 14ade59. That brings #544 as a squash and
ten other commits: #1280, #1009, #596, #1173, #398, #428, #567, #584,
#588 and #864. The merge has no conflict. No file has changes on both
sides.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
The base merges main at 14ade59. That brings #544 as a squash and
ten other commits: #1280, #1009, #596, #1173, #398, #428, #567, #584,
#588 and #864. The merge has no conflict. No file has changes on both
sides.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
The base merges main at 14ade59. That brings #544 as a squash and
ten other commits: #1280, #1009, #596, #1173, #398, #428, #567, #584,
#588 and #864.

One file conflicted: crates/engine/src/import_export.rs. #1009 moves
the body of handle_import_table to import_table in the new file
crates/engine/src/import_export/files.rs. The wasm32 build replaces
that file with a stand-in that refuses the operation.
handle_import_table keeps the enabled check and calls
files::import_table.

This branch changes the body that #1009 moves. When read_items finds a
line that it cannot read, the import keeps the items before that line.
It counts the line as one error and reads no more of the file.

The merge keeps the code of main in import_export.rs, with the doc
comment of this branch on handle_import_table. It makes the three
changes of this branch to the body in files.rs:

- The variable read holds the result of read_items: the items and the
  line that the reader cannot read.
- The loop takes the items, then that line. At that line it logs the
  line number and the fault, counts one error and ends the import.
- The comment over the FAILED status adds the date 2026-11-22, for the
  lines that the import cannot read.

The body of import_table in files.rs is now the same as the body of
handle_import_table at the head of this branch.

Git merged docs/manuals/07-upgrade-manual.md with no conflict. #398
adds its v1.1.0 entry at the top of "Behavior Changes by Release".
This branch adds its v1.1.0 entry at the end of that section.
LeeroyHannigan added a commit that referenced this pull request Nov 25, 2026
The base merges main at 14ade59. That brings #544 as a squash and
ten other commits: #1280, #1009, #596, #1173, #398, #428, #567, #584,
#588 and #864. The merge has no conflict.

Git merged crates/engine/src/lib.rs, the one file with changes on both
sides. Main compiles three modules only off wasm32 (backup,
import_export_io and private_fs), and adds the modules backup_requests
and pre_dispatch. This branch adds single_write_refusal after
deserialize_error.
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.

Update docs/design/04-component-storage.md to match reverse query logic in PR362

3 participants