From 4a78b946d94f7cec7b7fd6d1b884edee7ed07bf7 Mon Sep 17 00:00:00 2001 From: sudacode Date: Sun, 22 Nov 2026 14:37:03 -0800 Subject: [PATCH] fix(stats): address review findings on franchise walk and group view - The relation walk keeps every incoming link to an entry and follows it when any link is accepted, so a veto on one seed no longer hides a franchise root reached through another (and seed order no longer changes the result). - A stopped refresher starts no further AniList request; the in-flight result is dropped and the walk ends. - An open franchise that is left with one part closes once the library has loaded, so a later refresh cannot reopen it on its own. --- .../services/anilist/franchise-graph.test.ts | 47 +++++++++++++++++++ src/core/services/anilist/franchise-graph.ts | 37 +++++++++------ .../franchise-relation-refresher.ts | 5 +- .../src/components/anime/AnimeGroups.test.tsx | 44 +++++++++++++++++ stats/src/components/anime/AnimeTab.tsx | 7 +++ 5 files changed, 122 insertions(+), 18 deletions(-) diff --git a/src/core/services/anilist/franchise-graph.test.ts b/src/core/services/anilist/franchise-graph.test.ts index 50a64f66..39b5ad6a 100644 --- a/src/core/services/anilist/franchise-graph.test.ts +++ b/src/core/services/anilist/franchise-graph.test.ts @@ -172,6 +172,53 @@ test('walk does not follow the links of an entry that vetoes how it was reached' assert.deepEqual(asked, [[2], [1]]); }); +test('walk follows an entry reached through any link it accepts, whatever the seed order', async () => { + const nodes = [ + entry(1, 'TV', 20100101, [['SEQUEL', 3]]), + entry(2, 'TV', 20110101, [['SEQUEL', 3]]), + // Rejects seed 1 but accepts seed 2, so its own links are still followed. + entry(3, 'TV', 20120101, [ + ['SPIN_OFF', 1], + ['PREQUEL', 2], + ['PARENT', 4], + ]), + entry(4, 'TV', 20000101), + ]; + for (const seeds of [ + [1, 2], + [2, 1], + ]) { + const { asked, options } = walkHarness(nodes, { seeds }); + await walkFranchiseRelations(options); + assert.deepEqual(asked, [[1, 2], [3], [4]]); + } +}); + +test('a cancelled walk starts no further request and drops the in-flight result', async () => { + const seeds = Array.from({ length: 51 }, (_, index) => index + 1); + let cancelled = false; + const batches: number[] = []; + const { asked, known, options } = walkHarness( + seeds.map((id) => entry(id, 'TV', 20200101)), + { + seeds, + isFresh: () => false, + onBatch: (nodes) => batches.push(nodes.length), + isCancelled: () => cancelled, + }, + ); + const fetchNodes = options.fetchNodes; + options.fetchNodes = async (ids) => { + cancelled = true; + return fetchNodes(ids); + }; + const result = await walkFranchiseRelations(options); + assert.equal(asked.length, 1); + assert.deepEqual(batches, []); + assert.equal(known.size, 0); + assert.equal(result.truncated, true); +}); + test('walk respects the depth and fetch bounds', async () => { const chain = Array.from({ length: 10 }, (_, i) => entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []), diff --git a/src/core/services/anilist/franchise-graph.ts b/src/core/services/anilist/franchise-graph.ts index 0e4a86f4..aa78b2fe 100644 --- a/src/core/services/anilist/franchise-graph.ts +++ b/src/core/services/anilist/franchise-graph.ts @@ -154,6 +154,8 @@ export interface FranchiseWalkOptions { maxDepth: number; /** Most entries fetched in one walk; the rest wait for the next walk. */ maxFetch: number; + /** When true, the walk starts no further request and drops an in-flight result. */ + isCancelled?: () => boolean; } export interface FranchiseWalkResult { @@ -174,9 +176,12 @@ export async function walkFranchiseRelations( ): Promise { const { known } = options; const visited = new Set(); - let frontier: Array<{ id: number; from: number | null }> = [...new Set(options.seeds)].map( - (id) => ({ id, from: null }), - ); + // `from` lists every entry the walk reached this one through at this depth + // (empty for a seed), so the order seeds are given in cannot change the result. + let frontier: Array<{ id: number; from: number[] }> = [...new Set(options.seeds)].map((id) => ({ + id, + from: [], + })); let fetched = 0; let truncated = false; @@ -193,10 +198,11 @@ export async function walkFranchiseRelations( if (allowed.length < stale.length) truncated = true; for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) { + if (options.isCancelled?.()) return { fetched, truncated: true }; const chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE); - const found = new Map( - (await options.fetchNodes(chunk)).map((node) => [node.anilistId, node] as const), - ); + const fetchedNodes = await options.fetchNodes(chunk); + if (options.isCancelled?.()) return { fetched, truncated: true }; + const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const)); const fetchedAtMs = options.now(); const batch = chunk.map((id): AnilistMediaNode => { const node = found.get(id); @@ -222,21 +228,22 @@ export async function walkFranchiseRelations( if (depth >= options.maxDepth) break; - const next: Array<{ id: number; from: number | null }> = []; - const queued = new Set(); + const next = new Map(); for (const step of frontier) { const node = known.get(step.id); if (!node) continue; - // Reached through a link the entry itself rejects (a spin-off's original): - // it is not part of the franchise, so its own links are not followed. - if (step.from !== null && vetoes(node, step.from)) continue; + // Reached only through links the entry itself rejects (a spin-off's + // original): it is not part of the franchise, so its own links are not + // followed. One accepted incoming link is enough. + if (step.from.length > 0 && step.from.every((fromId) => vetoes(node, fromId))) continue; for (const targetId of franchiseTargets(node)) { - if (visited.has(targetId) || queued.has(targetId)) continue; - queued.add(targetId); - next.push({ id: targetId, from: node.anilistId }); + if (visited.has(targetId)) continue; + const from = next.get(targetId); + if (from) from.push(node.anilistId); + else next.set(targetId, [node.anilistId]); } } - frontier = next; + frontier = [...next].map(([id, from]) => ({ id, from })); } return { fetched, truncated }; diff --git a/src/core/services/immersion-tracker/franchise-relation-refresher.ts b/src/core/services/immersion-tracker/franchise-relation-refresher.ts index 366c3211..f6eda357 100644 --- a/src/core/services/immersion-tracker/franchise-relation-refresher.ts +++ b/src/core/services/immersion-tracker/franchise-relation-refresher.ts @@ -64,9 +64,8 @@ export function createFranchiseRelationRefresher( known, isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS, fetchNodes: (ids) => deps.fetcher.fetchMedia(ids), - onBatch: (nodes) => { - if (!stopped) writeAnilistRelationNodes(deps.db, nodes); - }, + onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes), + isCancelled: () => stopped, now, maxDepth: FRANCHISE_WALK_MAX_DEPTH, maxFetch: FRANCHISE_WALK_MAX_FETCH, diff --git a/stats/src/components/anime/AnimeGroups.test.tsx b/stats/src/components/anime/AnimeGroups.test.tsx index 930d7bff..5fd4b569 100644 --- a/stats/src/components/anime/AnimeGroups.test.tsx +++ b/stats/src/components/anime/AnimeGroups.test.tsx @@ -132,3 +132,47 @@ test('a franchise card opens its parts in release order, and a part can stand al uninstallDom(); } }); + +test('a franchise left with one part closes and does not reopen on a later refresh', async () => { + const uninstallDom = installDom(); + const original = { ...apiClient }; + const [movie, season] = overlord.parts as [AnimeLibraryGroupPart, AnimeLibraryGroupPart]; + const split: AnimeLibraryGroup[] = [ + { ...overlord, parts: [movie], coverAnimeId: movie.animeId }, + { ...overlord, groupKey: 1, title: season.canonicalTitle, parts: [season], coverAnimeId: 1 }, + ]; + let library: AnimeLibraryGroup[] = [overlord]; + apiClient.getAnimeLibraryGroups = async () => library; + apiClient.getAnimeMergeRecommendations = async () => ({ recommendations: [] }); + apiClient.getAnimeDetail = async () => detailData(); + apiClient.getAnimeWords = async () => []; + apiClient.getAnimeRollups = async () => []; + apiClient.getAnimeKnownWordsSummary = async () => ({ totalUniqueWords: 0, knownWordCount: 0 }); + apiClient.setAnimeGroupOverride = async () => { + library = split; + }; + + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + try { + await act(async () => root.render()); + await act(async () => findButton(container, 'Overlord').click()); + await act(async () => findButton(container, 'Overlord II').click()); + await act(async () => findButton(container, 'Show On Its Own').click()); + await act(async () => findButton(container, 'Back to Overlord').click()); + assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/); + + // The franchise gets its second part back; the library must stay where it is. + library = [overlord]; + await act(async () => { + window.dispatchEvent(new window.Event('focus')); + }); + assert.match(findButton(container, 'Overlord').textContent ?? '', /2 parts/); + assert.doesNotMatch(container.textContent ?? '', /Seasons and Movies/); + } finally { + await act(async () => root.unmount()); + Object.assign(apiClient, original); + uninstallDom(); + } +}); diff --git a/stats/src/components/anime/AnimeTab.tsx b/stats/src/components/anime/AnimeTab.tsx index d8819741..48f8cf7d 100644 --- a/stats/src/components/anime/AnimeTab.tsx +++ b/stats/src/components/anime/AnimeTab.tsx @@ -161,6 +161,13 @@ export function AnimeTab({ 0, ); const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null; + // A franchise that no longer has several parts closes, so a later refresh + // cannot reopen it on its own. Only loaded results count; while a part is + // open, the franchise stays its back target. + useEffect(() => { + if (loading || selectedGroupKey === null || selectedAnimeId !== null) return; + if (!selectedGroup || selectedGroup.parts.length < 2) setSelectedGroupKey(null); + }, [loading, selectedGroupKey, selectedAnimeId, selectedGroup]); const checkedEntries = checkedAnimeIds .map((animeId) => anime.find((entry) => entry.animeId === animeId)) .filter((entry): entry is (typeof anime)[number] => entry !== undefined);