docs(578): scope the bound to LOGICAL ROWS — physical work is not bounded, and I claimed it was

Comment- and docs-only. Verified: the diff for both .cs files contains no non-comment line.

HIGH (claim). "LIMIT n reads exactly n index entries and n rows" is false, and the bounded-physical-
work reading it implied is false with it. Two mechanisms, both retracted explicitly in the record
rather than quietly reworded:

- MySQL purge lag. Deleted clustered-index records survive until purge runs and a range scan still
  traverses them, so returning 2,000 VISIBLE rows can touch far more index records. Deletion history
  therefore STILL affects physical work — precisely what attempt 4's failure was supposed to have
  made irrelevant. Attempt 5 removes the LOGICAL dependence on Id distribution; it does not make
  physical work independent of deletion history.
- Unbounded row width. Artists/AlbumArtists are unrestricted TEXT/longtext and both SQLite and InnoDB
  spill to overflow pages, so a row count implies neither a byte count nor a page-read count.

The guarantee is now stated as exactly what it is: at most 20,000 LOGICAL rows returned/materialized,
and at most 10 round trips (11 for artist). The 392 KiB measurement is labelled one data point on one
library whose credits average ~20 B/row, with an instruction to re-measure rather than extrapolate
for long credit lists or MySQL over a network. Also noted: the query-shape test pins the SQL STRING —
it cannot pin a plan, MVCC visibility work or payload I/O, and on MySQL using the index to satisfy
ORDER BY is an optimizer choice, not a semantic guarantee.

Precision fix, and the reviewer is right that the sloppy version misleads: "any predicate defeats
LIMIT" is wrong, since the query's own cursor is a predicate. The distinction is a SEEKABLE PREDICATE
ON THE ORDERING KEY (positions the scan, never discards a row) versus a RESIDUAL predicate (discards
rows the engine already produced, so LIMIT bounds survivors and says nothing about how many were
produced). Restated in the handler, the record and api-conventions.

MEDIUM. docs/decisions.md still advertised "a superset LIKE pre-filter that may over-match but never
under-match" for list-valued columns. That is the documented entry point for convention lookups, so a
maintainer starting there was told to preserve exactly what round 4 deleted, in direct contradiction
of the linked active record. Fixed.

LOW. Two test comments read as current: "however many non-matching rows" (false past the ceiling —
now bounded and cross-referenced to the test that pins that boundary) and the ampersand case
"widens to the bare anchor" (no prefix predicate exists; kept because it is the input shape that
broke the old scheme, now labelled as such).

