Deterministic paging
Every grid names a unique stable key. The compiler adds it as the last sort key, after the keys the user chose, so that rows with equal values always come back in the same order. The added key gets a null position like any other sort key.
Rule. Schema config declares a required, unique stableKey per grid. If the IR's sort array, once reduced as the pinned paragraph below says, does not already reach that key, the compiler appends it as an implicit trailing tiebreaker — after every sort key the user actually chose, never ahead of them — before compiling the final ordering clause. The appended tiebreaker still needs a nullsPosition (SEM-3 applies to it exactly as to any other sort key): since a stableKey is required to be unique but not required to be NOT NULL, the compiler cannot skip specifying one. Use the same adapter default SEM-3 pins (last on ascending, which the tiebreaker always is, since it exists purely to break ties and has no direction the user chose) — i.e. the appended key is always { field: stableKey, direction: "asc", nullsPosition: "last" }.
The effective sort lists a field once and stops at an exact stable key (pinned; Bug #2565). Before the compiler appends anything it reduces the request's sort array by two rules, and both only remove keys that can never change the order:
- A later occurrence of a field the sort already named is dropped. The first occurrence already decided every tie the later one could break (
[age desc, age asc]orders exactly like[age desc]). This looks at the field only: a repeat that differs in direction or null placement is still redundant. - When the stable key orders exactly, everything after its first occurrence is dropped. A key on it orders exactly when the field is of any non-text type (numeric, boolean, date, datetime), or a text field declared case-sensitive (SC-3,
text.caseSensitivity): two rows with different values never tie under it, so no key after it can break a tie ([id desc, age asc]orders exactly like[id desc]). When the sort stops at the stable key this way nothing is appended; when it does not reach it, the tiebreaker is appended as above.
"Unique" in this rule means that no two rows share a value, NULL included: at most one row has no value. SQL Server's UNIQUE constraint and a MongoDB unique index enforce that; PostgreSQL, MySQL, SQLite and Oracle allow many NULLs, and a host on one of them whose stable key is nullable never had SEM-6's guarantee, since the appended tiebreaker does not break ties among NULLs either. Rule 2 relies on the same reading of "unique" that the appended tiebreaker always did.
A case-insensitive text stable key is the exception to rule 2. Under SEM-1 a user's own key on a text field resolves case-insensitively unless the field declares otherwise, and 'aB3' and 'Ab3' compare equal under it (the blockquote below makes the same argument against collating the appended key). Such a sort is not total, so nothing after it is dropped and the exact tiebreaker is appended as before. One gap predates this rule and is left as it was: a sort that already ends in the case-insensitive key ([code], [age, code]) gets no tiebreaker, because the user's key already names the column and nothing separates case variants there (the rows tie in the engine's own order; a host that needs more declares the key case-sensitive). Rule 1 applies regardless. Where the exact tiebreaker is appended after an earlier key on the same column (the user's collated key, then the exact tiebreaker), two arms cannot list a column twice, and each spells the tiebreaker as a different expression instead (Bug #2809; fixture sort-paging/017 carries both arms): SQL Server spells the repeated tiebreaker with the field's case-sensitive mechanism, SC-3's own spelling, [code] COLLATE Latin1_General_CS_AS, and carries that collation inside the tiebreaker's null-bucket CASE (SQL Server refuses an ORDER BY expression identical to an earlier one, error 169, and accepts the same column under a different collation; measured on SQL Server 2022); MongoDB sorts the tiebreaker on a synthetic field holding {$toHashedIndexKey: "$code"} (a non-string, which the query's collation cannot fold), added with the null buckets and unset after the $sort. The other four SQL dialects accept a repeated column and render the same case-sensitive spelling where they have one (SQLite, Oracle); PostgreSQL renders it bare (its column default) and MySQL has no collation to spell, so there a case-insensitive column keeps folding case in the tiebreaker, which is the DDL-side host obligation GRP-2 and SC-3 already record: the host declares such a stable key case-sensitive or on a binary collation. The tie order among case variants is not promised to be the same on every arm: PostgreSQL and the Search arm order them by the column's default and the keyword field, SQL Server by CS_AS (lowercase first) and MongoDB by hash. Where the tiebreaker is exact, that order is stable and no variant is dropped or repeated; no rule says which of two case variants that tie on every earlier key comes first, and no fixture's expected rows depend on it. The user's own null placement is not repeated for it: a null ties on the earlier key already.
A dropped key is never a way around the allowlist. The reductions run only on a sort every key of which the query knows: on a row query, a field of the schema; on a grouped level, the group column or one of the level's aggregate column ids (GRP-4). A sort that names anything else is left as it is, so the compiler's own check still sees the unknown key and rejects it exactly as SC-1, SEC-6 and GRP-4 require, wherever in the sort it sits (adversarial/028). Only a key that is known and redundant is ever dropped.
The result names every field at most once, except in that exception, and, whenever the stable key is among them, ends in it. The first wording of this rule only asked whether the sort ends in the stable key, so [id desc, age asc] compiled to ORDER BY id DESC, age ASC, id ASC: SQL Server refuses a column named twice in an ORDER BY list (error 169), and a MongoDB $sort document cannot hold one key twice, so the same request failed on one arm and was ambiguous on another. A field before the stable key is kept ([age asc, id desc] stays as written). The reductions apply to the group column in a grouped level exactly as to the stable key, with rule 2 unconditional (GRP-4, GRP-2: it is unique and exact across the level's rows by construction), so an aggregate of the level after the group column is dropped (a Search level used to refuse it; it can never change the order of one-bucket-per-value rows). A column the level does not produce is not an aggregate and is not dropped: GRP-4 rejects it wherever it sits. The reductions also apply to every consumer of the effective sort, including the keyset walk of an export.
Must NOT: reject a request for naming a field twice or for sorting past the stable key (the grid cannot prevent either, and the order the user asked for is still honoured); drop a key that comes before the stable key, and drop a key that is the first occurrence of its field; drop the keys after a case-insensitive text stable key; drop a key the query does not know (it must reach the rejection); keep a dropped key "for the record" in any backend's artifact.
Superseded in part by GRP-4 (#1640) for a grouped level, and by GRP-6 (#1641) for BM-3's distinct-values query. This rule says the appended key is always the schema's
stableKey, and its first Must-NOT below forbids treating anything else as unique. On a grouped level that is now wrong: thestableKeyis not in the grouped projection at all, so ordering by it is invalid SQL rather than merely undesirable, and the group column plays its role instead — appended last, ascending, nulls last, and not appended twice when the sort already ends in it, all of which are this rule's own mechanics unchanged. The Must-NOT's intent is untouched and still binds: the substitute is not a key that "merely looks unique", it is unique across the level's rows by construction, since aGROUP BYemits one row per distinct value of it.A BM-3 distinct-values query appends nothing at all (GRP-6(e)) — and it is the exclusion this enumeration is most likely to be read past, because it carries no
groupSpecand so answers to "not grouped" on the only test a compiler has in front of it. It is nonetheless not a row query: thestableKeyis absent from its one-column projection exactly as it is from a grouped one, so appending it is the same invalid SQL, and its singleORDER BYkey — the distinct column — is already unique across the result rows by this blockquote's own by-construction argument, leaving no tie for a tiebreaker to break. A port that appends here emitsORDER BY "region" ASC NULLS LAST, "id" ASC NULLS LAST LIMIT $1and failsgroup-aggregation/016-019on all seven arms.Everything else — an ordinary row query, and a fully-consumed drill-down leaf, which projects rows — keeps
stableKeyexactly as written here. Recorded rather than deleted, since the affected artifacts (group-aggregation/001-004,007-015,020,021on every arm) were authored against the original.
Superseded in part by #1640's review, for the appended tiebreaker's case sensitivity. The appended key resolves exact — no case-folding mechanism is spelled on it — whatever SEM-1 says about the
stableKey's own field, and whether or not the query is grouped. Everything else about the tiebreaker is unchanged: still last, still ascending, still nulls-last, still not appended when the sort already ends in it.This is not a stylistic exemption, it is this rule's own guarantee. A
stableKeyis declared unique, and it is unique under the collation its storage uses; a compiler that attaches a different one is no longer comparing the text a user asked about, it is re-deciding row identity. The fixture suite'scraticula_ciis declareddeterministic = false, and under a non-deterministic collation'aB3'and'Ab3'compare equal — so a collated tiebreaker leaves exactly the ties it exists to break, the same statement may order those rows differently atOFFSET 0and atOFFSET 100, and a row is returned twice or dropped from both pages. That is the Rationale immediately below, and the third Must-NOT further down, reintroduced through this rule's own mechanism. Spelling nothing sorts the key under its storage collation, i.e. under the one its declared uniqueness is stated in. It is GRP-2's argument extended by one step: a key that establishes identity is not governed by how a field's values compare.The scope is the appended key only. A user's own sort key keeps SEM-1 in full, including on the stable key's own column when the request sorts by it explicitly (nothing was appended then) — so one statement legitimately reads
ORDER BY "last_name" COLLATE craticula_ci ASC NULLS LAST, "id" ASC NULLS LAST, a collated user key beside a bare tiebreaker, andspec/fixtures/sort-paging/001pins it. Recorded rather than folded into the rule becausegroup-aggregation/005/006are the only artifacts in the whole suite that ever pinned the collated form — measured across all seven backends — and both were authored, and re-authored, inside #1640.
Rationale. Paging over a sort key that isn't unique is non-deterministic at the database level: nothing in the SQL standard (or in Mongo's or ES's own documentation) guarantees that rows tied on the chosen sort key come back in the same relative order across two separate executions of the identical query — including two consecutive page reads of the same filter+sort. A user sorting a grid by lastName alone, with duplicate last names in the dataset, can see a row duplicated across two pages or silently missing from both, depending on how the engine happened to break the tie that particular time. This is a uniquely nasty bug class: the query "looks" correct, it reproduces intermittently, and the AG Grid UI itself gives the end user no way to add a tiebreaker (a user can only sort by the columns visible in the grid). Requiring the schema to declare a stableKey once, and having every compiler append it automatically, removes the ambiguity without depending on every sort model the UI might ever construct happening to already be unique.
Worked example — user sorts by lastName ASC only; schema declares stableKey: "id":
- SQL —
ORDER BYgains the tiebreaker as its final key, with its own explicit null placement per SEM-3 (NULLS LASThere, since the tiebreaker's direction is alwaysasc):ORDER BY last_name ASC NULLS LAST, id ASC NULLS LAST - MongoDB — the
$sortdocument gains the same trailing key (object key order is significant and preserved for$sort); ifidcan itself be null/missing, it goes through the same null-bucket emulation SEM-3 shows forlastName— bucket key before the real field, matching SEM-3's own canonical order exactly (not the reverse):{ "$sort": { "__lastNameNullBucket": 1, "lastName": 1, "__idNullBucket": 1, "id": 1 } }The
__idNullBucketstage is emitted unconditionally, with no exception —stableKeyis usually a non-nullable primary/surrogate key in practice, making the bucket a runtime no-op, butgrid-schema.schema.jsonhas no way to declare NOT NULL, so there is no schema state a compiler could check to justify skipping it. The same unconditional rule applies everywhere else this document's examples show the marker (SEM-3's own worked example, and every other tiebreaker example in this document) — "the field is probably never null in practice" is never a license to omit the mechanism; the mechanism is what makes it not matter if it turns out to be null. - OpenSearch / Elasticsearch — the
sortarray, whose element order is the tiebreak order, gains the mappedstableKeyfield (or its.keywordsub-field) as its last element, with its ownmissingparameter:{ "sort": [ { "lastName": { "order": "asc", "missing": "_last" } }, { "id": { "order": "asc", "missing": "_last" } } ] }
This is v1's only paging mechanism ($defs/rangePage's startRow/endRow, AG-3) — the tiebreaker's job is to make that offset-based paging deterministic, not to enable an alternative keyset-paging mode; see the "must NOT" below.
The page window is non-empty (AG-3, SEC-3). A request's startRow/endRow window must satisfy 0 <= startRow < endRow (endRow is exclusive, so endRow - startRow is the requested size and must be at least 1). A request with endRow <= startRow (an inverted window, or a zero-width one such as startRow: 100, endRow: 100) is refused at the AG Grid request boundary with a defined error before any compilation, identically for every backend; it is never compiled into a statement a backend may reject (T-SQL refuses FETCH NEXT 0 ROWS, msg 10744) or silently answer with an empty page. The refusal is requestParsing / malformed-request (adversarial/027). An IR built by hand may still carry a zero-size RangePage (an adapter's count-only query), which is why ir.schema.json keeps endRow >= startRow; the strict rule belongs to the wire request. Under EXP-1's exportScope: "all" the window is discarded (EXP-2) and therefore not checked.
Must NOT.
- Must NOT accept a client-supplied sort model that merely looks unique (a field that happens to have distinct values in a sample dataset) as sufficient without it being the schema's declared
stableKey— apparent uniqueness in a sample is not a guarantee. - Must NOT insert the tiebreaker ahead of, or interleaved with, the user's chosen sort keys — it is always the final key, so every key the user actually asked for keeps full precedence.
- Must NOT treat this rule as license to switch v1 grid paging from offset-based (
$defs/rangePage) to keyset-based paging — SQL keyset pagination is an explicit v2 opt-in (PERF-2), not a v1 requirement or even a v1 option. ThestableKeytiebreaker's job in v1 is narrower than "enabling keyset paging": it makes the existingstartRow/endRowoffset paging deterministic across page reads, by guaranteeing the sort itself has one and only one possible row ordering. EXP-3's ban onOFFSET-walking is a separate, narrower rule scoped to the export-streaming fallback path (chunking an unpaginated export when a driver can't stream) — it does not apply to, and must not be read as banning, ordinary v1 grid paging. - Must NOT omit the tiebreaker's null-ordering marker (SQL
NULLS, Mongo bucket, ESmissing) on the theory thatstableKeyis "probably never null" — there is no schema state that licenses this omission (see the worked example above); every tiebreaker in every artifact carries the marker, unconditionally, including underpage: none(EXP-2) and export scopes (EXP-1), which use the identical sort-compilation path as ordinary paged requests. (This bullet is about the marker on a tiebreaker that exists. It is not an enumeration of the shapes that get one, and in particular "unpaginated" does not imply "still appends": a BM-3 distinct-values query is also unpaginated and appends no tiebreaker at all — GRP-6(e), and the first blockquote above.)
Cross-links. $defs/sortItem (the array the compiler appends to), $defs/fieldName (stableKey is resolved through the schema the same way any other IR field reference is), $defs/pageSpec / $defs/rangePage (the paging context this rule protects the determinism of).