feat(578): artist typeahead covers music-video and song credits; album_artist stops 404ing

`GET /api/v1/search/fields/{name}/values` sourced `artist` from `ArtistMetadata.Title` only —
entity artists — so the free-text credits that `LuceneSearchIndex` also writes to the `artist`
field (`MusicVideoArtist.Name`, `SongMetadata.Artists`) produced no suggestions, and
`album_artist` 404'd outright.

`MusicVideoArtist` turned out to be a real entity table, so it just joins the existing server-side
pipeline as a `Concat` — one bounded `UNION ALL` + `LOWER(...) LIKE ... LIMIT` on both providers.

`SongMetadata.Artists`/`AlbumArtists` are the hard case: EF 9 maps them as primitive collections
(one JSON array per row in a single column), and neither provider can project the elements
server-side — SQLite needs the SQL APPLY operator it lacks, Pomelo MySQL 9.0.0 has no
primitive-collection support at all. Both failures are now pinned by a test, so a provider upgrade
that fixes them shows up as a red rather than as a stale workaround. For those columns the handler
pre-filters on the raw JSON (`LOWER(col) LIKE '%"<encoded-prefix>%' ESCAPE '/'` — a deliberate
superset, since it matches a row and not an element), caps the rows at 1000 with an `ORDER BY` that
makes the truncation deterministic, then splits and exact-filters in memory.

