fix(578): a fixed row budget turns an over-matching prefilter into a false negative
BLOCKER 1. The invariant a883e5f0 established — "the pre-filter may over-match, it must never under-match" — is only sound while the candidate set is not truncated. It was truncated. A non-ASCII or JSON-escaped prefix collapses the pattern to the bare `%"%` anchor, so every row becomes a candidate, and `ORDER BY Id LIMIT 1000` then spent the whole budget on rows that could not match. Seed 1000 songs by "zzz", put the only "éclair" in row 1001, ask for album_artist?q=é: a883e5f0 returns [], while 1b78dc9e returned "éclair" because its (separately broken) tighter pattern kept the candidate set small. Neither revision was correct — the old one under-matched at the pattern, the new one under-matched at the cap. Widening a predicate under a fixed budget starves it. So the budget is gone. Candidate rows are now walked keyset-paged on Id (`Id > @AfterId … ORDER BY Id LIMIT @Batch`), continuing past non-matching candidates and stopping on the first of: enough distinct exact matches for `limit`, a short page (source exhausted), or a 20,000-candidate-row ceiling in 2,000-row batches. The bound is on effort; it no longer silently decides the result, and the lossy case needs 20,000 rows that already passed the pre-filter before it bites. BLOCKER 2. The endpoint description and the record's rule claimed ordinal matching/dedup/ordering endpoint-wide. False for EF-backed fields: the database runs LOWER/DISTINCT/ORDER BY/LIMIT before any ordinal code, so `genre?q=é` still misses a stored "Éclair" on SQLite. Both are now scoped to the final in-memory stages, and the underlying gap is referenced as #668 rather than described as fixed. #669 (normalized SongArtist table) is referenced as the follow-up for the scan cost. Accuracy corrections to my own claims, all verified by re-running the mutations: - Only THREE of the nine Unicode cases fail 1b78dc9e (é/édith/BJÖRK — where query and stored casing differ, so the escape texts diverge); the other six pass it. The comment said all nine. They stay as continuity coverage, now labelled as such rather than as regression guards. - Ordering_Is_Best_Effort used "Zulu"/"Éclair", where DB and ordinal orderings BOTH pick "Zulu" — it could not demonstrate the divergence it claimed. Now "Zulu"/"apple", which actually diverges: ordinal ranks "Zulu" first, the DB ranks "apple" first, and limit=1 returns ["apple"]. The record sentence was false and is corrected. - The record printed literal "Édith"/"é" where it needed to show the escape TEXT (Édith, é), contradicting the very explanation it was giving. - Corrected the cost claim: the leading wildcard forces scan ACCESS, but each page stops once it has filled @Batch, so a dense query finishes early — it is not necessarily a full table scan. - The Unicode sweep is labelled a PROOF OBLIGATION: it is revision-independent and passes every revision, which is correct for what it is but must not read as regression coverage. One process note: the new record's frontmatter had a lone apostrophe inside a single-quoted YAML scalar ("SQLite's"). decisions_validate.py's hand parser accepted it; scripts/tests caught it.
This commit is contained in:
@@ -15,16 +15,28 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
private const int MaxLimit = 50;
|
||||
|
||||
/// <summary>
|
||||
/// Row cap for the list-valued (JSON-array) columns on <c>SongMetadata</c>. The SQL pre-filter over the
|
||||
/// raw JSON is a deliberate superset (a matching row is fetched whole, including its non-matching
|
||||
/// elements), so the number of rows it can return has to be bounded independently of <c>limit</c> —
|
||||
/// otherwise an empty <c>q</c> degenerates into materializing the entire table. The cap is applied on
|
||||
/// <c>ORDER BY Id</c>, which is a unique integer primary key on both providers: unlike ordering on the
|
||||
/// JSON column itself, that makes the truncation point genuinely deterministic (MySQL sorts <c>TEXT</c>
|
||||
/// using only the first <c>max_sort_length</c> bytes, so long JSON rows sharing a prefix would tie
|
||||
/// arbitrarily) and lets the engine walk the primary key instead of sorting the whole matching set.
|
||||
/// 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.
|
||||
/// <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.
|
||||
/// </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.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal const int ListValuedRowCap = 1000;
|
||||
internal const int ListValuedBatchRows = 2000;
|
||||
|
||||
/// <inheritdoc cref="ListValuedBatchRows" />
|
||||
internal const int ListValuedMaxScannedRows = 20000;
|
||||
|
||||
/// <summary>
|
||||
/// Escape character for the raw-JSON <c>LIKE</c> pre-filter. Deliberately NOT a backslash: the stored
|
||||
@@ -103,7 +115,7 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
|
||||
if (listColumn is not null)
|
||||
{
|
||||
values.AddRange(await GetSongListValuedValues(dbContext, listColumn, query, cancellationToken));
|
||||
values.AddRange(await GetSongListValuedValues(dbContext, listColumn, query, limit, cancellationToken));
|
||||
}
|
||||
|
||||
// ORDERING IS BEST-EFFORT, NOT EXACT. Each source truncates using its own ordering — the EF source by the
|
||||
@@ -164,67 +176,102 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
|
||||
/// collections at all — so there is no server-side <c>SELECT DISTINCT</c> over the elements.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Instead: pre-filter on the raw JSON text in SQL (a superset — a row is matched, not an element,
|
||||
/// so its other elements come along), cap the rows by primary key, then split and exact-filter in
|
||||
/// memory. Correctness lives in the in-memory filter; the SQL pattern is only an optimization and is
|
||||
/// allowed to over-match but never to under-match. When the library has more matching rows than
|
||||
/// <see cref="ListValuedRowCap" /> the suggestion list for these fields is the lowest-id prefix of
|
||||
/// the matches rather than the complete set.
|
||||
/// So the rows are walked in primary-key order, keyset-paged, and split + exact-filtered in memory.
|
||||
/// The SQL <c>LIKE</c> is only a narrowing hint: correctness lives entirely in the in-memory filter,
|
||||
/// and the walk continues past non-matching candidates rather than letting a row budget decide the
|
||||
/// answer. See <see cref="ListValuedBatchRows" /> for why a single fixed budget was wrong.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
private static async Task<List<string>> GetSongListValuedValues(
|
||||
TvContext dbContext,
|
||||
string column,
|
||||
string query,
|
||||
int limit,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
IEnumerable<string> rows = await dbContext.Connection.QueryAsync<string>(
|
||||
new CommandDefinition(
|
||||
ListValuedSql(column),
|
||||
new { Pattern = JsonElementPrefixPattern(query), Cap = ListValuedRowCap },
|
||||
cancellationToken: cancellationToken));
|
||||
string sql = ListValuedSql(column);
|
||||
string pattern = JsonElementPrefixPattern(query);
|
||||
|
||||
var values = new List<string>();
|
||||
foreach (string row in rows)
|
||||
var distinct = new System.Collections.Generic.HashSet<string>(StringComparer.Ordinal);
|
||||
var afterId = 0;
|
||||
var scanned = 0;
|
||||
|
||||
while (scanned < ListValuedMaxScannedRows && distinct.Count < limit)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(row))
|
||||
int batch = Math.Min(ListValuedBatchRows, ListValuedMaxScannedRows - scanned);
|
||||
|
||||
List<ListValuedRow> rows = (await dbContext.Connection.QueryAsync<ListValuedRow>(
|
||||
new CommandDefinition(
|
||||
sql,
|
||||
new { Pattern = pattern, AfterId = afterId, Batch = batch },
|
||||
cancellationToken: cancellationToken))).AsList();
|
||||
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
|
||||
string[] elements;
|
||||
try
|
||||
{
|
||||
elements = JsonSerializer.Deserialize<string[]>(row);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
scanned += rows.Count;
|
||||
afterId = rows[^1].Id;
|
||||
|
||||
foreach (string element in elements ?? [])
|
||||
foreach (ListValuedRow row in rows)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(element) && element.StartsWith(query, StringComparison.OrdinalIgnoreCase))
|
||||
foreach (string element in ParseElements(row.Payload))
|
||||
{
|
||||
values.Add(element);
|
||||
if (element.StartsWith(query, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
distinct.Add(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.Count < batch)
|
||||
{
|
||||
// short page: the source is exhausted, not merely bounded
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
return distinct.ToList();
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ParseElements(string payload)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payload))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return (JsonSerializer.Deserialize<string[]>(payload) ?? []).Where(e => !string.IsNullOrEmpty(e));
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bounded pre-filter query. <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. The cap rides <c>ORDER BY Id</c> — a unique integer key both providers
|
||||
/// can walk — rather than the JSON column, so the truncation point is well-defined and no full sort of
|
||||
/// the matching set is required.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static string ListValuedSql(string column) =>
|
||||
$"SELECT {column} FROM SongMetadata WHERE {column} IS NOT NULL " +
|
||||
$"SELECT Id, {column} AS Payload FROM SongMetadata WHERE {column} IS NOT NULL " +
|
||||
"AND Id > @AfterId " +
|
||||
$"AND LOWER({column}) LIKE @Pattern ESCAPE '{LikeEscapeChar}' " +
|
||||
"ORDER BY Id LIMIT @Cap";
|
||||
"ORDER BY Id LIMIT @Batch";
|
||||
|
||||
private sealed class ListValuedRow
|
||||
{
|
||||
public int Id { get; init; }
|
||||
|
||||
public string Payload { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the raw-JSON <c>LIKE</c> pattern used to narrow the rows fetched for a list-valued column.
|
||||
|
||||
@@ -316,80 +316,77 @@ public class GetSearchFieldValuesHandlerTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task List_Valued_Source_Row_Cap_Is_Exactly_1000_Rows()
|
||||
public async Task List_Valued_Walk_Is_Bounded_By_A_Scan_Ceiling_Of_Exactly_20000_Candidate_Rows()
|
||||
{
|
||||
// Pins the cap value in BOTH directions. Asserting only that an over-cap row is dropped would also pass
|
||||
// with a cap of 3, or with the handler wrongly using `limit` as the row cap; asserting only that an
|
||||
// under-cap row survives would pass with no cap at all. The marker row's element sorts first in the
|
||||
// output, so an unbounded implementation cannot help but return it.
|
||||
const string marker = "aaa-the-marker-row";
|
||||
// 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";
|
||||
|
||||
// rows are capped by ascending Id, and Id is assigned in insertion order
|
||||
async Task SeedFillerThenMarker(int fillerRows)
|
||||
// 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
|
||||
""");
|
||||
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
await using TvContext context = _db.CreateContext();
|
||||
for (var i = 0; i < fillerRows; i++)
|
||||
{
|
||||
context.SongMetadata.Add(Song($"Song {i}", [$"b{i:D4}"]));
|
||||
}
|
||||
|
||||
context.SongMetadata.Add(Song("Marker", [marker]));
|
||||
// 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();
|
||||
|
||||
(await context.SongMetadata.CountAsync()).ShouldBe(20000);
|
||||
}
|
||||
|
||||
var handler = new GetSearchFieldValuesHandler(_db.Factory);
|
||||
|
||||
// 999 filler rows -> the marker is row 1000 -> inside a cap of 1000
|
||||
await SeedFillerThenMarker(999);
|
||||
|
||||
Option<SearchFieldValuesResponseModel> atCap = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", string.Empty, 3),
|
||||
Option<SearchFieldValuesResponseModel> atCeiling = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
atCap.IsSome.ShouldBeTrue();
|
||||
atCap.IfSome(
|
||||
atCeiling.IsSome.ShouldBeTrue();
|
||||
atCeiling.IfSome(
|
||||
r => r.Values.ShouldBe(
|
||||
new List<string> { marker, "b0000", "b0001" },
|
||||
"the 1000th row must still be read - a cap below 1000 would drop it"));
|
||||
new List<string> { needle },
|
||||
"candidate row 20000 is inside the ceiling and must be reached"));
|
||||
|
||||
// one more filler row pushes the marker to row 1001 -> outside a cap of 1000
|
||||
// one more filler row pushes the needle to candidate row 20001, past the ceiling
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
context.SongMetadata.Add(Song("Extra", ["b9999"]));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
// move the marker to the end so it sits at Id 1002, past the cap
|
||||
SongMetadata existing = await context.SongMetadata.SingleAsync(m => m.Title == "Marker");
|
||||
SongMetadata existing = await context.SongMetadata.SingleAsync(m => m.Title == "Needle");
|
||||
context.SongMetadata.Remove(existing);
|
||||
await SeedFiller(context, 1);
|
||||
await context.SaveChangesAsync();
|
||||
context.SongMetadata.Add(Song("Marker", [marker]));
|
||||
context.SongMetadata.Add(Song("Needle", [needle]));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
(await context.SongMetadata.CountAsync()).ShouldBe(1001);
|
||||
(await context.SongMetadata.CountAsync()).ShouldBe(20001);
|
||||
}
|
||||
|
||||
Option<SearchFieldValuesResponseModel> pastCap = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", string.Empty, 3),
|
||||
Option<SearchFieldValuesResponseModel> pastCeiling = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
pastCap.IsSome.ShouldBeTrue();
|
||||
pastCap.IfSome(
|
||||
r => r.Values.ShouldNotContain(
|
||||
marker,
|
||||
"the 1001st row must not be read - an unbounded query would return it first"));
|
||||
pastCap.IfSome(r => r.Values.ShouldBe(new List<string> { "b0000", "b0001", "b0002" }));
|
||||
pastCeiling.IsSome.ShouldBeTrue();
|
||||
pastCeiling.IfSome(
|
||||
r => r.Values.ShouldBeEmpty("candidate row 20001 is past the ceiling and must not be reached"));
|
||||
|
||||
// positive control: the same row IS reachable once the pre-filter narrows the candidates below the cap,
|
||||
// so the assertion above cannot be passing because the value is unreachable for an unrelated reason
|
||||
// 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", "aaa", 50),
|
||||
new GetSearchFieldValues("artist", "zzz", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
narrowed.IsSome.ShouldBeTrue();
|
||||
narrowed.IfSome(r => r.Values.ShouldBe(new List<string> { marker }));
|
||||
narrowed.IfSome(r => r.Values.ShouldBe(new List<string> { "zzz-filler" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -433,10 +430,17 @@ public class GetSearchFieldValuesHandlerTests
|
||||
[TestCase("\u00D6", "\u00D6zdemir")]
|
||||
public async Task Prefilter_Never_Under_Matches_A_NonAscii_Value(string query, string stored)
|
||||
{
|
||||
// The SQL pre-filter narrows on raw JSON, where non-ASCII is stored escaped (\u00C9). Any narrowing
|
||||
// that includes an escaped character under-matches, because SQL LOWER() folds the escape TEXT and not
|
||||
// the codepoint — every one of these cases returned EMPTY before the pattern builder was restricted to
|
||||
// the leading verbatim-ASCII run. Accented artists are the common case in a music library, not an edge.
|
||||
// The SQL pre-filter narrows on raw JSON, where non-ASCII is stored escaped (\u00C9). A narrowing run
|
||||
// that includes an escaped character can under-match, because SQL LOWER() folds the escape TEXT and not
|
||||
// the codepoint it denotes.
|
||||
//
|
||||
// Be precise about what these cases guard: THREE of the nine fail against 1b78dc9e (the JSON-encode-the-
|
||||
// whole-prefix revision) — ("é", "Édith Piaf"), ("édith", "Édith Piaf") and ("BJÖRK", "Björk") — because
|
||||
// those are the ones where the query and stored casings differ, so the lowercased escape text (\u00e9)
|
||||
// and the stored escape text (\u00C9) diverge. The other SIX pass that revision: when the query casing
|
||||
// already matches the stored casing the escape texts happen to line up. They are kept as continuity
|
||||
// coverage of the ASCII-run narrowing, NOT as regression guards. Accented artists are the common case in
|
||||
// a music library, so both groups are worth pinning.
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
context.SongMetadata.AddRange(
|
||||
@@ -532,25 +536,80 @@ public class GetSearchFieldValuesHandlerTests
|
||||
public async Task Ordering_Is_Best_Effort_When_A_Source_Truncates()
|
||||
{
|
||||
// Documents the acknowledged imprecision rather than claiming exactness the code does not have. The EF
|
||||
// source truncates by the DATABASE collation (SQLite's is ASCII-only), which is not the ordinal ordering
|
||||
// the merge then applies — so a value the database ranked outside its first `limit` never reaches the
|
||||
// merge, even if the merge would have ranked it first.
|
||||
// source truncates by the DATABASE collation, which is NOT the ordinal ordering the merge then applies —
|
||||
// so a value the database ranked outside its first `limit` never reaches the merge, even if the merge
|
||||
// would have ranked it first.
|
||||
//
|
||||
// "Zulu" vs "apple" is the pair that actually diverges: ordinal puts every ASCII uppercase letter before
|
||||
// every lowercase one, so ordinal ranks "Zulu" first, while a case-insensitive database ordering ranks
|
||||
// "apple" first. (An earlier version used "Zulu"/"Éclair", where BOTH orderings pick "Zulu" — it could
|
||||
// not have told the two apart, and the divergence it claimed to show did not exist.)
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
context.ArtistMetadata.Add(Artist("Zulu"));
|
||||
context.ArtistMetadata.Add(Artist("\u00C9clair"));
|
||||
context.ArtistMetadata.Add(Artist("apple"));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var handler = new GetSearchFieldValuesHandler(_db.Factory);
|
||||
|
||||
// with room for both, the ordinal merge ranks "Zulu" (ASCII) before "\u00C9clair" (non-ASCII)
|
||||
// with room for both, the ordinal merge ranks "Zulu" first
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", string.Empty, 50), CancellationToken.None))
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { "Zulu", "\u00C9clair" }));
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { "Zulu", "apple" }));
|
||||
|
||||
// with limit=1 the database picks the survivor by ITS collation, and the merge only sees that one
|
||||
// with limit=1 the database picks the survivor by ITS ordering, and the merge only ever sees that one
|
||||
(await handler.Handle(new GetSearchFieldValues("artist", string.Empty, 1), CancellationToken.None))
|
||||
.IfSome(r => r.Values.Count.ShouldBe(1));
|
||||
.IfSome(r => r.Values.ShouldBe(new List<string> { "apple" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Prefilter_Widening_Must_Not_Starve_The_Candidate_Set_Past_The_Row_Bound()
|
||||
{
|
||||
// BLOCKER-1 REGRESSION (fails a883e5f0). A non-ASCII prefix narrows to the bare anchor `%"%`, so EVERY
|
||||
// row qualifies. Under a fixed 1000-row budget the 1001st row -- the only exact match -- was discarded
|
||||
// before the in-memory filter ever saw it, and the endpoint returned []. "Over-matching is free" only
|
||||
// holds when the candidate set is not truncated; with a fixed cap, widening the predicate STARVES it.
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
context.SongMetadata.Add(Song($"Filler {i}", ["zzz-filler"], ["zzz-filler-album"]));
|
||||
}
|
||||
|
||||
context.SongMetadata.Add(Song("Needle", ["\u00E9clair"], ["\u00E9clair"]));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var handler = new GetSearchFieldValuesHandler(_db.Factory);
|
||||
|
||||
Option<SearchFieldValuesResponseModel> albumArtist = await handler.Handle(
|
||||
new GetSearchFieldValues("album_artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
albumArtist.IsSome.ShouldBeTrue();
|
||||
albumArtist.IfSome(r => r.Values.ShouldBe(new List<string> { "\u00E9clair" }));
|
||||
|
||||
// same starvation shape on the merged `artist` field
|
||||
Option<SearchFieldValuesResponseModel> artist = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "\u00E9", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
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
|
||||
await using (TvContext context = _db.CreateContext())
|
||||
{
|
||||
context.SongMetadata.Add(Song("Ampersand", ["&Me"]));
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
Option<SearchFieldValuesResponseModel> escapedPrefix = await handler.Handle(
|
||||
new GetSearchFieldValues("artist", "&M", 50),
|
||||
CancellationToken.None);
|
||||
|
||||
escapedPrefix.IsSome.ShouldBeTrue();
|
||||
escapedPrefix.IfSome(r => r.Values.ShouldBe(new List<string> { "&Me" }));
|
||||
}
|
||||
|
||||
private static ArtistMetadata Artist(string title) => new()
|
||||
|
||||
@@ -30,6 +30,13 @@ public class SearchFieldValuesPrefilterSupersetTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PROOF OBLIGATION, not regression coverage. This is revision-independent — it asserts a property of
|
||||
/// .NET's ordinal case folding and passes against every revision of the handler, including the ones with
|
||||
/// the under-matching pattern builder. It is here because the superset argument DEPENDS on it: if a
|
||||
/// future runtime changed this, the ASCII narrowing would start under-matching with nothing else to
|
||||
/// catch it.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void No_NonAscii_Codepoint_OrdinalIgnoreCase_Equals_A_Printable_Ascii_Character()
|
||||
{
|
||||
@@ -63,6 +70,10 @@ public class SearchFieldValuesPrefilterSupersetTests
|
||||
offenders.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PROOF OBLIGATION plus one regression assertion. The escaped-set half is revision-independent (it
|
||||
/// pins the encoder); the pattern-builder half below fails against 1b78dc9e.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void The_Json_Writer_Escapes_Exactly_The_Ascii_Characters_The_Pattern_Builder_Refuses_To_Narrow_On()
|
||||
{
|
||||
@@ -109,14 +120,29 @@ public class SearchFieldValuesPrefilterSupersetTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Row_Cap_Is_Applied_On_The_Primary_Key_Not_The_Json_Column()
|
||||
public void Candidate_Rows_Are_Keyset_Paged_On_The_Primary_Key_Not_The_Json_Column()
|
||||
{
|
||||
// MySQL sorts TEXT/longtext using only max_sort_length bytes, so ordering on the JSON column would let
|
||||
// rows sharing a long prefix tie arbitrarily and the surviving 1000 would be unspecified. Id is a unique
|
||||
// integer key on both providers.
|
||||
// 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");
|
||||
|
||||
sql.ShouldContain("ORDER BY Id LIMIT @Cap");
|
||||
sql.ShouldContain("Id > @AfterId");
|
||||
sql.ShouldContain("ORDER BY Id LIMIT @Batch");
|
||||
sql.ShouldNotContain("ORDER BY Artists");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void The_Scan_Ceiling_Is_A_Whole_Number_Of_Batches()
|
||||
{
|
||||
// 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);
|
||||
|
||||
GetSearchFieldValuesHandler.ListValuedMaxScannedRows
|
||||
.ShouldBeGreaterThan(GetSearchFieldValuesHandler.ListValuedBatchRows);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,9 +205,11 @@ public class SearchController(IMediator mediator) : ControllerBase
|
||||
"Returns distinct whole values from the database for the given text field, filtered by an " +
|
||||
"optional case-insensitive prefix. Powers the visual rule builder's facet-value typeahead. " +
|
||||
"404 when the field is unknown, is not a text field, or is a text field with no distinct-value " +
|
||||
"source. Matching, dedup and ordering are ordinal, not culture-dependent. The list-valued music " +
|
||||
"fields (artist, album_artist) are bounded best-effort: on a very large library they return a " +
|
||||
"bounded subset of the matches rather than every match.")]
|
||||
"source. The final filter, dedup and ordering applied to the response are ordinal and not " +
|
||||
"culture-dependent; note that fields sourced by a plain database query are additionally " +
|
||||
"pre-filtered by the database collation first, which on SQLite is ASCII-only. The list-valued " +
|
||||
"music fields (artist, album_artist) are bounded best-effort: on a very large library they may " +
|
||||
"return a bounded subset of the matches rather than every match.")]
|
||||
[EndpointGroupName("general")]
|
||||
[ProducesResponseType(typeof(SearchFieldValuesResponseModel), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
|
||||
|
||||
@@ -18063,7 +18063,7 @@
|
||||
"Search"
|
||||
],
|
||||
"summary": "List distinct database values for a text search field",
|
||||
"description": "Returns distinct whole values from the database for the given text field, filtered by an optional case-insensitive prefix. Powers the visual rule builder's facet-value typeahead. 404 when the field is unknown, is not a text field, or is a text field with no distinct-value source. Matching, dedup and ordering are ordinal, not culture-dependent. The list-valued music fields (artist, album_artist) are bounded best-effort: on a very large library they return a bounded subset of the matches rather than every match.",
|
||||
"description": "Returns distinct whole values from the database for the given text field, filtered by an optional case-insensitive prefix. Powers the visual rule builder's facet-value typeahead. 404 when the field is unknown, is not a text field, or is a text field with no distinct-value source. The final filter, dedup and ordering applied to the response are ordinal and not culture-dependent; note that fields sourced by a plain database query are additionally pre-filtered by the database collation first, which on SQLite is ASCII-only. The list-valued music fields (artist, album_artist) are bounded best-effort: on a very large library they may return a bounded subset of the matches rather than every match.",
|
||||
"operationId": "GetSearchFieldValues",
|
||||
"parameters": [
|
||||
{
|
||||
|
||||
+22
-10
@@ -457,17 +457,29 @@ or partly) by `SongMetadata.Artists`/`AlbumArtists`, which EF maps as **primitiv
|
||||
JSON array per row in a single column, with no server-side projection on either provider. `album_artist`
|
||||
therefore no longer 404s, and `artist` now also covers free-text music-video (`MusicVideoArtist`) and
|
||||
song credits, not only entity artists. For these fields the handler narrows on the raw JSON in SQL and
|
||||
caps the rows it reads, so on a very large library the response is a bounded subset of the matches rather
|
||||
than every match — say so in the `[EndpointDescription]` of any endpoint that adopts this shape.
|
||||
walks candidate rows keyset-paged on the primary key, so on a very large library the response may be a
|
||||
bounded subset of the matches — say so in the `[EndpointDescription]` of any endpoint that adopts this shape.
|
||||
|
||||
Two rules generalize beyond this endpoint. **A SQL pre-filter layered under an in-memory exact filter may
|
||||
over-match but must NEVER under-match** — an under-match is a silent false negative that no assertion over
|
||||
the returned values can see, so prove the superset (ours is proved by an exhaustive Unicode sweep, not by
|
||||
argument) rather than eyeballing it. And **prefix matching, dedup and ordering on any `/api/*` read must be
|
||||
ordinal, never current-culture**: `UseRequestLocalization` honours `Accept-Language`, so `ToLower()` and the
|
||||
default linguistic `StartsWith(string)` let a caller change the result by changing a header. Full rationale,
|
||||
the rejected normalized-side-table alternative, the accepted scan cost and the dual-provider `LIKE`/`LOWER`
|
||||
rules: `api.search-field-values-sources` (which supersedes `api.search-field-values`).
|
||||
Three rules generalize beyond this endpoint.
|
||||
|
||||
1. **A SQL pre-filter layered under an in-memory exact filter may over-match but must NEVER under-match.**
|
||||
An under-match is a silent false negative that no assertion over the returned values can see, so prove
|
||||
the superset (ours is proved by an exhaustive Unicode sweep) rather than eyeballing it.
|
||||
2. **That licence to over-match is void the moment the candidate set is truncated by a fixed row budget.**
|
||||
Widening the predicate then starves the budget with rows that cannot match and drops real matches sitting
|
||||
behind them — the same false negative, one stage later. Bound the WORK (page with a keyset cursor until you
|
||||
have enough matches, the source is exhausted, or a scan ceiling is hit), never the candidate rows with a
|
||||
single `LIMIT` whose survivors silently become the answer. Both revisions of this endpoint got this wrong
|
||||
in opposite directions before it was written down.
|
||||
3. **Prefix matching, dedup and ordering must be ordinal, not current-culture** (`OrdinalIgnoreCase`,
|
||||
`StringComparer.Ordinal`): `UseRequestLocalization` honours `Accept-Language`, so `ToLower()` and the
|
||||
default linguistic `StartsWith(string)` let a caller change the result by changing a header. **Scope the
|
||||
claim to the stage that actually holds it** — a value set that a database `LOWER`/`DISTINCT`/`ORDER BY`/
|
||||
`LIMIT` already filtered and truncated is not ordinal no matter what runs after it, and saying otherwise in
|
||||
an `[EndpointDescription]` publishes a false contract (ersatztv#668).
|
||||
|
||||
Full rationale, the rejected normalized-side-table alternative (ersatztv#669), the accepted scan cost and the
|
||||
dual-provider `LIKE`/`LOWER` rules: `api.search-field-values-sources` (supersedes `api.search-field-values`).
|
||||
|
||||
**Param + DTO expansion (#293, cap `search/all-items`)**: no new endpoint — `GET /api/v1/search/all-items`
|
||||
gained two **optional** query params (`pageSize` default 500, clamped 1–1000 via the §1 Logs `Math.Clamp`
|
||||
|
||||
@@ -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). Prefix matching, dedup and ordering are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled. 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; the rows are capped at 1000 on `ORDER BY Id` (a unique integer key, not the JSON column) and then split, filtered, deduped, sorted and `limit`ed in memory. 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 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-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). Prefix matching, dedup and ordering are ORDINAL (`OrdinalIgnoreCase` / `StringComparer.Ordinal`), never current-culture, because `UseRequestLocalization` makes the culture caller-controlled. 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; the rows are capped at 1000 on `ORDER BY Id` (a unique integer key, not the JSON column) and then split, filtered, deduped, sorted and `limit`ed in memory. 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'
|
||||
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.'
|
||||
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'
|
||||
---
|
||||
|
||||
@@ -39,10 +39,10 @@ need no lookup; text fields need a live one; the source is the database and neve
|
||||
|
||||
This is the load-bearing invariant, and the first implementation got it wrong in a way that no test
|
||||
of the returned values could see. It JSON-encoded the whole query prefix, reasoning that since the
|
||||
stored text escapes non-ASCII (`Édith` is on disk as `Édith`), encoding the prefix the same way
|
||||
would line up. **It does not.** SQL `LOWER()` lowercases the *escape text* — `É` — it cannot
|
||||
case-fold the codepoint that escape denotes. So `q=é` produced a pattern of `é` that never
|
||||
matched, the row was discarded before the in-memory filter ever saw it, and **every accented artist
|
||||
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.
|
||||
|
||||
The fix is to narrow only on ground that can be proved: the leading run of characters the JSON
|
||||
@@ -68,38 +68,62 @@ Soundness rests on two facts, both **asserted by exhaustive computation** in
|
||||
`UseRequestLocalization` honours `Accept-Language`, so a caller can select `tr-TR` and turn `q=I`
|
||||
into `ı`. The old chain used `ToLower()` plus the default *linguistic* `StartsWith(string)`, making
|
||||
the same library answer differently per caller. Comparison is now `OrdinalIgnoreCase` and ordering
|
||||
`StringComparer.Ordinal` throughout, 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.
|
||||
`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.
|
||||
|
||||
**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
|
||||
database has already decided which values survive. Store a genre `"Éclair"` on SQLite and ask for
|
||||
`genre?q=é`: SQLite's ASCII-only `LOWER()` drops it before the ordinal in-memory filter ever runs, and
|
||||
a case-insensitive collation's `DISTINCT` can likewise collapse values ordinal dedup would have kept.
|
||||
The endpoint description and this record's `rule:` therefore say "the final filter, dedup and
|
||||
ordering", not "matching is ordinal". Closing that gap means filtering those tables client-side and is
|
||||
tracked separately as **ersatztv#668** — do not describe it as fixed here.
|
||||
|
||||
## Ordering is best-effort, and the code says so
|
||||
|
||||
Merging sources does **not** yield the exact first `limit` of the union. Each source truncates using
|
||||
its own ordering — the EF source by the database collation (SQLite's is ASCII-only), the list source
|
||||
by primary key — and neither is the ordinal ordering the merge applies. With `"Zulu"` and `"Éclair"`
|
||||
and `limit=1`, the EF source keeps `"Zulu"` and the merge never sees `"Éclair"`, which it would have
|
||||
ranked first. Below the truncation points — the normal typeahead case — the result is exact. An
|
||||
earlier comment claimed exactness the code does not have; do not restore it.
|
||||
its own ordering — the EF source by the database collation, the list source by primary key — and
|
||||
neither is the ordinal ordering the merge applies. The pair that actually demonstrates it is `"Zulu"`
|
||||
and `"apple"`: ordinal puts every ASCII uppercase letter before every lowercase one, so the merge
|
||||
ranks `"Zulu"` first, while the case-insensitive database ordering ranks `"apple"` first — at
|
||||
`limit=1` the response is `["apple"]`, not the ordinally-first `"Zulu"`. Below the truncation points
|
||||
— the normal typeahead case — the result is exact. An earlier comment claimed exactness the code does
|
||||
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 row cap does and does not bound
|
||||
## What the bound bounds — and why a fixed row budget was wrong
|
||||
|
||||
`ListValuedRowCap = 1000` bounds **rows fetched**, not values returned, because the pre-filter
|
||||
matches rows whole. The cap rides `ORDER BY Id` — a unique integer primary key both providers can
|
||||
walk — rather than the JSON column: ordering on `TEXT` would not be deterministic on MySQL, which
|
||||
sorts using only the first `max_sort_length` (default 1024) bytes, so long rows sharing a prefix
|
||||
would tie arbitrarily; and it avoids sorting the whole matching set.
|
||||
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.
|
||||
|
||||
**It does not bound database work, and that is a known cost.** `LOWER(col) LIKE '%…'` has a leading
|
||||
wildcard, so no index can be sought and every `SongMetadata` row is scanned before the cap applies.
|
||||
An empty `q` matches nearly every row. Every `artist` request now scans the song table's JSON column
|
||||
in addition to its previous work, once per debounced keystroke; the endpoint is authenticated by
|
||||
default but `Api:RequireKeyForReads=false` makes it anonymous. Accepted for now because the scan is
|
||||
bounded in *memory* and the affected table is one of the smaller ones, and because the alternative is
|
||||
the migration below. **Follow-up candidate: 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. Rejected for #578 on blast radius, not on merit.
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
## `album_artist` 404 → 200 is additive
|
||||
|
||||
@@ -113,4 +137,6 @@ any, so no `/api/v2`.
|
||||
The **EF-sourced** fields (`genre`, `studio`, `artist`'s entity half, …) still prefix-match through
|
||||
SQL `LOWER()`, which on SQLite is ASCII-only — so `q=é` does not match a stored `Édith` for those
|
||||
fields either. That predates #578 and is unchanged by it; fixing it would mean filtering those tables
|
||||
client-side. Noted here so the next reader does not mistake the list-valued fix for a global one.
|
||||
client-side. Tracked as **ersatztv#668**. Noted here so the next reader does not mistake the
|
||||
list-valued fix for a global one, and so the scoped ordinal wording above is not "tidied" into a
|
||||
broader claim.
|
||||
|
||||
Reference in New Issue
Block a user