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.
This commit is contained in:
sudacode committed 2026-11-22 14:37:03 -08:00
1 parent 55110fd592
commit 4a78b946d9
5 files changed
+122 -18

No files matched your search

@@ -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]]); 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 () => { test('walk respects the depth and fetch bounds', async () => {
const chain = Array.from({ length: 10 }, (_, i) => const chain = Array.from({ length: 10 }, (_, i) =>
entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []), entry(i + 1, 'TV', 20000101 + i, i < 9 ? [['SEQUEL', i + 2]] : []),
+22 -15
View File
@@ -154,6 +154,8 @@ export interface FranchiseWalkOptions {
maxDepth: number; maxDepth: number;
/** Most entries fetched in one walk; the rest wait for the next walk. */ /** Most entries fetched in one walk; the rest wait for the next walk. */
maxFetch: number; maxFetch: number;
/** When true, the walk starts no further request and drops an in-flight result. */
isCancelled?: () => boolean;
} }
export interface FranchiseWalkResult { export interface FranchiseWalkResult {
@@ -174,9 +176,12 @@ export async function walkFranchiseRelations(
): Promise<FranchiseWalkResult> { ): Promise<FranchiseWalkResult> {
const { known } = options; const { known } = options;
const visited = new Set<number>(); const visited = new Set<number>();
let frontier: Array<{ id: number; from: number | null }> = [...new Set(options.seeds)].map( // `from` lists every entry the walk reached this one through at this depth
(id) => ({ id, from: null }), // (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 fetched = 0;
let truncated = false; let truncated = false;
@@ -193,10 +198,11 @@ export async function walkFranchiseRelations(
if (allowed.length < stale.length) truncated = true; if (allowed.length < stale.length) truncated = true;
for (let start = 0; start < allowed.length; start += FETCH_CHUNK_SIZE) { 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 chunk = allowed.slice(start, start + FETCH_CHUNK_SIZE);
const found = new Map( const fetchedNodes = await options.fetchNodes(chunk);
(await options.fetchNodes(chunk)).map((node) => [node.anilistId, node] as const), if (options.isCancelled?.()) return { fetched, truncated: true };
); const found = new Map(fetchedNodes.map((node) => [node.anilistId, node] as const));
const fetchedAtMs = options.now(); const fetchedAtMs = options.now();
const batch = chunk.map((id): AnilistMediaNode => { const batch = chunk.map((id): AnilistMediaNode => {
const node = found.get(id); const node = found.get(id);
@@ -222,21 +228,22 @@ export async function walkFranchiseRelations(
if (depth >= options.maxDepth) break; if (depth >= options.maxDepth) break;
const next: Array<{ id: number; from: number | null }> = []; const next = new Map<number, number[]>();
const queued = new Set<number>();
for (const step of frontier) { for (const step of frontier) {
const node = known.get(step.id); const node = known.get(step.id);
if (!node) continue; if (!node) continue;
// Reached through a link the entry itself rejects (a spin-off's original): // Reached only through links the entry itself rejects (a spin-off's
// it is not part of the franchise, so its own links are not followed. // original): it is not part of the franchise, so its own links are not
if (step.from !== null && vetoes(node, step.from)) continue; // 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)) { for (const targetId of franchiseTargets(node)) {
if (visited.has(targetId) || queued.has(targetId)) continue; if (visited.has(targetId)) continue;
queued.add(targetId); const from = next.get(targetId);
next.push({ id: targetId, from: node.anilistId }); if (from) from.push(node.anilistId);
else next.set(targetId, [node.anilistId]);
} }
} }
frontier = next; frontier = [...next].map(([id, from]) => ({ id, from }));
} }
return { fetched, truncated }; return { fetched, truncated };
@@ -64,9 +64,8 @@ export function createFranchiseRelationRefresher(
known, known,
isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS, isFresh: (node) => now() - node.fetchedAtMs < FRANCHISE_RELATION_STALE_MS,
fetchNodes: (ids) => deps.fetcher.fetchMedia(ids), fetchNodes: (ids) => deps.fetcher.fetchMedia(ids),
onBatch: (nodes) => { onBatch: (nodes) => writeAnilistRelationNodes(deps.db, nodes),
if (!stopped) writeAnilistRelationNodes(deps.db, nodes); isCancelled: () => stopped,
},
now, now,
maxDepth: FRANCHISE_WALK_MAX_DEPTH, maxDepth: FRANCHISE_WALK_MAX_DEPTH,
maxFetch: FRANCHISE_WALK_MAX_FETCH, maxFetch: FRANCHISE_WALK_MAX_FETCH,
@@ -132,3 +132,47 @@ test('a franchise card opens its parts in release order, and a part can stand al
uninstallDom(); 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(<AnimeTab />));
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();
}
});
+7
View File
@@ -161,6 +161,13 @@ export function AnimeTab({
0, 0,
); );
const selectedGroup = groups.find((group) => group.groupKey === selectedGroupKey) ?? null; 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 const checkedEntries = checkedAnimeIds
.map((animeId) => anime.find((entry) => entry.animeId === animeId)) .map((animeId) => anime.find((entry) => entry.animeId === animeId))
.filter((entry): entry is (typeof anime)[number] => entry !== undefined); .filter((entry): entry is (typeof anime)[number] => entry !== undefined);