Provider portability is by construction rather than by trusting `LIKE`: the prefix is JSON-encoded
before matching (which is how it is stored, and which makes the pattern pure ASCII, so SQLite's
ASCII-only `lower()` and MySQL's Unicode-aware `LOWER()` agree) and lowercased in C#, so the match
is correct under a case-sensitive MySQL collation as well as a case-insensitive one. The escape
character is `/`, never `\`: `ESCAPE '\'` is not a portable SQL literal.

An empty `q` stays supported for these fields — the row cap already bounds it, and a non-empty-`q`
carve-out would make one group of fields behave differently for the same client code.

Docs: new `api.search-field-values-list-columns` record (additive sibling — the base record's rule
still reads true; only its body's "intentionally-uncovered gap" claim was stale), plus
`api-conventions.md`, `spa-conventions.md` §12 and the regenerated `v1.json`.

Decisions-Edit: yes
This commit is contained in:
2026-07-27 03:10:35 +02:00
parent 8de02d5bde
commit cd6f36185c
11 changed files with 603 additions and 20 deletions
@@ -1,3 +1,6 @@
using System.Text;
using System.Text.Json;
using Dapper;
using ErsatzTV.Core.Api.Search;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
@@ -11,6 +14,24 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
private const int DefaultLimit = 50;
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. Combined with the
/// <c>ORDER BY</c> in <see cref="ListValuedSql" />, the truncation point is deterministic rather than
/// whatever the storage engine happened to emit first.
/// </summary>
private const int ListValuedRowCap = 1000;
/// <summary>
/// Escape character for the raw-JSON <c>LIKE</c> pre-filter. Deliberately NOT a backslash: the stored
/// JSON is full of backslashes (<c>\u00E9</c>, <c>\u0022</c>) and, worse, <c>ESCAPE '\'</c> is not a
/// portable literal — MySQL applies C-style escaping to string literals, so it reads as an unterminated
/// string, while SQLite would reject the doubled <c>'\\'</c> form as a two-character escape.
/// </summary>
private const char LikeEscapeChar = '/';
public async Task<Option<SearchFieldValuesResponseModel>> Handle(
GetSearchFieldValues request,
CancellationToken cancellationToken)
@@ -46,19 +67,34 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
}
IQueryable<string> source = GetSource(dbContext, request.Name);
if (source is null)
string listColumn = GetSongListValuedColumn(request.Name);
if (source is null && listColumn is null)
{
return Option<SearchFieldValuesResponseModel>.None;
}
List<string> values = await source
.Where(v => v != null && v.ToLower().StartsWith(qLower))
.Distinct()
.OrderBy(v => v)
.Take(limit)
.ToListAsync(cancellationToken);
var values = new List<string>();
return new SearchFieldValuesResponseModel(values);
if (source is not null)
{
values.AddRange(
await source
.Where(v => v != null && v.ToLower().StartsWith(qLower))
.Distinct()
.OrderBy(v => v)
.Take(limit)
.ToListAsync(cancellationToken));
}
if (listColumn is not null)
{
values.AddRange(
await GetSongListValuedValues(dbContext, listColumn, request.Query, qLower, cancellationToken));
}
// Each contributing source already returned its own prefix-filtered, ascending first-`limit` values, so
// sorting the union and taking `limit` again yields exactly the first `limit` of the combined set.
return new SearchFieldValuesResponseModel(FilterSortTake(values.Distinct(), qLower, limit));
}
private static IQueryable<string> GetSource(TvContext dbContext, string name) => name switch
@@ -68,8 +104,11 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
"director" => dbContext.Set<Director>().Select(d => d.Name),
"writer" => dbContext.Set<Writer>().Select(w => w.Name),
"actor" => dbContext.Actors.Select(a => a.Name),
// entity artists only; free-text music-video/song artist credits are not included (known limitation)
"artist" => dbContext.ArtistMetadata.Select(m => m.Title),
// Mirrors what LuceneSearchIndex writes to the `artist` field: the music video's linked artist entity
// (ArtistMetadata.Title) plus its free-text credits (MusicVideoArtist rows). The third contributor —
// SongMetadata.Artists — is a JSON-array column and is handled by GetSongListValuedValues instead.
"artist" => dbContext.ArtistMetadata.Select(m => m.Title)
.Concat(dbContext.Set<MusicVideoArtist>().Select(a => a.Name)),
"tag" => dbContext.Set<Tag>()
.Where(t => t.ExternalTypeId != Tag.NfoCountryTypeId && t.ExternalTypeId != Tag.PlexNetworkTypeId)
.Select(t => t.Name),
@@ -87,6 +126,123 @@ public class GetSearchFieldValuesHandler(IDbContextFactory<TvContext> dbContextF
_ => null
};
/// <summary>
/// Maps a field name onto the <c>SongMetadata</c> column that backs it as an <c>IList&lt;string&gt;</c>.
/// The returned value is a compile-time constant from this switch — never caller input — so it is safe
/// to interpolate into the SQL in <see cref="ListValuedSql" />.
/// </summary>
private static string GetSongListValuedColumn(string name) => name switch
{
"artist" => "Artists",
"album_artist" => "AlbumArtists",
_ => null
};
/// <summary>
/// Reads whole values out of a <c>SongMetadata</c> <c>IList&lt;string&gt;</c> column.
/// <para>
/// EF maps these as primitive collections: one JSON array per row in a single <c>TEXT</c>/
/// <c>longtext</c> column. Neither provider can project the elements server-side — SQLite needs
/// the SQL <c>APPLY</c> operator it doesn't have, and Pomelo MySQL doesn't implement primitive
/// 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, then split and exact-filter in memory. When the
/// library has more matching rows than <see cref="ListValuedRowCap" /> the suggestion list for these
/// fields is a deterministic prefix of the matches rather than the complete set.
/// </para>
/// </summary>
private static async Task<List<string>> GetSongListValuedValues(
TvContext dbContext,
string column,
string query,
string qLower,
CancellationToken cancellationToken)
{
IEnumerable<string> rows = await dbContext.Connection.QueryAsync<string>(
new CommandDefinition(
ListValuedSql(column),
new { Pattern = JsonElementPrefixPattern(query), Cap = ListValuedRowCap },
cancellationToken: cancellationToken));
var values = new List<string>();
foreach (string row in rows)
{
if (string.IsNullOrWhiteSpace(row))
{
continue;
}
string[] elements;
try
{
elements = JsonSerializer.Deserialize<string[]>(row);
}
catch (JsonException)
{
continue;
}
foreach (string element in elements ?? [])
{
if (!string.IsNullOrEmpty(element) && element.ToLower().StartsWith(qLower))
{
values.Add(element);
}
}
}
return values;
}
/// <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.
/// </summary>
private static string ListValuedSql(string column) =>
$"SELECT {column} FROM SongMetadata WHERE {column} IS NOT NULL " +
$"AND LOWER({column}) LIKE @Pattern ESCAPE '{LikeEscapeChar}' " +
$"ORDER BY {column} LIMIT @Cap";
/// <summary>
/// Builds the raw-JSON <c>LIKE</c> pattern that matches a row containing an element starting with
/// <paramref name="query" />. Anchoring on the opening quote (<c>%"prefix%</c>) keeps the superset
/// tight: it matches element starts, not substrings anywhere in the row.
/// <para>
/// The prefix is JSON-encoded first, because that is how it is stored — EF writes the array with the
/// default <c>JavaScriptEncoder</c>, so <c>Beyoncé</c> lands on disk as <c>Beyoncé</c> and a
/// literal quote as <c>"</c>. Encoding also makes the pattern pure ASCII, which is why this
/// match means the same thing on both providers: SQLite's <c>lower()</c> is ASCII-only and MySQL's
/// is Unicode-aware, but on ASCII input they agree. Lowercasing the pattern here (rather than
/// relying on <c>LIKE</c>'s own case rules) is what keeps the comparison correct under a
/// case-sensitive MySQL column collation as well as a case-insensitive one; under a
/// case-insensitive collation it simply widens the superset, which the in-memory exact filter
/// then narrows again.
/// </para>
/// </summary>
private static string JsonElementPrefixPattern(string query)
{
string encoded = JsonSerializer.Serialize(query ?? string.Empty);
// strip the quotes JsonSerializer wraps a string in
encoded = encoded.Substring(1, encoded.Length - 2);
var builder = new StringBuilder("%\"");
foreach (char c in encoded.ToLowerInvariant())
{
if (c is '%' or '_' or LikeEscapeChar)
{
builder.Append(LikeEscapeChar);
}
builder.Append(c);
}
return builder.Append('%').ToString();
}
private static async Task<List<string>> GetContentRatingValues(
TvContext dbContext,
string qLower,
@@ -4,6 +4,7 @@ using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Shouldly;
@@ -176,6 +177,231 @@ public class GetSearchFieldValuesHandlerTests
networkResult.IfSome(r => r.Values.ShouldBe(new List<string> { "HBO" }));
}
[Test]
public async Task Artist_Merges_Entity_Artists_Music_Video_Credits_And_Song_Credits()
{
await using (TvContext context = _db.CreateContext())
{
context.ArtistMetadata.Add(Artist("Alpha Entity"));
// negative control: an entity artist that must NOT match the "al" prefix
context.ArtistMetadata.Add(Artist("Zeta Entity"));
context.MusicVideoMetadata.AddRange(
MusicVideo("MV One", "Alpha Credit", "Alpha Shared"),
// "Alpha Shared" appears in two rows, so DISTINCT has something to collapse
MusicVideo("MV Two", "Alpha Shared"),
MusicVideo("MV Three", "Zeta Credit"));
context.SongMetadata.AddRange(
Song("Song One", ["Alpha Song", "Zeta Song"]),
Song("Song Two", ["Alpha Song"]),
Song("Song Three", ["Zeta Only"]));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
Option<SearchFieldValuesResponseModel> result = await handler.Handle(
new GetSearchFieldValues("artist", "al", 50),
CancellationToken.None);
result.IsSome.ShouldBeTrue();
result.IfSome(r => r.Values.ShouldBe(
new List<string> { "Alpha Credit", "Alpha Entity", "Alpha Shared", "Alpha Song" }));
}
[Test]
public async Task Artist_Returns_Every_Source_For_Empty_Query()
{
await using (TvContext context = _db.CreateContext())
{
context.ArtistMetadata.Add(Artist("Entity"));
context.MusicVideoMetadata.Add(MusicVideo("MV", "Credit"));
context.SongMetadata.Add(Song("Song", ["SongArtist"]));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
Option<SearchFieldValuesResponseModel> result = await handler.Handle(
new GetSearchFieldValues("artist", string.Empty, 50),
CancellationToken.None);
result.IsSome.ShouldBeTrue();
result.IfSome(r => r.Values.ShouldBe(new List<string> { "Credit", "Entity", "SongArtist" }));
}
[Test]
public async Task Album_Artist_Returns_Song_Album_Artists_Instead_Of_NotFound()
{
await using (TvContext context = _db.CreateContext())
{
context.SongMetadata.AddRange(
Song("One", ["Performer"], ["Alpha Album Artist", "Beta Album Artist"]),
// repeated across rows so DISTINCT is exercised
Song("Two", ["Performer"], ["Alpha Album Artist"]),
// negative control: a row whose album artists are absent entirely
Song("Three", ["Performer"], null));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
Option<SearchFieldValuesResponseModel> result = await handler.Handle(
new GetSearchFieldValues("album_artist", string.Empty, 50),
CancellationToken.None);
result.IsSome.ShouldBeTrue();
result.IfSome(r => r.Values.ShouldBe(new List<string> { "Alpha Album Artist", "Beta Album Artist" }));
// the performers on the same rows must not leak into album_artist
result.IfSome(r => r.Values.ShouldNotContain("Performer"));
}
[Test]
public async Task List_Valued_Fields_Match_Whole_Elements_Not_Substrings_And_Ignore_Neighbours()
{
await using (TvContext context = _db.CreateContext())
{
context.SongMetadata.AddRange(
// "Neighbour" rides along in the SQL superset because "Radiohead" matches; it must be
// dropped by the in-memory exact prefix filter.
Song("One", ["Radiohead", "Neighbour"]),
// "The Radio Dept." contains "radio" but does not start with it
Song("Two", ["The Radio Dept."]),
Song("Three", ["Radio Birdman"]));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
Option<SearchFieldValuesResponseModel> result = await handler.Handle(
new GetSearchFieldValues("artist", "radio", 50),
CancellationToken.None);
result.IsSome.ShouldBeTrue();
result.IfSome(r => r.Values.ShouldBe(new List<string> { "Radio Birdman", "Radiohead" }));
}
[Test]
public async Task List_Valued_Fields_Survive_Json_Escaping_And_Like_Wildcards()
{
await using (TvContext context = _db.CreateContext())
{
context.SongMetadata.AddRange(
// non-ASCII: stored on disk JSON-escaped as é
Song("One", ["Beyoncé"]),
// an embedded quote is stored as "
Song("Two", ["\"Weird Al\" Yankovic"]),
// LIKE wildcards in the query must be treated literally
Song("Three", ["50% Off"]),
Song("Four", ["50 Cent"]));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
(await handler.Handle(new GetSearchFieldValues("artist", "beyoncé", 50), CancellationToken.None))
.IfSome(r => r.Values.ShouldBe(new List<string> { "Beyoncé" }));
(await handler.Handle(new GetSearchFieldValues("artist", "\"weird", 50), CancellationToken.None))
.IfSome(r => r.Values.ShouldBe(new List<string> { "\"Weird Al\" Yankovic" }));
// "50%" must not behave as the wildcard "50<anything>" — "50 Cent" must not come back
(await handler.Handle(new GetSearchFieldValues("artist", "50%", 50), CancellationToken.None))
.IfSome(r => r.Values.ShouldBe(new List<string> { "50% Off" }));
}
[Test]
public async Task List_Valued_Source_Is_Bounded_By_A_Row_Cap()
{
// The handler caps the raw-JSON pre-filter at 1000 rows, ordered by the raw column. Seed one row past
// the cap whose JSON sorts last but whose element would sort FIRST in the output: an unbounded
// implementation returns it, a capped one cannot.
const string overCap = "aaa-past-the-row-cap";
await using (TvContext context = _db.CreateContext())
{
for (var i = 0; i < 1000; i++)
{
context.SongMetadata.Add(Song($"Song {i}", [$"b{i:D4}"]));
}
context.SongMetadata.Add(Song("Over", ["zzz-sorts-last", overCap]));
await context.SaveChangesAsync();
}
var handler = new GetSearchFieldValuesHandler(_db.Factory);
Option<SearchFieldValuesResponseModel> result = await handler.Handle(
new GetSearchFieldValues("artist", string.Empty, 3),
CancellationToken.None);
result.IsSome.ShouldBeTrue();
result.IfSome(r => r.Values.ShouldBe(new List<string> { "b0000", "b0001", "b0002" }));
result.IfSome(r => r.Values.ShouldNotContain(overCap));
// positive control: the same row IS reachable once the pre-filter narrows the candidate set below the cap
Option<SearchFieldValuesResponseModel> narrowed = await handler.Handle(
new GetSearchFieldValues("artist", "aaa", 50),
CancellationToken.None);
narrowed.IsSome.ShouldBeTrue();
narrowed.IfSome(r => r.Values.ShouldBe(new List<string> { overCap }));
}
[Test]
public async Task List_Valued_Columns_Are_Stored_As_Ascii_Escaped_Json_Arrays()
{
// Pins the on-disk encoding the LIKE pre-filter is built against. If an EF upgrade changes the
// JavaScriptEncoder (e.g. stops escaping non-ASCII), the pattern would silently stop matching —
// this fails loudly instead. It also documents why LOWER() is provider-independent here: the
// stored text is pure ASCII, so SQLite's ASCII-only lower() and MySQL's Unicode-aware LOWER() agree.
await using (TvContext context = _db.CreateContext())
{
context.SongMetadata.Add(Song("One", ["Beyoncé", "\"Q\""]));
await context.SaveChangesAsync();
}
await using (TvContext context = _db.CreateContext())
{
List<string> raw = await context.Database
.SqlQueryRaw<string>("SELECT Artists AS Value FROM SongMetadata")
.ToListAsync();
raw.ShouldBe(new List<string> { """["Beyonc\u00E9","\u0022Q\u0022"]""" });
}
}
private static ArtistMetadata Artist(string title) => new()
{
MetadataKind = MetadataKind.External,
DateAdded = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow,
Title = title
};
private static MusicVideoMetadata MusicVideo(string title, params string[] artists) => new()
{
MetadataKind = MetadataKind.External,
DateAdded = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow,
Title = title,
Artists = artists.Map(a => new MusicVideoArtist { Name = a }).ToList()
};
private static SongMetadata Song(string title, IList<string> artists, IList<string> albumArtists = null) => new()
{
MetadataKind = MetadataKind.External,
DateAdded = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow,
Title = title,
Artists = artists,
AlbumArtists = albumArtists
};
[Test]
public async Task Dedupes_Repeated_Values()
{
@@ -0,0 +1,107 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Application.Search;
/// <summary>
/// Provider-shape guards for the <c>artist</c> / <c>album_artist</c> facet-value sources (#578).
/// <para>
/// <see cref="GetSearchFieldValuesHandlerTests" /> runs against in-memory SQLite, so it structurally
/// cannot see a MySQL translation or collation difference. These tests build the same LINQ against the
/// Pomelo MySQL provider and assert the generated SQL — <c>ToQueryString</c> compiles the query without
/// touching a server, so no MySQL instance is needed.
/// </para>
/// </summary>
[TestFixture]
[NonParallelizable]
public class SearchFieldValuesQueryShapeTests
{
private bool _wasSqlite;
[SetUp]
public void SetUp() => _wasSqlite = TvContext.IsSqlite;
[TearDown]
public void TearDown() => TvContext.IsSqlite = _wasSqlite;
[Test]
public void Artist_Entity_Union_Translates_On_Both_Providers_With_Lower_And_A_Row_Limit()
{
foreach ((string provider, Func<TvContext> create) in Providers())
{
using TvContext context = create();
// exactly the queryable half of GetSearchFieldValuesHandler.GetSource("artist")
string sql = context.ArtistMetadata.Select(m => m.Title)
.Concat(context.Set<MusicVideoArtist>().Select(a => a.Name))
.Where(v => v != null && v.ToLower().StartsWith("a"))
.Distinct()
.OrderBy(v => v)
.Take(50)
.ToQueryString();
// case-insensitivity comes from LOWER() on the column, not from the provider's LIKE collation
sql.ShouldContain("LOWER(", Case.Insensitive, $"{provider}: {sql}");
sql.ShouldContain("LIKE", Case.Insensitive, $"{provider}: {sql}");
sql.ShouldContain("MusicVideoArtist", Case.Insensitive, $"{provider}: {sql}");
// the whole thing is one bounded server-side query, never a client-side scan
sql.ShouldContain("LIMIT", Case.Insensitive, $"{provider}: {sql}");
}
}
[Test]
public void Song_List_Columns_Cannot_Be_Projected_Server_Side_On_Either_Provider()
{
// Documents WHY the handler drops to raw SQL for SongMetadata.Artists / .AlbumArtists rather than
// SelectMany-ing them: EF maps them as JSON primitive collections and neither provider can translate
// the projection (SQLite needs APPLY; Pomelo has no primitive-collection support). If a provider
// upgrade ever makes this translate, this test fails and the raw-SQL path can be retired.
foreach ((string provider, Func<TvContext> create) in Providers())
{
using TvContext context = create();
Should.Throw<InvalidOperationException>(
() => context.SongMetadata.SelectMany(m => m.Artists).Distinct().Take(50).ToQueryString(),
$"{provider} unexpectedly translated a primitive-collection projection");
Should.Throw<InvalidOperationException>(
() => context.SongMetadata.SelectMany(m => m.AlbumArtists).Distinct().Take(50).ToQueryString(),
$"{provider} unexpectedly translated a primitive-collection projection");
}
}
private static IEnumerable<(string Provider, Func<TvContext> Create)> Providers() =>
[
("sqlite", Sqlite),
("mysql", MySql)
];
private static TvContext Sqlite()
{
TvContext.IsSqlite = true;
var builder = new DbContextOptionsBuilder<TvContext>();
builder.UseSqlite("Data Source=:memory:");
return Create(builder.Options);
}
private static TvContext MySql()
{
TvContext.IsSqlite = false;
var builder = new DbContextOptionsBuilder<TvContext>();
builder.UseMySql(
"Server=localhost;Database=ersatztv_query_shape;User=root;Password=ersatztv;",
new MySqlServerVersion(new Version(8, 0, 36)));
return Create(builder.Options);
}
private static TvContext Create(DbContextOptions<TvContext> options) =>
new(
options,
NullLoggerFactory.Instance,
new SlowQueryInterceptor(NullLogger<SlowQueryInterceptor>.Instance));
}
+2 -1
View File
@@ -205,7 +205,8 @@ 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.")]
"source. The list-valued music fields (artist, album_artist) are bounded best-effort: on a very " +
"large library they return a deterministic subset of the matches rather than every match.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(SearchFieldValuesResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
+1 -1
View File
@@ -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.",
"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 list-valued music fields (artist, album_artist) are bounded best-effort: on a very large library they return a deterministic subset of the matches rather than every match.",
"operationId": "GetSearchFieldValues",
"parameters": [
{
+11 -1
View File
@@ -444,7 +444,7 @@ standard credential (catalog-read tier — no `[RequiresAuthentication]`):
Query params: `q` (optional prefix filter, case-insensitive, default empty) and `limit` (optional,
clamped `1..50`, default 50). `{name}` is allow-listed to `SearchFieldCatalog` fields with
`type: "text"` AND a distinct-value source in the database — an unknown field, a non-text field (e.g.
an enum), or a text field without a source (`title`, `show_title`, `album_artist`) 404s rather than
an enum), or a text field without a source (`title`, `show_title`) 404s rather than
returning an empty list, since enum fields already ship their values inline on
`GET /api/v1/search/fields` and never need this endpoint. Returns `SearchFieldValuesResponseModel`
(`{ values: string[] }`), sourced from a per-field distinct-values DB query (`IDbContextFactory<TvContext>`),
@@ -452,6 +452,16 @@ not the Lucene term dictionary — analyzed text fields store lowercased word to
No server-side caching. Powers the visual rule builder's value-input combobox for text fields; see
`docs/decisions.md` 2026-07-23 (#434) and `spa-conventions.md` §12.
**Bounded best-effort for list-valued fields (#578)**: `artist` and `album_artist` are backed (wholly
or partly) by `SongMetadata.Artists`/`AlbumArtists`, which EF maps as **primitive collections** — one
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 pre-filters on the raw JSON in SQL
and caps the rows it reads, so on a very large library the response is a **deterministic subset** of the
matches rather than every match — say so in the `[EndpointDescription]` of any endpoint that adopts this
shape, and never let an unbounded scan stand in for it. Full rationale, the rejected normalized-side-table
alternative and the dual-provider `LIKE`/`LOWER` portability rules: `api.search-field-values-list-columns`.
**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`
precedent; `pageNum` 0-based, clamped `0..2_000_000` so `pageNum * pageSize` can't overflow `int` to a 500)
+1
View File
@@ -215,3 +215,4 @@ another doc or an old issue comment should land here and then follow the link.
- 2026-07-25 — Rule-builder group nesting is bounded-arbitrary depth (`MAX_GROUP_DEPTH`), not one level (#436) — [`spa.rulebuilder-nesting`](decisions/records/spa/rulebuilder-nesting.md)
- 2026-07-25 — The rationale-edit marker is a git trailer, not a substring anywhere in the commit range (#609) — [`ci.decisions-edit-trailer`](decisions/records/ci/decisions-edit-trailer.md)
- 2026-07-25 — UI-E2E: headless Playwright flows in the existing `functional-e2e` job, browser baked into the CI image (#445) — [`ci.ui-e2e-harness`](decisions/records/ci/ui-e2e-harness.md)
- 2026-07-26 — List-valued (JSON primitive collection) facet fields get bounded best-effort values via a raw-JSON LIKE pre-filter, not a normalized side table (#578) — [`api.search-field-values-list-columns`](decisions/records/api/search-field-values-list-columns.md)
+1
View File
@@ -29,6 +29,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `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` | `GET /api/v1/search/fields/{name}/values?q=&limit=` returns distinct WHOLE values from the database for one of a narrow allow-list of catalog fields (not the Lucene term dictionary — analyzed `TextField`s store lowercased word tokens, e.g. "Science Fiction" → `science`/`fiction`, useless as a typeahead suggestion), 404 for an unknown field, a non-`text` field, or a `text` field with no distinct-value source; case-insensitive prefix-filtered on `q`, `limit` clamped to `[1, 50]` (default 50). | 2026-07-23 | [link](records/api/search-field-values.md) |
| `api.search-field-values-list-columns` | A `text` search field whose values live in an EF **primitive collection** (one JSON array per row in a single column — `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) IS served by `GET /api/v1/search/fields/{name}/values`, not 404'd, but as **bounded best-effort**: SQL pre-filters on the raw JSON with `LOWER(col) LIKE '%"<json-encoded-lowercased-prefix>%' ESCAPE '/'` — a deliberate superset, since it matches a row, not an element — capped at a fixed row cap (1000) with an `ORDER BY` on the raw column so the truncation point is deterministic; the rows are then split, exact-prefix-filtered, deduped, sorted and `limit`ed in memory. An empty `q` is supported (it degenerates to `%"%`, still capped), so these fields need no special-case client contract. The prefix is JSON-encoded before matching because that is how it is stored, which also makes the pattern pure ASCII and therefore makes `LOWER()` mean the same thing on SQLite (ASCII-only) and MySQL (Unicode-aware); the pattern is lowercased in C# rather than relying on `LIKE`'s own case rules, so the match is correct under a case-sensitive MySQL collation as well as a case-insensitive one. The escape character is `/`, never `\` — `ESCAPE '\'` is not a portable SQL literal. | 2026-07-26 | [link](records/api/search-field-values-list-columns.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) |
@@ -0,0 +1,75 @@
---
key: api.search-field-values-list-columns
title: '2026-07-26 — list-valued (JSON primitive collection) fields get bounded best-effort facet values via a raw-JSON LIKE pre-filter, not a normalized side table (#578)'
status: active
since: '2026-07-26'
supersedes: none
superseded-by: none
rule: 'A `text` search field whose values live in an EF **primitive collection** (one JSON array per row in a single column — `SongMetadata.Artists`, `SongMetadata.AlbumArtists`) IS served by `GET /api/v1/search/fields/{name}/values`, not 404''d, but as **bounded best-effort**: SQL pre-filters on the raw JSON with `LOWER(col) LIKE ''%"<json-encoded-lowercased-prefix>%'' ESCAPE ''/''` — a deliberate superset, since it matches a row, not an element — capped at a fixed row cap (1000) with an `ORDER BY` on the raw column so the truncation point is deterministic; the rows are then split, exact-prefix-filtered, deduped, sorted and `limit`ed in memory. An empty `q` is supported (it degenerates to `%"%`, still capped), so these fields need no special-case client contract. The prefix is JSON-encoded before matching because that is how it is stored, which also makes the pattern pure ASCII and therefore makes `LOWER()` mean the same thing on SQLite (ASCII-only) and MySQL (Unicode-aware); the pattern is lowercased in C# rather than relying on `LIKE`''s own case rules, so the match is correct under a case-sensitive MySQL collation as well as a case-insensitive one. The escape character is `/`, never `\` — `ESCAPE ''\''` is not a portable SQL literal.'
signals: 'artist typeahead free-text credits, album_artist 404, SongMetadata.Artists, SongMetadata.AlbumArtists, MusicVideoArtist suggestions, EF primitive collection, PrimitiveCollection JSON column, SelectMany requires APPLY on SQLite, Pomelo primitive collections not enabled, raw JSON LIKE pre-filter, ListValuedRowCap, bounded best-effort facet values, LIKE ESCAPE portability · paths: `ErsatzTV.Application/Search/Queries/GetSearchFieldValuesHandler.cs`, `ErsatzTV/Controllers/Api/SearchController.cs`, `ErsatzTV.Tests/Application/Search/GetSearchFieldValuesHandlerTests.cs`, `ErsatzTV.Tests/Application/Search/SearchFieldValuesQueryShapeTests.cs` · issues: #578, #434'
mechanics: '`GetSearchFieldValuesHandler.GetSongListValuedColumn` / `.GetSongListValuedValues` / `.ListValuedSql` / `.JsonElementPrefixPattern`; `SearchFieldValuesQueryShapeTests` (dual-provider `ToQueryString` guard); `api.search-field-values` (the base endpoint contract this extends)'
---
Extends `api.search-field-values` rather than superseding it: that record's rule still reads true —
whole values, from the database, not the Lucene term dictionary, 404 for a field with no
distinct-value source. What changed is only **which** fields have a source. Its body's claim that
music-video/song artist credits are "a known, intentionally-uncovered gap" and that `album_artist`
has no server-side source was corrected in place.
**The three `artist` sources are not the same problem.** `LuceneSearchIndex` writes the `artist`
field from three places, and only two of them are ordinary columns:
- `ArtistMetadata.Title` — a plain column on a plain table.
- `MusicVideoArtist.Name` — also a real entity table (`MusicVideoMetadata.HasMany(m => m.Artists)`),
so the free-text music-video credits are directly `SELECT DISTINCT`-able. These two are simply
`Concat`ed into the existing server-side pipeline
(`.Where(v => v.ToLower().StartsWith(qLower)).Distinct().OrderBy(v => v).Take(limit)`), which EF
emits as one bounded `UNION ALL` + `LOWER(...) LIKE ... LIMIT` on both providers.
- `SongMetadata.Artists` (and, for `album_artist`, `SongMetadata.AlbumArtists`) — an
`IList<string>` that EF 9 maps as a **primitive collection**: no `HasConversion` anywhere, one
JSON array per row in a single `TEXT`/`longtext` column. This one has no server-side projection at
all. Verified empirically against both providers: SQLite reports *"Translating this query requires
the SQL APPLY operation, which is not supported on SQLite"*, and Pomelo MySQL 9.0.0 reports
*"Primitive collections support has not been enabled"*. `SearchFieldValuesQueryShapeTests` pins
both failures, so if a provider upgrade ever makes the projection translate, the raw-SQL path can
be retired on a red test rather than on a hunch.
**Why the LIKE superset and not a normalized `SongArtist` table.** A real join table (the shape
`MusicVideoArtist` already has) would make this exact and indexable forever, but it costs a
dual-provider schema migration plus a data backfill, changes to every scanner write path that
populates `SongMetadata.Artists`, changes to the Lucene indexer, and leaves two representations of
the same fact to drift apart — a large blast radius for a typeahead convenience. Rejected on cost.
The raw-JSON pre-filter is confined to one private method, needs no migration, and is a strictly
additive read path. Also rejected: querying the Lucene term dictionary, which is the thing
`api.search-field-values` exists to avoid (analyzed `TextField`s store lowercased word tokens).
**The bound is the point, and it is tested behaviourally.** `ListValuedRowCap = 1000` bounds rows
fetched, not values returned, because the pre-filter matches rows whole. The `ORDER BY` on the raw
column is what makes the truncation deterministic — and therefore testable:
`List_Valued_Source_Is_Bounded_By_A_Row_Cap` seeds 1001 rows where the over-cap row's JSON sorts
*last* but its element would sort *first* in the output, so an unbounded implementation returns it
and a capped one cannot. A positive control in the same test narrows `q` until that row is back
under the cap and asserts it reappears, so the test cannot pass by the value being unreachable for
some unrelated reason.
**`album_artist` 404 → 200 is additive.** Nothing consumes the 404 as a signal: the SPA's
`getSearchFieldValues` (`web/src/api/search.ts`) treats any non-200 as "no suggestions, fall back to
a free-text input", which is exactly what it will now do less often. Per `api.versioning-v1`,
widening which fields return values — and which values a field returns — adds capability without
removing any, so it needs no `/api/v2`.
**Known imprecision, deliberately accepted.** On a library with more than 1000 rows matching the
pre-filter, the suggestions for `artist`/`album_artist` are a deterministic prefix of the matches
rather than every match. This is stated on the endpoint's `[EndpointDescription]` so it reaches the
OpenAPI document. The alternative — requiring a non-empty `q` for list-valued fields — was rejected:
it would make one group of fields behave differently from every other field for the same client
code, for a case the row cap already handles.
**Dual-provider verification, and its limit.** The queryable half is pinned on both providers by
`SearchFieldValuesQueryShapeTests`, which compiles the query with `ToQueryString()` — no server
needed. The raw-SQL half cannot be executed against MySQL from the unit-test suite; it is defended
by construction instead (portable `LOWER`/`LIKE`/`ESCAPE`/`ORDER BY`/`LIMIT`, unquoted identifiers,
a non-backslash escape character, and an ASCII-only pattern so collation and `LOWER()` semantics
cannot diverge) plus `List_Valued_Columns_Are_Stored_As_Ascii_Escaped_Json_Arrays`, which pins the
on-disk JSON encoding the pattern is built against so an EF encoder change fails loudly instead of
silently returning nothing.
@@ -23,8 +23,9 @@ an empty list for a field that will never have values — a 404 tells a caller "
**DB-sourced, not the search index.** The handler injects `IDbContextFactory<TvContext>` and resolves an
explicit per-field-name `IQueryable<string>` (or, for a few special cases, an in-memory list) rather than
querying `ISearchIndex`: `genre`/`show_genre` → `Set<Genre>()`, `studio` → `Set<Studio>()`, `director` →
`Set<Director>()`, `writer` → `Set<Writer>()`, `actor` → `Actors`, `artist` → `ArtistMetadata.Title` (entity
artists only — free-text music-video/song artist credits are a known, intentionally-uncovered gap), `tag` →
`Set<Director>()`, `writer` → `Set<Writer>()`, `actor` → `Actors`, `artist` → `ArtistMetadata.Title`
concatenated with `Set<MusicVideoArtist>().Name` (plus `SongMetadata.Artists` via the list-valued path —
see `api.search-field-values-list-columns`, #578), `tag` →
`Set<Tag>()` excluding `Tag.NfoCountryTypeId`/`Tag.PlexNetworkTypeId` (reapplying the indexer's own
exclusions so country/network strings don't leak in as tags), `network` → `Set<Tag>()` filtered to
`Tag.PlexNetworkTypeId`, `collection` → `Collections`, `video_codec` → `MediaStreams` filtered to
@@ -36,10 +37,11 @@ of queried: `state` (the fixed 4-value `MediaItemState` enum) and `video_dynamic
`MovieMetadata`/`ShowMetadata`/`OtherVideoMetadata`/`RemoteStreamMetadata`, so the handler pulls the distinct
raw strings then `Split('/')`s, trims, and dedupes in memory before the same prefix-filter/sort/take — this
matches what search actually matches on, rather than surfacing the compound string as one facet value.
**`title`, `show_title`, `album_artist` are explicitly NOT supported** (404, free-text fallback): `title`/
`show_title` are near-unique free-text fields spanning ~9 metadata tables where a distinct list of every
title isn't a useful facet; `album_artist` backs onto `SongMetadata.AlbumArtists`, a value-converted
`IList<string>` column EF can't translate into a server-side distinct query.
**`title` and `show_title` are explicitly NOT supported** (404, free-text fallback): they are near-unique
free-text fields spanning ~9 metadata tables where a distinct list of every title isn't a useful facet.
`album_artist` was originally 404 here for a different reason — it backs onto `SongMetadata.AlbumArtists`,
which EF can't translate into a server-side distinct query — and since #578 it returns bounded best-effort
values instead; see `api.search-field-values-list-columns`.
**Why a thin query, not a cache.** No result cache, no debounce on the server side (the SPA combobox
debounces the keystroke) — each per-field query is a bounded, indexed `Distinct`/`Take`; adding a cache
+5 -1
View File
@@ -624,7 +624,11 @@ not wired here.
`GET /api/v1/search/fields/{name}/values?q=&limit=`), debounced on keystroke, prefix-matching the
in-progress value against distinct terms already in the index. It always allows free-text entry as a
fallback — a 404 (non-text field) or an empty result list (e.g. ElasticSearch backend) degrades to a
plain text input rather than blocking the rule.
plain text input rather than blocking the rule. Since #578 (`api.search-field-values-list-columns`)
`album_artist` returns values instead of 404ing, and `artist` covers free-text music-video/song credits
as well as entity artists; for those two the server's list is **bounded best-effort** on a very large
library, so the free-text fallback stays load-bearing — never treat an absent suggestion as an invalid
value.
- **Single-child-group normalization** (#438) — `normalizeGroup` (`validation.ts`) coerces a group's
`match` to `all` whenever it has fewer than two children, recursively. A one-child `any` group is
semantically identical to `all` but doesn't round-trip through `compile`→`parse` (the compiled Lucene