Fifth consecutive round of stale text, so this sweep was done by grepping the subject across handler,
tests, record, decisions.md, api-conventions.md and the endpoint description: LIKE, ESCAPE,
pre-filter, superset, over-match, under-match, anchor, keyspace, window, candidate, row cap, index
entries, 392, and every deleted constant name. Every surviving hit is now either current-and-correct
or explicitly framed as history.
This commit is contained in:
2026-07-27 03:10:36 +02:00
parent b93a7d33ff
commit 5f73cd4482
6 changed files with 119 additions and 44 deletions
@@ -28,11 +28,31 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
/// ranges and inspects nothing.
/// </para>
/// <para>
/// What makes this one hold is that <b>the query has no predicate to evaluate and discard</b>. It is
/// a plain keyset page over the primary key, so <c>LIMIT</c> bounds index entries scanned and rows
/// returned alike, and it returns exactly <see cref="ListValuedBatchRows" /> rows whenever that many
/// remain — independent of how sparse the matches are, how many rows were deleted, or where the
/// gaps fall. Selectivity moves entirely into memory.
/// What makes this one hold is that <b>the query has no RESIDUAL predicate</b> — nothing that can
/// discard a row the engine already produced. The only condition is the cursor
/// <c>Id &gt; @AfterId</c>, which is a seek on the <c>ORDER BY</c> key itself, not a filter. So the
/// page returns exactly <see cref="ListValuedBatchRows" /> rows whenever that many logical rows
/// remain, independent of how sparse the matches are or where the <c>Id</c> gaps fall.
/// </para>
/// <para>
/// <b>Be precise about what is bounded: LOGICAL ROWS RETURNED AND MATERIALIZED, and the number of
/// round trips. Not physical work, and not bytes.</b> Two things break the stronger reading, and an
/// earlier version of this comment asserted it anyway:
/// <list type="bullet">
/// <item>
/// MySQL purge lag. Deleted clustered-index records survive until purge runs, and a range
/// scan still traverses them, so returning 2,000 VISIBLE rows can touch far more index
/// records. Deletion history therefore still affects physical work — the very thing the
/// keyspace attempt was trying to make irrelevant.
/// </item>
/// <item>
/// Row width is unbounded. These columns are <c>TEXT</c>/<c>longtext</c>, which both SQLite
/// and InnoDB spill to overflow pages, so a row count implies neither a byte count nor a
/// page-read count.
/// </item>
/// </list>
/// The logical-row bound is still worth having — it is what makes the walk terminate and what caps
/// what this process holds in memory — but do not restate it as bounded I/O.
/// </para>
/// <para>
/// The trade is real and deliberate: no server-side narrowing, so a query with few matches transfers
@@ -252,12 +272,20 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
/// <summary>
/// One keyset page of rows, by ROW POSITION rather than by <c>Id</c> value.
/// <para>
/// There is deliberately <b>no <c>WHERE</c> clause beyond the keyset cursor</b> — no <c>LIKE</c>, and
/// not even <c>IS NOT NULL</c>. Any predicate is something the engine must evaluate and discard,
/// which is what let every earlier revision scan past its own bound: <c>LIMIT</c> only truncates
/// what survives a predicate, so with one present it bounds the output and not the work. Stripped to
/// a bare primary-key range, <c>LIMIT n</c> reads exactly <c>n</c> index entries and <c>n</c> rows.
/// Null payloads are dropped in memory by <see cref="ParseElements" />.
/// The only condition is the cursor — deliberately <b>no RESIDUAL predicate</b>: no <c>LIKE</c>, no
/// <c>LOWER</c>, not even <c>IS NOT NULL</c>. The distinction that matters is not "no predicate"
/// (the cursor is one); it is that <c>Id &gt; @AfterId</c> is a <i>seekable predicate on the
/// ordering key</i>, which positions the scan and never discards a row, whereas a residual
/// predicate throws away rows the engine already produced. <c>LIMIT</c> only truncates what
/// survives a residual predicate, so with one present it bounds the output rather than the row
/// count — which is how every earlier revision scanned past its own bound. With none, <c>LIMIT n</c>
/// yields <c>n</c> logical rows. Null payloads are dropped in memory by
/// <see cref="ParseElements" />.
/// </para>
/// <para>
/// Note this pins the SQL string only. It cannot pin an execution plan, MVCC visibility work, or
/// payload I/O — and on MySQL, using the index to satisfy <c>ORDER BY</c> is an optimizer choice,
/// not a semantic guarantee.
/// </para>
/// </summary>
internal static string ListValuedSql(string column) =>
@@ -557,8 +557,9 @@ public class GetSearchFieldValuesHandlerTests
{
// Fails a883e5f0, which capped rows at a fixed 1000 AFTER a deliberately over-matching SQL pre-filter:
// the 1001st row -- the only exact match -- was discarded before the in-memory filter ever saw it and
// the endpoint returned []. The pre-filter is gone, but the property it broke is permanent: a match must
// not be hidden by however many non-matching rows happen to precede it.
// the endpoint returned []. The pre-filter is gone, and the property it broke now holds for any match
// within the read ceiling: preceding non-matching rows do not hide it. Past the ceiling it is still
// lost by design -- see List_Valued_Walk_Reads_At_Most_20000_Rows, which pins that boundary.
await using (TvContext context = _db.CreateContext())
{
for (var i = 0; i < 1000; i++)
@@ -587,7 +588,9 @@ public class GetSearchFieldValuesHandlerTests
artist.IsSome.ShouldBeTrue();
artist.IfSome(r => r.Values.ShouldBe(new List<string> { "\u00E9clair" }));
// ... and for a prefix stopped early by a JSON-escaped character, which also widens to the bare anchor
// ... and for a prefix beginning with a character that JSON escapes on disk. That used to collapse the
// SQL pattern to the bare anchor; there is no prefix predicate at all now, so it is simply an ordinary
// prefix -- kept because it is the input shape that broke the old scheme.
await using (TvContext context = _db.CreateContext())
{
context.SongMetadata.Add(Song("Ampersand", ["&Me"]));
+16 -9
View File
@@ -458,18 +458,25 @@ JSON array per row in a single column, with no server-side projection on either
therefore no longer 404s, and `artist` now also covers free-text music-video (`MusicVideoArtist`) and
song credits, not only entity artists. Those rows are read by a keyset page that carries **no predicate
at all** and filtered in memory, bounded at 20,000 rows per request — so on a larger library the
response may be a bounded subset of the matches. Say so in the `[EndpointDescription]` of any endpoint
that adopts this shape.
response may be a bounded subset of the matches — bounded in LOGICAL ROWS, which is not the same as
bounded work or bytes. Say so in the `[EndpointDescription]` of any endpoint that adopts this shape.
Three rules generalize beyond this endpoint.
1. **`LIMIT` bounds the OUTPUT, not the WORK, whenever a predicate is present.** It truncates what
survives the predicate, and the engine may evaluate and discard arbitrarily many rows first — a query
that matches nothing must examine every eligible row before it can return an empty page. If you need
to bound work, remove the predicate and page by row position over the primary key, then filter in
memory. This endpoint got it wrong four times: bounding the result, then candidates returned, then
`Id` keyspace width (keyspace is not rows — one live row at `Id` 20001 behind 20,000 deleted ones
reads nothing), before arriving at "no predicate, so `LIMIT n` reads exactly `n` rows".
1. **`LIMIT` bounds the OUTPUT, not the row count, whenever a RESIDUAL predicate is present.** The
distinction is not "predicate vs none" — a keyset cursor is a predicate. It is that a *seekable
predicate on the ordering key* positions the scan and never discards a row, while a *residual*
predicate (`LIKE`, `LOWER`, `IS NOT NULL`) throws away rows the engine already produced, so `LIMIT`
truncates the survivors and says nothing about how many were produced — a query matching nothing
must examine every eligible row before it can return an empty page. To bound rows, drop the residual
predicate, page by row position over the primary key, and filter in memory. This endpoint got it
wrong four times: bounding the result, then candidates returned, then `Id` keyspace width (keyspace
is not rows — one live row at `Id` 20001 behind 20,000 deleted ones reads nothing), before arriving
at "cursor only".
**And scope the resulting claim to LOGICAL ROWS.** It is not bounded physical work: MySQL still
traverses deleted-but-unpurged index records, so deletion history keeps affecting cost, and an
unrestricted `TEXT` column spills to overflow pages so a row count implies no byte or page-read
count. A SQL-string assertion pins none of that — not a plan, not visibility work, not I/O.
2. **A SQL pre-filter under an in-memory exact filter may over-match but must never under-match — and
that licence is void the moment the candidate set is truncated.** Widening the predicate then starves
the budget with rows that cannot match. If you find yourself proving a superset property to keep a
+1 -1
View File
@@ -215,4 +215,4 @@ another doc or an old issue comment should land here and then follow the link.
- 2026-07-25 — Rule-builder group nesting is bounded-arbitrary depth (`MAX_GROUP_DEPTH`), not one level (#436) — [`spa.rulebuilder-nesting`](decisions/records/spa/rulebuilder-nesting.md)
- 2026-07-25 — The rationale-edit marker is a git trailer, not a substring anywhere in the commit range (#609) — [`ci.decisions-edit-trailer`](decisions/records/ci/decisions-edit-trailer.md)
- 2026-07-25 — UI-E2E: headless Playwright flows in the existing `functional-e2e` job, browser baked into the CI image (#445) — [`ci.ui-e2e-harness`](decisions/records/ci/ui-e2e-harness.md)
- 2026-07-26 — Facet-value typeahead restated: every artist source covered; list-valued columns via a superset LIKE pre-filter that may over-match but never under-match (#578) — [`api.search-field-values-sources`](decisions/records/api/search-field-values-sources.md)
- 2026-07-26 — Facet-value typeahead restated: every artist source covered; the JSON-column source is paged by row position with no residual SQL predicate (#578) — [`api.search-field-values-sources`](decisions/records/api/search-field-values-sources.md)
+1 -1
View File
@@ -28,7 +28,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `api.schedule-item-flat-dto` | Schedule-item GET/POST/PUT use a flat, non-polymorphic `ScheduleItemResponseModel` (every subtype field promoted to a nullable top-level member) instead of the polymorphic Application VM hierarchy, with mutation field names matching `ScheduleItemRequest` 1:1 for a lossless round-trip. | 2026-07-10 | [link](records/api/schedule-item-flat-dto.md) |
| `api.scheduling-hardening` | Create/Replace handlers guard against null/whitespace `name` (`IsNullOrWhiteSpace`, not just `Length`) to prevent NRE-500s, template-item overlap validation compares by index (not record value-equality) to catch exact-duplicate items, and unreachable 404 `ProducesResponseType` attributes on create-only actions are trimmed. | 2026-07-13 | [link](records/api/scheduling-hardening.md) |
| `api.search-allitems-paging` | `GET /api/v1/search/all-items` is paginated (capped page size, `Totals` field) to bound DoS exposure; the SPA add-all flow pages to completeness instead of relying on an unbounded response. | 2026-07-18 | [link](records/api/search-allitems-paging.md) |
| `api.search-field-values-sources` | `GET /api/v1/search/fields/{name}/values?q=&limit=` returns distinct WHOLE values from the database for a narrow allow-list of catalog fields (never the Lucene term dictionary — analyzed `TextField`s store lowercased word tokens, e.g. "Science Fiction" → `science`/`fiction`, useless as a suggestion), 404 for an unknown field, a non-`text` field, or a `text` field with no distinct-value source (`title`, `show_title` only); `limit` clamped to `[1, 50]` (default 50). The FINAL filter, dedup and ordering applied to the response are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled — scoped to the in-memory stages on purpose: a field sourced by a plain EF query is filtered and truncated by the DATABASE collation first (SQLite's `LOWER()` is ASCII-only), which ordinal semantics downstream cannot undo (ersatztv#668). A field whose values live in an EF **primitive collection** (one JSON array per row in a single column: `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) is served, not 404'd, as bounded best-effort, and its rows are read by a keyset page carrying **NO predicate whatsoever** — `SELECT Id, <col> AS Payload FROM SongMetadata WHERE Id > @AfterId ORDER BY Id LIMIT @Batch`, no `LIKE`, no `LOWER`, not even `IS NOT NULL` — because `LIMIT` only truncates what survives a predicate, so any predicate at all makes it bound the OUTPUT rather than the WORK. All selectivity is in memory. The walk reads at most 20,000 actual rows in 2,000-row pages, density-independent, stopping on the first of enough distinct matches, a short page, or the ceiling; the cost of having no server-side narrowing is a measured 392 KiB of JSON transferred in the worst case (20,000 rows, ~20 B/row). | 2026-07-26 | [link](records/api/search-field-values-sources.md) |
| `api.search-field-values-sources` | `GET /api/v1/search/fields/{name}/values?q=&limit=` returns distinct WHOLE values from the database for a narrow allow-list of catalog fields (never the Lucene term dictionary — analyzed `TextField`s store lowercased word tokens, e.g. "Science Fiction" → `science`/`fiction`, useless as a suggestion), 404 for an unknown field, a non-`text` field, or a `text` field with no distinct-value source (`title`, `show_title` only); `limit` clamped to `[1, 50]` (default 50). The FINAL filter, dedup and ordering applied to the response are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled — scoped to the in-memory stages on purpose: a field sourced by a plain EF query is filtered and truncated by the DATABASE collation first (SQLite's `LOWER()` is ASCII-only), which ordinal semantics downstream cannot undo (ersatztv#668). A field whose values live in an EF **primitive collection** (one JSON array per row in a single column: `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) is served, not 404'd, as bounded best-effort, and its rows are read by a keyset page carrying **NO predicate whatsoever** — `SELECT Id, <col> AS Payload FROM SongMetadata WHERE Id > @AfterId ORDER BY Id LIMIT @Batch`, no `LIKE`, no `LOWER`, not even `IS NOT NULL` — because `LIMIT` only truncates what survives a predicate, so any predicate at all makes it bound the OUTPUT rather than the WORK. All selectivity is in memory. The guarantee is scoped: **at most 20,000 LOGICAL rows returned/materialized and at most 10 round trips (11 for `artist`)** — NOT bounded physical work and NOT bounded bytes, because MySQL traverses deleted-but-unpurged index records and the `TEXT`/`longtext` payload width is unrestricted. The walk pages 2,000 rows at a time, stopping on the first of enough distinct matches, a short page, or the ceiling. | 2026-07-26 | [link](records/api/search-field-values-sources.md) |
| `api.search-paging-cap` | Search stays capped at 100 items per media kind; an overflowing kind's "See all" reuses library-browse paging instead of adding new API surface. | 2026-07-11 | [link](records/api/search-paging-cap.md) |
| `api.versioning-v1` | The entire `/api` surface is versioned to `/api/v1` uniformly (no unversioned corner); legacy unversioned callers are rewritten in-pipeline (not redirected) with Deprecation/Link/Sunset headers, and post-freeze `/api/v1` is additive-only — a breaking change requires `/api/v2`. | 2026-07-13 | [link](records/api/versioning-v1.md) |
| `blazor.rollback-tag` | The commit immediately preceding the Blazor-removal merge is tagged `blazor-final` (not a `v*` tag, so it doesn't trigger a prod release build) as the documented rollback/restore path. | 2026-07-11 | [link](records/blazor/rollback-tag.md) |
@@ -5,8 +5,8 @@ status: active
since: '2026-07-26'
supersedes: api.search-field-values@2026-07-23
superseded-by: none
rule: '`GET /api/v1/search/fields/{name}/values?q=&limit=` returns distinct WHOLE values from the database for a narrow allow-list of catalog fields (never the Lucene term dictionary — analyzed `TextField`s store lowercased word tokens, e.g. "Science Fiction" → `science`/`fiction`, useless as a suggestion), 404 for an unknown field, a non-`text` field, or a `text` field with no distinct-value source (`title`, `show_title` only); `limit` clamped to `[1, 50]` (default 50). The FINAL filter, dedup and ordering applied to the response are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled — scoped to the in-memory stages on purpose: a field sourced by a plain EF query is filtered and truncated by the DATABASE collation first (SQLite''s `LOWER()` is ASCII-only), which ordinal semantics downstream cannot undo (ersatztv#668). A field whose values live in an EF **primitive collection** (one JSON array per row in a single column: `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) is served, not 404''d, as bounded best-effort, and its rows are read by a keyset page carrying **NO predicate whatsoever** — `SELECT Id, <col> AS Payload FROM SongMetadata WHERE Id > @AfterId ORDER BY Id LIMIT @Batch`, no `LIKE`, no `LOWER`, not even `IS NOT NULL` — because `LIMIT` only truncates what survives a predicate, so any predicate at all makes it bound the OUTPUT rather than the WORK. All selectivity is in memory. The walk reads at most 20,000 actual rows in 2,000-row pages, density-independent, stopping on the first of enough distinct matches, a short page, or the ceiling; the cost of having no server-side narrowing is a measured 392 KiB of JSON transferred in the worst case (20,000 rows, ~20 B/row).'
signals: 'artist typeahead free-text credits, album_artist 404, artist suggestions missing music videos, SongMetadata.Artists, SongMetadata.AlbumArtists, MusicVideoArtist, EF primitive collection, PrimitiveCollection JSON column, SelectMany requires APPLY on SQLite, Pomelo primitive collections not enabled, LIMIT bounds output not work, predicate defeats LIMIT as a bound, keyspace is not rows, page by row position, density-independent paging, deleted rows leave Id gaps, ListValuedBatchRows, ListValuedMaxRowsRead, bounded best-effort facet values, OrdinalIgnoreCase vs InvariantCultureIgnoreCase folding, Accept-Language tr-TR dotless i, content_rating split, text field allow-list · paths: `ErsatzTV.Application/Search/Queries/GetSearchFieldValuesHandler.cs`, `ErsatzTV/Controllers/Api/SearchController.cs`, `ErsatzTV.Tests/Application/Search/GetSearchFieldValuesHandlerTests.cs`, `ErsatzTV.Tests/Application/Search/SearchFieldValuesQueryShapeTests.cs`, `web/src/api/search.ts` · issues: #578, #434, #176, #668, #669'
rule: '`GET /api/v1/search/fields/{name}/values?q=&limit=` returns distinct WHOLE values from the database for a narrow allow-list of catalog fields (never the Lucene term dictionary — analyzed `TextField`s store lowercased word tokens, e.g. "Science Fiction" → `science`/`fiction`, useless as a suggestion), 404 for an unknown field, a non-`text` field, or a `text` field with no distinct-value source (`title`, `show_title` only); `limit` clamped to `[1, 50]` (default 50). The FINAL filter, dedup and ordering applied to the response are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled — scoped to the in-memory stages on purpose: a field sourced by a plain EF query is filtered and truncated by the DATABASE collation first (SQLite''s `LOWER()` is ASCII-only), which ordinal semantics downstream cannot undo (ersatztv#668). A field whose values live in an EF **primitive collection** (one JSON array per row in a single column: `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) is served, not 404''d, as bounded best-effort, and its rows are read by a keyset page carrying **NO predicate whatsoever** — `SELECT Id, <col> AS Payload FROM SongMetadata WHERE Id > @AfterId ORDER BY Id LIMIT @Batch`, no `LIKE`, no `LOWER`, not even `IS NOT NULL` — because `LIMIT` only truncates what survives a predicate, so any predicate at all makes it bound the OUTPUT rather than the WORK. All selectivity is in memory. The guarantee is scoped: **at most 20,000 LOGICAL rows returned/materialized and at most 10 round trips (11 for `artist`)** — NOT bounded physical work and NOT bounded bytes, because MySQL traverses deleted-but-unpurged index records and the `TEXT`/`longtext` payload width is unrestricted. The walk pages 2,000 rows at a time, stopping on the first of enough distinct matches, a short page, or the ceiling.'
signals: 'artist typeahead free-text credits, album_artist 404, artist suggestions missing music videos, SongMetadata.Artists, SongMetadata.AlbumArtists, MusicVideoArtist, EF primitive collection, PrimitiveCollection JSON column, SelectMany requires APPLY on SQLite, Pomelo primitive collections not enabled, LIMIT bounds output not work, seekable cursor vs residual predicate, MySQL purge lag traverses deleted index records, TEXT overflow pages, logical rows not physical work, keyspace is not rows, page by row position, density-independent paging, deleted rows leave Id gaps, ListValuedBatchRows, ListValuedMaxRowsRead, bounded best-effort facet values, OrdinalIgnoreCase vs InvariantCultureIgnoreCase folding, Accept-Language tr-TR dotless i, content_rating split, text field allow-list · paths: `ErsatzTV.Application/Search/Queries/GetSearchFieldValuesHandler.cs`, `ErsatzTV/Controllers/Api/SearchController.cs`, `ErsatzTV.Tests/Application/Search/GetSearchFieldValuesHandlerTests.cs`, `ErsatzTV.Tests/Application/Search/SearchFieldValuesQueryShapeTests.cs`, `web/src/api/search.ts` · issues: #578, #434, #176, #668, #669'
mechanics: '`GetSearchFieldValuesHandler` (`GetSource`, `GetSongListValuedColumn`, `GetSongListValuedValues`, `ListValuedSql`, `ParseElements`, `FilterSortTake`); `SearchFieldValuesQueryShapeTests.List_Valued_Page_Query_Has_No_Predicate_Beyond_The_Keyset_Cursor`; api-conventions.md; spa-conventions.md §12'
---
@@ -101,28 +101,63 @@ and each was caught only by someone constructing the adversarial case rather tha
| 4 | **keyspace width** — closed `Id` range per page | keyspace is not rows. Delete 20,000 historical rows, put one song at `Id` 20001, `q=que` → `[]`. **One row in the table, zero rows inspected.** Capacity fell linearly with deletion ratio and no ratio was safe: one placed gap hides the next match |
| 5 | **actual rows** — keyset page by row position, **no predicate** | — |
The through-line: **`LIMIT` truncates what survives a predicate.** With any predicate present it
bounds the output and says nothing about the work; the engine may evaluate and discard arbitrarily
many rows first. Attempts 3 and 4 both tried to keep selectivity in SQL and add accounting around it.
Attempt 5 removes the predicate, so `LIMIT n` reads exactly `n` index entries and `n` rows regardless
of data, sparsity or deletion history, and the accounting becomes trivial:
The through-line: **`LIMIT` truncates what survives a RESIDUAL predicate.** The distinction is not
"predicate vs no predicate" — attempt 5's query still has `Id > @AfterId`. It is:
- a **seekable predicate on the ordering key** (the cursor) positions the scan and never discards a
row, so `LIMIT n` yields `n` rows;
- a **residual predicate** (`LIKE`, `LOWER`, `IS NOT NULL`) throws away rows the engine already
produced, so `LIMIT` bounds the survivors and says nothing about how many were produced.
Attempts 3 and 4 both kept selectivity in SQL and tried to add accounting around it. Attempt 5 drops
the residual predicate and keeps only the cursor, so the accounting becomes trivial:
```sql
SELECT Id, Artists AS Payload FROM SongMetadata WHERE Id > @AfterId ORDER BY Id LIMIT @Batch
```
`ListValuedBatchRows = 2000`, `ListValuedMaxRowsRead = 20000`. The walk stops on the first of: enough
distinct matches for `limit`, a short page (with no predicate, that can only mean exhaustion — it can
never mean "this stretch matched nothing", which is exactly why the predicate had to go), or the
ceiling. Round trips: **at most 10** for `album_artist`, **at most 11** for `artist`, which also runs
one EF query for its entity/music-video half. `SearchFieldValuesQueryShapeTests` pins the SQL string
exactly and asserts the absence of `LIKE`, `LOWER` and `IS NOT NULL`, so a future reviewer
reintroducing "just a cheap filter" fails a test instead of silently unbounding the walk.
distinct matches for `limit`, a short page (with no residual predicate that can only mean exhaustion
— it can never mean "this stretch matched nothing", which is exactly why the residual predicate had
to go), or the ceiling. Round trips: **at most 10** for `album_artist`, **at most 11** for `artist`,
which also runs one EF query for its entity/music-video half.
`SearchFieldValuesQueryShapeTests` pins the SQL string exactly and asserts the absence of `LIKE`,
`LOWER` and `IS NOT NULL`, so a reviewer reintroducing "just a cheap filter" fails a test instead of
silently unbounding the walk.
### Exactly what is bounded — and what is NOT
State this precisely, because an earlier version of this record claimed more and the overclaim is
more dangerous than the code ever was. What holds:
- **at most `ListValuedMaxRowsRead` logical rows returned and materialized per request**, and
- **at most 10 (or 11) round trips.**
That is the whole guarantee. It is what makes the walk terminate and what caps what this process
holds in memory. **Explicitly retracted**, having been asserted here in an earlier revision:
- ~~"`LIMIT n` reads exactly `n` index entries"~~ — **false on MySQL.** Deleted clustered-index
records survive until purge runs, and a range scan still traverses them. Hold an old InnoDB
snapshot open, delete a million early `SongMetadata` rows, and query from a newer snapshot with
purge blocked: returning 2,000 *visible* rows can touch far more index records. **Deletion history
therefore still affects physical work** — the very thing attempt 4's failure was supposed to have
made irrelevant. Attempt 5 fixes the *logical* dependence on `Id` distribution; it does not make
physical work independent of deletion history.
- ~~bounded physical work / bounded I/O~~ — row width is unbounded. `Artists`/`AlbumArtists` are
unrestricted `TEXT`/`longtext`, and both SQLite and InnoDB spill large payloads to overflow pages,
so a row count implies neither a byte count nor a page-read count.
Nor can the query-shape test carry more than it does: it pins the SQL **string**. It cannot pin an
execution plan, MVCC visibility work, or payload I/O — and on MySQL, using the index to satisfy
`ORDER BY` is an optimizer choice, not a SQL semantic.
### The cost, measured
No server-side narrowing means rows are transferred that will be discarded. Measured on a seeded
20,000-song library (in-memory SQLite, so the SQL wall time is a floor, not a production figure):
No server-side narrowing means rows are transferred that will be discarded. **This is ONE data point
on ONE library, not a general figure** — see the row-width caveat above: these numbers hold for a
library whose artist credits average ~20 bytes of JSON, and a library with long credit lists would
transfer proportionally more for the same row count. Measured on a seeded 20,000-song library
(in-memory SQLite, so the wall times are a floor, not a production figure):
| case | rows read | round trips | payload | wall |
|---|---|---|---|---|
@@ -131,10 +166,12 @@ No server-side narrowing means rows are transferred that will be discarded. Meas
| dense prefix (`rad`) | 2,000 | 1 | ~39 KiB | ~38 ms |
| non-ASCII prefix (`beyoncé`) | 2,000 | 1 | ~39 KiB | ~39 ms |
Judged acceptable: the worst case is a debounced typeahead keystroke that matches nothing, at ~392
KiB and tens of milliseconds against a local SQLite file. Dense queries — including the empty `q` the
combobox opens with — stop on the first page. **If this ever becomes unacceptable, do not reintroduce
selectivity;** that is the trap this record exists to document. Go to #669.
Judged acceptable **for this shape of library**: the worst case is a debounced typeahead keystroke
that matches nothing, at ~392 KiB and tens of milliseconds against a local SQLite file. Dense queries
— including the empty `q` the combobox opens with — stop on the first page. Re-measure rather than
extrapolate if credit lists are long or the provider is MySQL over a network. **If it ever becomes
unacceptable, do not reintroduce selectivity;** that is the trap this record exists to document. Go
to #669.
### Accepted losses