fix(578): bound the Id KEYSPACE — LIMIT cannot bound a query that matches nothing
BLOCKER. Round 3's ceiling counted LIKE-positive candidates, which is not the quantity that needed bounding. To return an empty page the engine must first evaluate every eligible row, so a no-match query came back with rows.Count == 0, ended the walk having counted zero against the ceiling, and had already inspected the entire table. Round trips and materialized rows were bounded; database work was not. Worse, a dense widened prefix could materialize 20x the candidates and make 10x the round trips of round 1 — a regression dressed as a bound. Third time bounding the wrong quantity: revisions 1-2 bounded the RESULT (a fixed LIMIT budget the widened pattern starved), revision 3 bounded the CANDIDATES, and neither bounds what the database LOOKS AT. Now the Id range is closed on both sides — `Id > @AfterId AND Id <= @AfterId + @Window` — so each round trip is a primary-key range scan of known width. The LIKE still decides what comes back; it no longer decides how much gets looked at. The walk advances by the WINDOW, never by what returned (an empty page means "nothing matched in this stretch", not "exhausted"), and there is deliberately no LIMIT in the SQL — the window caps the row count, and a LIMIT would only restore the illusion that it is doing the bounding. One indexed SELECT MAX(Id) up front stops the walk burning windows on empty keyspace. Result: at most 10 round trips and 20,000 rows inspected for any q, matching or not. New test `List_Valued_Walk_Cannot_Inspect_Past_The_Bound_When_Nothing_Matches` covers the case every earlier bound test missed — they all gave the pre-filter something to return. With a narrow pattern and a needle at row 30,000, revision 3 returns the needle (right answer, unbounded work) and this revision returns []. Paired with a positive control at row 20,000 inside the bound. The ceiling's remaining false negative (20,000 "zzz" rows then "éclair" at 20,001 -> []) is kept and still pinned: it is the documented bounded-best-effort contract at a rarer threshold, not a defect. Stale/false comments, several of them repeat offenders: - The handler still used "Zulu"/"Éclair" as the truncation example, where both orderings pick "Zulu". I had corrected the test and left the comment. Now "Zulu"/"apple" in both. - "leans entirely on the row cap" described a mechanism that no longer exists. - The escape example rendered as literal Édith/É/é rather than the escape TEXT (Édith, É, é) in both the handler and the record, contradicting the explanation it was giving. - "every accented artist was unsuggestable" overstated it: exactly three of the nine pinned cases fail 1b78dc9e (those where query and stored casing differ, so the escape texts diverge); the other six pass. The record now says what the test comment already said. - The record claimed the ordinal switch left response SETS unchanged. False — ordering runs before Take(limit), so with "Zulu"/"apple", empty q and limit=1 the comparer changes which value survives. - The_Scan_Ceiling_Is_A_Whole_Number_Of_Batches was a style preference wearing a correctness costume (a 20,500 ceiling is perfectly safe — the final window clamps). Replaced with the invariant that actually matters: the walk's own arithmetic terminates and lands exactly on the ceiling.
This commit is contained in:
@@ -15,28 +15,34 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
private const int MaxLimit = 50;
|
||||
|
||||
/// <summary>
|
||||
/// Rows fetched per round trip when walking the list-valued (JSON-array) columns on
|
||||
/// <c>SongMetadata</c>, and the overall ceiling on rows materialized for one request.
|
||||
/// Width of the <c>Id</c> keyspace window examined per round trip when walking the list-valued
|
||||
/// (JSON-array) columns on <c>SongMetadata</c>, and the ceiling on total keyspace visited per request.
|
||||
/// <para>
|
||||
/// These bound EFFORT, not the result. An earlier revision used a single fixed row budget, which
|
||||
/// looked equivalent and was not: the SQL pre-filter is deliberately allowed to over-match, so
|
||||
/// widening it (which is what a non-ASCII or JSON-escaped prefix does — it collapses to the bare
|
||||
/// `%"%` anchor) floods the candidate set with rows that cannot match, and a fixed budget then
|
||||
/// discards real matches sitting behind them. Seed 1000 songs and put the only accented artist in
|
||||
/// row 1001 and the endpoint returned nothing. Over-matching is only free when the candidate set is
|
||||
/// not truncated.
|
||||
/// What these bound is <b>rows the database LOOKS AT</b>, and getting that right took three tries.
|
||||
/// A single fixed <c>LIMIT</c> budget was wrong because the pre-filter is deliberately allowed to
|
||||
/// over-match: a non-ASCII or JSON-escaped prefix collapses the pattern to the bare <c>%"%</c>
|
||||
/// anchor, every row becomes a candidate, and the budget gets spent on rows that cannot match while
|
||||
/// real matches sit behind them. Keyset-paging with a <c>LIMIT</c> fixed that but bounded the wrong
|
||||
/// quantity: <c>LIMIT</c> caps rows RETURNED, and a query with no matches must evaluate every
|
||||
/// eligible row before it can return an empty page. Rows examined stayed bounded only by table size.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// So the walk is keyset-paged on <c>Id</c> and stops on the first of: enough distinct exact matches
|
||||
/// to satisfy <c>limit</c>, the source exhausted, or <see cref="ListValuedMaxScannedRows" /> rows
|
||||
/// examined. Only the last of those is lossy, and it needs that many CANDIDATE rows — rows that
|
||||
/// already passed the SQL pre-filter — before it bites.
|
||||
/// So the window is on the <b>keyspace</b> — <c>Id > @AfterId AND Id <= @AfterId + @Window</c>
|
||||
/// — which the primary key can range-scan. The <c>LIKE</c> still decides what comes BACK; it no
|
||||
/// longer decides how much gets LOOKED AT. Each round trip inspects at most <see cref="ListValuedWindowRows" />
|
||||
/// rows and the walk visits at most <see cref="ListValuedMaxVisitedRows" /> in total, whether or not
|
||||
/// anything matches.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The walk stops on the first of: enough distinct exact matches to satisfy <c>limit</c>, the
|
||||
/// keyspace exhausted, or the ceiling. Only the ceiling is lossy — a match beyond it is not found,
|
||||
/// which is the bounded-best-effort contract the endpoint documents.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal const int ListValuedBatchRows = 2000;
|
||||
internal const int ListValuedWindowRows = 2000;
|
||||
|
||||
/// <inheritdoc cref="ListValuedBatchRows" />
|
||||
internal const int ListValuedMaxScannedRows = 20000;
|
||||
/// <inheritdoc cref="ListValuedWindowRows" />
|
||||
internal const int ListValuedMaxVisitedRows = 20000;
|
||||
|
||||
/// <summary>
|
||||
/// Escape character for the raw-JSON <c>LIKE</c> pre-filter. Deliberately NOT a backslash: the stored
|
||||
@@ -121,8 +127,9 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
// ORDERING IS BEST-EFFORT, NOT EXACT. Each source truncates using its own ordering — the EF source by the
|
||||
// database collation (SQLite's NOCASE/BINARY is ASCII-only), the list source by primary key — and neither
|
||||
// is the ordinal ordering applied here. So when a source actually truncates, a value it dropped may have
|
||||
// outranked one that survived: with "Zulu" and "Éclair" and limit=1 the EF source keeps "Zulu" and the
|
||||
// merge never sees "Éclair". Below the truncation points (the normal typeahead case) the result is exact.
|
||||
// outranked one that survived: with "Zulu" and "apple" and limit=1 the database keeps "apple" (its
|
||||
// ordering is case-insensitive) while ordinal ranks "Zulu" first, so the merge never sees "Zulu".
|
||||
// Below the truncation points (the normal typeahead case) the result is exact.
|
||||
return new SearchFieldValuesResponseModel(FilterSortTake(values.Distinct(StringComparer.Ordinal), query, limit));
|
||||
}
|
||||
|
||||
@@ -192,27 +199,26 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
string sql = ListValuedSql(column);
|
||||
string pattern = JsonElementPrefixPattern(query);
|
||||
|
||||
// one indexed lookup, so an exhausted keyspace ends the walk instead of burning windows on empty range
|
||||
int maxId = await dbContext.Connection.ExecuteScalarAsync<int>(
|
||||
new CommandDefinition(
|
||||
"SELECT COALESCE(MAX(Id), 0) FROM SongMetadata",
|
||||
cancellationToken: cancellationToken));
|
||||
|
||||
var distinct = new System.Collections.Generic.HashSet<string>(StringComparer.Ordinal);
|
||||
var afterId = 0;
|
||||
var scanned = 0;
|
||||
var visited = 0;
|
||||
|
||||
while (scanned < ListValuedMaxScannedRows && distinct.Count < limit)
|
||||
while (afterId < maxId && visited < ListValuedMaxVisitedRows && distinct.Count < limit)
|
||||
{
|
||||
int batch = Math.Min(ListValuedBatchRows, ListValuedMaxScannedRows - scanned);
|
||||
int window = Math.Min(ListValuedWindowRows, ListValuedMaxVisitedRows - visited);
|
||||
int upperId = afterId + window;
|
||||
|
||||
List<ListValuedRow> rows = (await dbContext.Connection.QueryAsync<ListValuedRow>(
|
||||
IEnumerable<ListValuedRow> rows = await dbContext.Connection.QueryAsync<ListValuedRow>(
|
||||
new CommandDefinition(
|
||||
sql,
|
||||
new { Pattern = pattern, AfterId = afterId, Batch = batch },
|
||||
cancellationToken: cancellationToken))).AsList();
|
||||
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
scanned += rows.Count;
|
||||
afterId = rows[^1].Id;
|
||||
new { Pattern = pattern, AfterId = afterId, UpperId = upperId },
|
||||
cancellationToken: cancellationToken));
|
||||
|
||||
foreach (ListValuedRow row in rows)
|
||||
{
|
||||
@@ -225,11 +231,10 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.Count < batch)
|
||||
{
|
||||
// short page: the source is exhausted, not merely bounded
|
||||
break;
|
||||
}
|
||||
// advance by the WINDOW, never by what came back: an empty page means "nothing matched in this
|
||||
// stretch of keyspace", not "the source is exhausted"
|
||||
afterId = upperId;
|
||||
visited += window;
|
||||
}
|
||||
|
||||
return distinct.ToList();
|
||||
@@ -253,18 +258,23 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One keyset page of candidate rows. <c>LOWER(...) LIKE ... ESCAPE</c>, <c>ORDER BY</c> and
|
||||
/// <c>LIMIT</c> are all portable between SQLite and MySQL, and the identifiers are unquoted so neither
|
||||
/// provider's quoting dialect is baked in. Paging rides <c>Id</c> — a unique integer key both providers
|
||||
/// can walk — rather than the JSON column: ordering on <c>TEXT</c> would not be deterministic on MySQL,
|
||||
/// which sorts using only the first <c>max_sort_length</c> bytes, and a keyset predicate on the primary
|
||||
/// key lets each page resume instead of re-scanning what the previous page already rejected.
|
||||
/// One keyspace window of candidate rows. <c>LOWER(...) LIKE ... ESCAPE</c> and <c>ORDER BY</c> are
|
||||
/// portable between SQLite and MySQL, and the identifiers are unquoted so neither provider's quoting
|
||||
/// dialect is baked in.
|
||||
/// <para>
|
||||
/// The <b>upper</b> bound is what makes this bounded work rather than a bounded result: with only
|
||||
/// <c>Id > @AfterId</c> and a <c>LIMIT</c>, a no-match query still forces the engine to evaluate
|
||||
/// every remaining row before it can return an empty page. Closing the range turns each round trip
|
||||
/// into a primary-key range scan of known width. There is deliberately no <c>LIMIT</c> — the window
|
||||
/// already caps the row count, and a <c>LIMIT</c> here would re-introduce the illusion that it is
|
||||
/// doing the bounding.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal static string ListValuedSql(string column) =>
|
||||
$"SELECT Id, {column} AS Payload FROM SongMetadata WHERE {column} IS NOT NULL " +
|
||||
"AND Id > @AfterId " +
|
||||
"AND Id > @AfterId AND Id <= @UpperId " +
|
||||
$"AND LOWER({column}) LIKE @Pattern ESCAPE '{LikeEscapeChar}' " +
|
||||
"ORDER BY Id LIMIT @Batch";
|
||||
"ORDER BY Id";
|
||||
|
||||
private sealed class ListValuedRow
|
||||
{
|
||||
@@ -286,15 +296,20 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
/// So the pattern narrows on the <b>leading run of ASCII characters the JSON writer stores
|
||||
/// verbatim</b>, and stops at the first character it cannot reason about — a non-ASCII character, or
|
||||
/// one of <see cref="JsonEscapedAscii" />. A query starting with such a character narrows to the bare
|
||||
/// element-opening anchor <c>%"%</c> and leans entirely on the row cap and the in-memory filter.
|
||||
/// element-opening anchor <c>%"%</c>, which matches every non-empty row — so the walk's keyspace
|
||||
/// bound, not the pattern, is what keeps that case bounded, and the in-memory filter is what keeps
|
||||
/// it correct.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Why that is sound, and why an earlier "JSON-encode the whole prefix" version was NOT: the stored
|
||||
/// text escapes non-ASCII, so <c>Édith</c> is on disk as <c>Édith</c>. SQL <c>LOWER()</c>
|
||||
/// lowercases the <i>escape text</i>, giving <c>É</c> — it cannot case-fold the codepoint that
|
||||
/// escape denotes, so a <c>q=é</c> pattern of <c>é</c> never matched and every accented artist
|
||||
/// was silently unsuggestable. Restricting the run to verbatim ASCII removes the escape from the
|
||||
/// comparison entirely. And for a run character <c>c</c>, any element character that
|
||||
/// text escapes non-ASCII, so <c>Édith</c> is on disk as <c>\u00C9dith</c>. SQL <c>LOWER()</c>
|
||||
/// lowercases the <i>escape text</i> — <c>\u00C9</c> becomes <c>\u00c9</c> — it cannot case-fold the
|
||||
/// codepoint that escape denotes. So a <c>q=é</c> prefix encoded to the pattern <c>\u00e9</c>, which
|
||||
/// never matched the stored <c>\u00C9</c>. It failed whenever the query's casing differed from the
|
||||
/// stored casing (three of the nine cases pinned in <c>GetSearchFieldValuesHandlerTests</c>); when
|
||||
/// the casings happened to agree the escape texts lined up and it worked, which is exactly why the
|
||||
/// bug survived review. Restricting the run to verbatim ASCII removes the escape from the comparison
|
||||
/// entirely. And for a run character <c>c</c>, any element character that
|
||||
/// OrdinalIgnoreCase-equals <c>c</c> is itself ASCII — no non-ASCII codepoint in all of Unicode
|
||||
/// OrdinalIgnoreCase-equals a printable ASCII character, which
|
||||
/// <c>SearchFieldValuesPrefilterSupersetTests</c> proves by exhaustive sweep rather than assertion.
|
||||
|
||||
@@ -315,30 +315,28 @@ public class GetSearchFieldValuesHandlerTests
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { "50% Off" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task List_Valued_Walk_Is_Bounded_By_A_Scan_Ceiling_Of_Exactly_20000_Candidate_Rows()
|
||||
{
|
||||
// The bound is on EFFORT, not on the result: the walk pages past non-matching candidates (proved by
|
||||
// Prefilter_Widening_Must_Not_Starve_The_Candidate_Set_Past_The_Row_Bound) but must still stop somewhere,
|
||||
// or a bare-anchor query on a huge library becomes an unbounded scan.
|
||||
//
|
||||
// Pinned in BOTH directions so the constant itself is nailed down: a needle at candidate row 20000 is
|
||||
// found, the same needle at row 20001 is not. Asserting only one side would pass with a ceiling of 3, or
|
||||
// with no ceiling at all.
|
||||
const string needle = "\u00E9clair-the-needle";
|
||||
/// <summary>
|
||||
/// Seeds <paramref name="fillerRows" /> non-matching songs through raw SQL — 20k rows via the change
|
||||
/// tracker is minutes, this is milliseconds.
|
||||
/// </summary>
|
||||
private static Task SeedFiller(TvContext context, int fillerRows) =>
|
||||
context.Database.ExecuteSqlRawAsync(
|
||||
$"""
|
||||
WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < {fillerRows})
|
||||
INSERT INTO SongMetadata (SongId, MetadataKind, Title, Artists, DateAdded, DateUpdated)
|
||||
SELECT 0, 0, 'Filler ' || n, '["zzz-filler"]', '2026-01-01', '2026-01-01' FROM seq
|
||||
""");
|
||||
|
||||
// seeded through raw SQL: 20k rows through the change tracker is minutes, this is milliseconds
|
||||
async Task SeedFiller(TvContext context, int rows) =>
|
||||
await context.Database.ExecuteSqlRawAsync(
|
||||
$"""
|
||||
WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < {rows})
|
||||
INSERT INTO SongMetadata (SongId, MetadataKind, Title, Artists, DateAdded, DateUpdated)
|
||||
SELECT 0, 0, 'Filler ' || n, '["zzz-filler"]', '2026-01-01', '2026-01-01' FROM seq
|
||||
""");
|
||||
[Test]
|
||||
public async Task List_Valued_Walk_Visits_At_Most_20000_Rows_When_Every_Row_Is_A_Candidate()
|
||||
{
|
||||
// The WIDENED case: a non-ASCII prefix collapses the pattern to the bare `%"%` anchor, so every row is
|
||||
// a candidate. Pinned in both directions so the ceiling itself is nailed down — a needle at row 20000 is
|
||||
// reached, the same needle at 20001 is not.
|
||||
const string needle = "\u00E9clair-the-needle";
|
||||
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
// 19999 filler rows + the needle == candidate row 20000, the last one inside the ceiling
|
||||
await SeedFiller(context, 19999);
|
||||
context.SongMetadata.Add(Song("Needle", [needle]));
|
||||
await context.SaveChangesAsync();
|
||||
@@ -348,17 +346,9 @@ public class GetSearchFieldValuesHandlerTests
|
||||
|
||||
var handler = new GetSearchFieldValuesHandler(_db.Factory);
|
||||
|
||||
Option<SearchFieldValuesResponseModel> atCeiling = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", "\u00E9", 50), CancellationToken.None))
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { needle }, "row 20000 is inside the ceiling"));
|
||||
|
||||
atCeiling.IsSome.ShouldBeTrue();
|
||||
atCeiling.IfSome(
|
||||
r => r.Values.ShouldBe(
|
||||
new List<string> { needle },
|
||||
"candidate row 20000 is inside the ceiling and must be reached"));
|
||||
|
||||
// one more filler row pushes the needle to candidate row 20001, past the ceiling
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
SongMetadata existing = await context.SongMetadata.SingleAsync(m => m.Title == "Needle");
|
||||
@@ -371,22 +361,63 @@ public class GetSearchFieldValuesHandlerTests
|
||||
(await context.SongMetadata.CountAsync()).ShouldBe(20001);
|
||||
}
|
||||
|
||||
Option<SearchFieldValuesResponseModel> pastCeiling = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", "\u00E9", 50), CancellationToken.None))
|
||||
.IfSome(
|
||||
r => r.Values.ShouldBeEmpty(
|
||||
"row 20001 is past the ceiling; this false negative is the documented bounded-best-effort "
|
||||
+ "contract, deliberately pinned rather than papered over"));
|
||||
|
||||
pastCeiling.IsSome.ShouldBeTrue();
|
||||
pastCeiling.IfSome(
|
||||
r => r.Values.ShouldBeEmpty("candidate row 20001 is past the ceiling and must not be reached"));
|
||||
// positive control: narrowing the prefix drops the filler from the candidate set, so the ceiling is what
|
||||
// the assertion above is about, not an unreachable value
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", "zzz", 50), CancellationToken.None))
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { "zzz-filler" }));
|
||||
}
|
||||
|
||||
// positive control: narrowing the prefix drops the filler rows from the candidate set entirely, so the
|
||||
// same row is reachable again -- the assertion above is about the ceiling, not an unreachable value
|
||||
Option<SearchFieldValuesResponseModel> narrowed = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "zzz", 50),
|
||||
CancellationToken.None);
|
||||
[Test]
|
||||
public async Task List_Valued_Walk_Cannot_Inspect_Past_The_Bound_When_Nothing_Matches()
|
||||
{
|
||||
// THE case every earlier bound test missed: they all gave the SQL pre-filter something to return.
|
||||
//
|
||||
// Here the pattern is NARROW (an ASCII prefix), so the LIKE matches nothing until the needle. A LIMIT
|
||||
// cannot bound this: to return an empty page the engine must evaluate every eligible row first. The
|
||||
// previous revision therefore let the database walk the entire table and FOUND a needle at row 30000 —
|
||||
// correct answer, unbounded work. The closed keyspace window stops at 20000 rows inspected, so the
|
||||
// needle beyond it is not found, and that is the observable difference.
|
||||
const string needle = "qqq-far-past-the-bound";
|
||||
|
||||
narrowed.IsSome.ShouldBeTrue();
|
||||
narrowed.IfSome(r => r.Values.ShouldBe(new List<string> { "zzz-filler" }));
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
await SeedFiller(context, 29999);
|
||||
context.SongMetadata.Add(Song("Needle", [needle]));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
(await context.SongMetadata.CountAsync()).ShouldBe(30000);
|
||||
}
|
||||
|
||||
var handler = new GetSearchFieldValuesHandler(_db.Factory);
|
||||
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", "qqq", 50), CancellationToken.None))
|
||||
.IfSome(
|
||||
r => r.Values.ShouldBeEmpty(
|
||||
"a no-match walk must stop at the visit ceiling; reaching row 30000 means the bound is on "
|
||||
+ "rows RETURNED rather than rows INSPECTED"));
|
||||
|
||||
// ... while the identical query against a needle inside the bound does find it, so the assertion above
|
||||
// is about the ceiling and not about the narrow pattern failing to match at all
|
||||
await using (InMemoryTvContext smaller = await InMemoryTvContext.CreateAsync())
|
||||
{
|
||||
await using (TvContext context = smaller.CreateContext())
|
||||
{
|
||||
await SeedFiller(context, 19999);
|
||||
context.SongMetadata.Add(Song("Needle", [needle]));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
(await new GetSearchFieldValuesHandler(smaller.Factory).Handle(
|
||||
new GetSearchFieldValues("artist", "qqq", 50),
|
||||
CancellationToken.None))
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { needle }, "row 20000 is inside the ceiling"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -120,29 +120,49 @@ public class SearchFieldValuesPrefilterSupersetTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Candidate_Rows_Are_Keyset_Paged_On_The_Primary_Key_Not_The_Json_Column()
|
||||
public void Candidate_Rows_Are_Read_In_A_Closed_Id_Keyspace_Window()
|
||||
{
|
||||
// Two things at once. ORDER BY rides Id because MySQL sorts TEXT/longtext using only max_sort_length
|
||||
// bytes, so ordering on the JSON column would let long rows sharing a prefix tie arbitrarily. And the
|
||||
// `Id > @AfterId` keyset predicate is what makes the walk RESUMABLE — without it the bound would have to
|
||||
// be a single fixed budget, which is exactly the starvation defect this replaced.
|
||||
string sql = GetSearchFieldValuesHandler.ListValuedSql("Artists");
|
||||
|
||||
// THE upper bound is the whole point. With only `Id > @AfterId` plus a LIMIT, a query that matches
|
||||
// nothing still forces the engine to evaluate every remaining row before it can return an empty page —
|
||||
// so rows RETURNED were bounded while rows INSPECTED were not. Closing the range makes each round trip
|
||||
// a primary-key range scan of known width.
|
||||
sql.ShouldContain("Id > @AfterId");
|
||||
sql.ShouldContain("ORDER BY Id LIMIT @Batch");
|
||||
sql.ShouldContain("Id <= @UpperId");
|
||||
|
||||
// ORDER BY rides Id, not the JSON column: MySQL sorts TEXT using only max_sort_length bytes.
|
||||
sql.ShouldContain("ORDER BY Id");
|
||||
sql.ShouldNotContain("ORDER BY Artists");
|
||||
|
||||
// and no LIMIT — the window caps the row count, and a LIMIT here would only restore the illusion that
|
||||
// it is what does the bounding
|
||||
sql.ShouldNotContain("LIMIT");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void The_Scan_Ceiling_Is_A_Whole_Number_Of_Batches()
|
||||
public void The_Visit_Ceiling_Is_A_Whole_Number_Of_Windows_So_The_Walk_Cannot_Overrun_It()
|
||||
{
|
||||
// The walk trims its last batch to land exactly on the ceiling, so this is not load-bearing for
|
||||
// correctness — but a ceiling that is not a multiple of the batch size means the final round trip
|
||||
// fetches a short page, which the loop would otherwise read as "source exhausted".
|
||||
(GetSearchFieldValuesHandler.ListValuedMaxScannedRows % GetSearchFieldValuesHandler.ListValuedBatchRows)
|
||||
.ShouldBe(0);
|
||||
// The invariant that actually matters is that the ceiling is reachable and never overshot. The walk
|
||||
// clamps its final window (`Math.Min(WindowRows, MaxVisitedRows - visited)`), so a ceiling that is not a
|
||||
// multiple of the window size would still be safe — an earlier version of this test rejected that, which
|
||||
// made it a style preference wearing a correctness costume.
|
||||
GetSearchFieldValuesHandler.ListValuedWindowRows.ShouldBeGreaterThan(0);
|
||||
GetSearchFieldValuesHandler.ListValuedMaxVisitedRows
|
||||
.ShouldBeGreaterThanOrEqualTo(GetSearchFieldValuesHandler.ListValuedWindowRows);
|
||||
|
||||
GetSearchFieldValuesHandler.ListValuedMaxScannedRows
|
||||
.ShouldBeGreaterThan(GetSearchFieldValuesHandler.ListValuedBatchRows);
|
||||
// simulate the walk's own arithmetic and assert it lands exactly on the ceiling, never past it
|
||||
var visited = 0;
|
||||
var windows = 0;
|
||||
while (visited < GetSearchFieldValuesHandler.ListValuedMaxVisitedRows)
|
||||
{
|
||||
visited += Math.Min(
|
||||
GetSearchFieldValuesHandler.ListValuedWindowRows,
|
||||
GetSearchFieldValuesHandler.ListValuedMaxVisitedRows - visited);
|
||||
windows++;
|
||||
windows.ShouldBeLessThan(1000, "the walk must terminate");
|
||||
}
|
||||
|
||||
visited.ShouldBe(GetSearchFieldValuesHandler.ListValuedMaxVisitedRows);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 — this is scoped to the in-memory stages on purpose: a field sourced by a plain EF query is pre-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: SQL narrows on the raw JSON with a `LIKE` pattern built ONLY from the leading run of characters the JSON writer stores verbatim (printable ASCII minus `"&'+<>\`), stopping at the first character it cannot prove — this pre-filter is an optimization that MAY over-match and MUST NEVER under-match, with correctness living in the in-memory exact filter; candidate rows are walked keyset-paged on `Id` (a unique integer key, not the JSON column) and split + exact-filtered in memory, stopping on the first of enough distinct matches, source exhausted, or a 20,000-candidate-row scan ceiling — the bound is on EFFORT, never a fixed row budget, because a fixed budget lets a widened pre-filter starve the candidate set and drop real matches. Ordering across merged sources is best-effort, exact only below the truncation points. | 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 — this is scoped to the in-memory stages on purpose: a field sourced by a plain EF query is pre-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: SQL narrows on the raw JSON with a `LIKE` pattern built ONLY from the leading run of characters the JSON writer stores verbatim (printable ASCII minus `"&'+<>\`), stopping at the first character it cannot prove — this pre-filter is an optimization that MAY over-match and MUST NEVER under-match, with correctness living in the in-memory exact filter; candidate rows are walked in CLOSED `Id` keyspace windows (`Id > @AfterId AND Id <= @AfterId + @Window`, no `LIMIT`) and split + exact-filtered in memory, stopping on the first of enough distinct matches, `MAX(Id)` passed, or a 20,000-row visit ceiling — the bound is on rows the database LOOKS AT, not on rows returned: a fixed `LIMIT` budget lets a widened pre-filter starve the candidate set, and a `LIMIT` alone cannot bound a no-match query, which must evaluate every eligible row before it can return an empty page. Ordering across merged sources is best-effort, exact only below the truncation points. | 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,7 +5,7 @@ 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 — this is scoped to the in-memory stages on purpose: a field sourced by a plain EF query is pre-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: SQL narrows on the raw JSON with a `LIKE` pattern built ONLY from the leading run of characters the JSON writer stores verbatim (printable ASCII minus `"&''+<>\`), stopping at the first character it cannot prove — this pre-filter is an optimization that MAY over-match and MUST NEVER under-match, with correctness living in the in-memory exact filter; candidate rows are walked keyset-paged on `Id` (a unique integer key, not the JSON column) and split + exact-filtered in memory, stopping on the first of enough distinct matches, source exhausted, or a 20,000-candidate-row scan ceiling — the bound is on EFFORT, never a fixed row budget, because a fixed budget lets a widened pre-filter starve the candidate set and drop real matches. Ordering across merged sources is best-effort, exact only below the truncation points.'
|
||||
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 — this is scoped to the in-memory stages on purpose: a field sourced by a plain EF query is pre-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: SQL narrows on the raw JSON with a `LIKE` pattern built ONLY from the leading run of characters the JSON writer stores verbatim (printable ASCII minus `"&''+<>\`), stopping at the first character it cannot prove — this pre-filter is an optimization that MAY over-match and MUST NEVER under-match, with correctness living in the in-memory exact filter; candidate rows are walked in CLOSED `Id` keyspace windows (`Id > @AfterId AND Id <= @AfterId + @Window`, no `LIMIT`) and split + exact-filtered in memory, stopping on the first of enough distinct matches, `MAX(Id)` passed, or a 20,000-row visit ceiling — the bound is on rows the database LOOKS AT, not on rows returned: a fixed `LIMIT` budget lets a widened pre-filter starve the candidate set, and a `LIMIT` alone cannot bound a no-match query, which must evaluate every eligible row before it can return an empty page. Ordering across merged sources is best-effort, exact only below the truncation points.'
|
||||
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, raw JSON LIKE pre-filter, superset never under-match, accented artist unsuggestable, LOWER cannot fold a \u00XX escape, OrdinalIgnoreCase vs InvariantCultureIgnoreCase folding, Accept-Language tr-TR dotless i, ListValuedRowCap, ORDER BY Id not TEXT, max_sort_length, content_rating split, text field allow-list · paths: `ErsatzTV.Application/Search/Queries/GetSearchFieldValuesHandler.cs`, `ErsatzTV/Controllers/Api/SearchController.cs`, `ErsatzTV.Tests/Application/Search/SearchFieldValuesPrefilterSupersetTests.cs`, `ErsatzTV.Tests/Application/Search/GetSearchFieldValuesHandlerTests.cs`, `web/src/api/search.ts` · issues: #578, #434, #176, #668, #669'
|
||||
mechanics: '`GetSearchFieldValuesHandler` (`GetSource`, `GetSongListValuedColumn`, `GetSongListValuedValues`, `ListValuedSql`, `JsonElementPrefixPattern`, `FilterSortTake`); `SearchFieldValuesPrefilterSupersetTests` (the superset proof); api-conventions.md; spa-conventions.md §12'
|
||||
---
|
||||
@@ -42,13 +42,20 @@ of the returned values could see. It JSON-encoded the whole query prefix, reason
|
||||
stored text escapes non-ASCII (`Édith` is on disk as `\u00C9dith`), encoding the prefix the same way
|
||||
would line up. **It does not.** SQL `LOWER()` lowercases the *escape text* — `\u00C9` becomes `\u00c9` —
|
||||
it cannot case-fold the codepoint that escape denotes, so the stored `\u00C9` never folds to `\u00e9`.
|
||||
A `q=é` prefix produced the pattern `\u00e9`, which never matched, the row was discarded before the in-memory filter ever saw it, and **every accented artist
|
||||
was silently unsuggestable** — in a music library, the common case, not an edge case.
|
||||
A `q=é` prefix produced the pattern `\u00e9`, which never matched the stored `\u00C9`, so the row was
|
||||
discarded before the in-memory filter ever saw it. Be precise about the blast radius, because the
|
||||
imprecision is what let it through review: it failed whenever the query's casing differed from the
|
||||
stored casing — **three of the nine cases** now pinned in `GetSearchFieldValuesHandlerTests`
|
||||
(`q=é`/`q=édith` against `"Édith Piaf"`, `q=BJÖRK` against `"Björk"`). When the casings happened to
|
||||
agree the two escape texts lined up and it worked, which is why six of the nine pass the broken
|
||||
revision. Accented artists are the common case in a music library, so a bug that fires on some
|
||||
casings and not others is still a bug worth this much prose.
|
||||
|
||||
The fix is to narrow only on ground that can be proved: the leading run of characters the JSON
|
||||
writer stores **verbatim**, stopping at the first non-ASCII or JSON-escaped character. A query
|
||||
starting with such a character narrows to the bare element-opening anchor `%"%` and leans on the row
|
||||
cap and the in-memory filter. `q=Beyoncé` still narrows on `beyonc`; `q=é` narrows on nothing.
|
||||
starting with such a character narrows to the bare element-opening anchor `%"%`, so the walk's
|
||||
keyspace bound — not the pattern — is what keeps that case bounded, and the in-memory filter is what
|
||||
keeps it correct. `q=Beyoncé` still narrows on `beyonc`; `q=é` narrows on nothing.
|
||||
|
||||
Soundness rests on two facts, both **asserted by exhaustive computation** in
|
||||
`SearchFieldValuesPrefilterSupersetTests` rather than argued:
|
||||
@@ -70,8 +77,10 @@ into `ı`. The old chain used `ToLower()` plus the default *linguistic* `StartsW
|
||||
the same library answer differently per caller. Comparison is now `OrdinalIgnoreCase` and ordering
|
||||
`StringComparer.Ordinal` throughout the in-memory stages, including the shared `FilterSortTake` that
|
||||
`state`, `video_dynamic_range` and `content_rating` also use. That is a deliberate change to shared
|
||||
behaviour: response *sets* are unchanged, response *order* is now ordinal rather than
|
||||
culture-dependent.
|
||||
behaviour, and **not a cosmetic one**: ordering happens before `Take(limit)`, so changing the
|
||||
comparer can change *which* values survive, not merely their order. With `"Zulu"` and `"apple"`, an
|
||||
empty `q` and `limit=1`, linguistic ordering yields `"apple"` and ordinal yields `"Zulu"`. An earlier
|
||||
version of this record claimed the response sets were unchanged; that was false.
|
||||
|
||||
**Scope this claim carefully — it is not endpoint-wide.** A field sourced by a plain EF query runs
|
||||
the database's `LOWER`, `DISTINCT`, `ORDER BY` and `LIMIT` *before* any ordinal code executes, so the
|
||||
@@ -94,36 +103,53 @@ ranks `"Zulu"` first, while the case-insensitive database ordering ranks `"apple
|
||||
not have; do not restore it. (An earlier version of this record used `"Zulu"`/`"Éclair"` as the
|
||||
example, where both orderings pick `"Zulu"` — it demonstrated nothing.)
|
||||
|
||||
## What the bound bounds — and why a fixed row budget was wrong
|
||||
## What the bound bounds — three revisions, three different wrong quantities
|
||||
|
||||
The first two revisions used a single fixed row budget (`LIMIT 1000`) and called it "bounded". It was
|
||||
bounded, and it was also **wrong**, in a way that only shows up in composition with the pre-filter.
|
||||
The pre-filter is deliberately allowed to over-match; a non-ASCII or JSON-escaped prefix makes it
|
||||
collapse to the bare `%"%` anchor, so *every* row becomes a candidate. Under a fixed budget the
|
||||
budget is then spent on rows that cannot match, and real matches behind them are discarded before the
|
||||
in-memory filter sees them. Seed 1,000 songs by `"zzz…"`, put the only `"éclair"` in row 1,001, ask
|
||||
for `album_artist?q=é`, and the endpoint returns `[]`. **"Over-matching is free" is only true when the
|
||||
candidate set is not truncated.** Widening the predicate under a fixed budget starves it — the same
|
||||
false-negative class the pre-filter fix was addressing, moved one stage later.
|
||||
Worth reading in full, because "it has a LIMIT so it is bounded" was wrong three times in a row and
|
||||
each time the code looked obviously fine.
|
||||
|
||||
So the walk is **keyset-paged on `Id`** (`Id > @AfterId … ORDER BY Id LIMIT @Batch`) and continues
|
||||
past non-matching candidates, stopping on the first of: enough distinct exact matches to satisfy
|
||||
`limit`, a short page (source exhausted), or `ListValuedMaxScannedRows = 20000` candidate rows
|
||||
examined, in `ListValuedBatchRows = 2000` batches. Only the ceiling is lossy, and it takes 20,000 rows
|
||||
that already passed the SQL pre-filter before it bites. Paging on the primary key rather than the JSON
|
||||
column also keeps the truncation point well-defined on MySQL, which sorts `TEXT` using only the first
|
||||
`max_sort_length` (default 1024) bytes.
|
||||
**Revision 1 and 2 bounded the RESULT.** A single fixed `LIMIT 1000` on candidate rows. Bounded, and
|
||||
wrong in composition with the pre-filter: the pre-filter is deliberately allowed to over-match, and a
|
||||
non-ASCII or JSON-escaped prefix collapses it to the bare `%"%` anchor, so *every* row becomes a
|
||||
candidate. The budget then gets spent on rows that cannot match while real matches sit behind them.
|
||||
Seed 1,000 songs by `"zzz…"`, put the only `"éclair"` in row 1,001, ask for `album_artist?q=é` —
|
||||
the endpoint returns `[]`. **"Over-matching is free" is only true while the candidate set is not
|
||||
truncated.** Widening the predicate under a fixed budget starves it: the same false-negative class the
|
||||
pre-filter fix was addressing, moved one stage later.
|
||||
|
||||
**The remaining cost is scan ACCESS, not necessarily a full table scan.** `LOWER(col) LIKE '%…'` has a
|
||||
leading wildcard, so no index can be sought and the engine walks rows — but each page stops as soon as
|
||||
it has filled `@Batch`, so a query whose candidates are dense finishes early and only a sparse
|
||||
bare-anchor query walks far. Worst case is bounded at 20,000 candidate rows across at most 10 round
|
||||
trips. The endpoint is authenticated by default, though `Api:RequireKeyForReads=false` makes it
|
||||
anonymous. **Follow-up: a normalized `SongArtist` join table** (the shape `MusicVideoArtist` already
|
||||
has) would make this exact, indexable and seekable, at the cost of a dual-provider schema migration
|
||||
plus data backfill, changes to every scanner write path populating `SongMetadata.Artists`, changes to
|
||||
the Lucene indexer, and two representations of the same fact free to drift. Tracked as
|
||||
**ersatztv#669**; rejected for #578 on blast radius, not on merit.
|
||||
**Revision 3 bounded the CANDIDATES.** Keyset paging (`Id > @AfterId … LIMIT @Batch`), walking past
|
||||
non-matching rows, with a ceiling on candidate rows materialized. That fixed the starvation, and still
|
||||
bounded the wrong quantity: `LIMIT` caps rows *returned*, and **a query with no matches must evaluate
|
||||
every eligible row before it can return an empty page**. An empty first page ended the walk having
|
||||
counted zero against the ceiling, so rows *inspected* remained bounded only by table size. Round trips
|
||||
and materialized rows were bounded; database work was not.
|
||||
|
||||
**Revision 4 bounds the KEYSPACE.** Each round trip closes the `Id` range on both sides —
|
||||
`Id > @AfterId AND Id <= @AfterId + @Window` — which the primary key range-scans. The `LIKE` still
|
||||
decides what comes *back*; it no longer decides how much gets *looked at*. The walk advances by the
|
||||
window, never by what returned (an empty page means "nothing matched in this stretch", not "source
|
||||
exhausted"), and stops on the first of: enough distinct matches for `limit`, `MAX(Id)` passed, or
|
||||
`ListValuedMaxVisitedRows = 20000` keyspace positions visited in `ListValuedWindowRows = 2000`
|
||||
windows. There is deliberately **no `LIMIT` in the SQL** — the window already caps the row count, and
|
||||
a `LIMIT` would only restore the illusion that it is doing the bounding. A single indexed
|
||||
`SELECT MAX(Id)` up front stops the walk from burning windows on empty keyspace.
|
||||
|
||||
So: at most 10 round trips, at most 20,000 rows inspected, whether or not anything matches, for any
|
||||
`q`. Ranging on the primary key rather than the JSON column also keeps the truncation point
|
||||
well-defined on MySQL, which sorts `TEXT` using only the first `max_sort_length` (default 1024) bytes.
|
||||
|
||||
**Two costs are accepted, not solved.** A match beyond the ceiling is not found — 20,000 `"zzz"` rows
|
||||
followed by `"éclair"` at 20,001 returns `[]`, and a test pins exactly that rather than pretending
|
||||
otherwise; it is the documented bounded-best-effort contract at a rarer threshold. And on a heavily
|
||||
fragmented `Id` space (many deletions) a window covers fewer live rows than its width, so the walk
|
||||
reaches less of the table — conservative in the safe direction, lossy in the same best-effort way.
|
||||
The endpoint is authenticated by default, though `Api:RequireKeyForReads=false` makes it anonymous.
|
||||
|
||||
**Follow-up: a normalized `SongArtist` join table** (the shape `MusicVideoArtist` already has) removes
|
||||
all of this — the predicate becomes seekable, so there is nothing to bound. Cost: a dual-provider
|
||||
schema migration plus data backfill, changes to every scanner write path populating
|
||||
`SongMetadata.Artists`, changes to the Lucene indexer, and two representations of the same fact free
|
||||
to drift. Tracked as **ersatztv#669**; rejected for #578 on blast radius, not on merit.
|
||||
|
||||
## `album_artist` 404 → 200 is additive
|
||||
|
||||
|
||||
Reference in New Issue
Block a user