diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f94d7ea..7a073167 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,7 +66,13 @@ jobs: - name: Install mpv and ffmpeg (Windows) if: runner.os == 'Windows' run: | - choco install mpv ffmpeg -y --no-progress + # community.chocolatey.org has short 503/504 outages, so retry before failing the job. + for attempt in 1 2 3 4; do + choco install mpv ffmpeg -y --no-progress && break + if [ "$attempt" -eq 4 ]; then exit 1; fi + echo "choco install failed (attempt $attempt), retrying in $((attempt * 30))s" + sleep $((attempt * 30)) + done # The mpv package adds no shim, so put its directory on PATH for later steps. mpv_exe="$(find /c/ProgramData/chocolatey/lib /c/ProgramData/chocolatey/bin "/c/Program Files" /c/tools -maxdepth 6 -iname mpv.exe 2>/dev/null | head -n 1)" test -n "$mpv_exe" diff --git a/changes/anki-poll-mining-race.md b/changes/anki-poll-mining-race.md new file mode 100644 index 00000000..8a1f28b5 --- /dev/null +++ b/changes/anki-poll-mining-race.md @@ -0,0 +1,4 @@ +type: fixed +area: anki + +- Fixed mined cards occasionally being dropped with an "Anki update already in progress" notification. The background AnkiConnect check for new cards no longer blocks mining while it waits on Anki. diff --git a/src/anki-integration/polling.test.ts b/src/anki-integration/polling.test.ts index 5166f98c..5cce99fc 100644 --- a/src/anki-integration/polling.test.ts +++ b/src/anki-integration/polling.test.ts @@ -173,3 +173,90 @@ test('a failed source lookup skips plugin events without stopping counting or en assert.deepEqual(h.ready, []); assert.equal(h.warnings.length, 2); }); + +/** A runner whose `findNotes` read stays pending until `finishRead`, sharing one update lock. */ +function makeSlowReadRunner() { + const state = { updating: false, processed: [] as number[], tracked: new Set() }; + let finishRead: (noteIds: number[]) => void = () => undefined; + const runner = new PollingRunner({ + getDeck: () => 'Mining', + getPollingRate: () => 3000, + findNotes: (query) => + query.includes('tag:') + ? Promise.resolve([]) + : new Promise((resolve) => { + finishRead = resolve; + }), + shouldAutoUpdateNewCards: () => true, + processNewCard: async (noteId) => { + state.processed.push(noteId); + }, + isUpdateInProgress: () => state.updating, + setUpdateInProgress: (value) => { + state.updating = value; + }, + getTrackedNoteIds: () => state.tracked, + setTrackedNoteIds: (noteIds) => { + state.tracked = noteIds; + }, + showStatusNotification: () => undefined, + logDebug: () => undefined, + logInfo: () => undefined, + logWarn: () => undefined, + }); + return { + runner, + state, + finishRead: (noteIds: number[]) => finishRead(noteIds), + /** The first poll only records the notes already in the deck. */ + initialize: async () => { + const poll = runner.pollOnce(); + finishRead([10]); + await poll; + }, + }; +} + +test('a poll waiting on Anki leaves the update lock free for mining', async () => { + const h = makeSlowReadRunner(); + await h.initialize(); + + const poll = h.runner.pollOnce(); + assert.equal(h.state.updating, false, 'mining can start while the read is pending'); + h.finishRead([10, 11]); + await poll; + + assert.deepEqual(h.state.processed, [11]); + assert.equal(h.state.updating, false); +}); + +test('a poll leaves new notes alone when mining starts during its read', async () => { + const h = makeSlowReadRunner(); + await h.initialize(); + + const poll = h.runner.pollOnce(); + // Mining takes the lock and adds note 11 while the poll's read is in flight. + h.state.updating = true; + h.finishRead([10, 11]); + await poll; + + assert.deepEqual(h.state.processed, []); + assert.deepEqual([...h.state.tracked], [10]); + assert.equal(h.state.updating, true, 'the poll must not release a lock it never took'); +}); + +test('the first poll keeps notes mined while its read was pending', async () => { + const h = makeSlowReadRunner(); + + const init = h.runner.pollOnce(); + // Mining finishes during the initial read and tracks note 11, which the read missed. + h.state.tracked.add(11); + h.finishRead([10]); + await init; + + const poll = h.runner.pollOnce(); + h.finishRead([10, 11]); + await poll; + + assert.deepEqual(h.state.processed, []); +}); diff --git a/src/anki-integration/polling.ts b/src/anki-integration/polling.ts index fde0d29a..2adea416 100644 --- a/src/anki-integration/polling.ts +++ b/src/anki-integration/polling.ts @@ -26,6 +26,8 @@ export interface PollingRunnerDeps { export class PollingRunner { private pollingInterval: ReturnType | null = null; + // Keeps interval ticks from stacking up behind a slow read, now that reads skip the update lock. + private pollInFlight = false; private initialized = false; private backoffMs = 200; private maxBackoffMs = 5000; @@ -56,19 +58,29 @@ export class PollingRunner { } async pollOnce(): Promise { - if (this.deps.isUpdateInProgress()) return; + if (this.pollInFlight || this.deps.isUpdateInProgress()) return; if (Date.now() < this.nextPollTime) return; - this.deps.setUpdateInProgress(true); + this.pollInFlight = true; + let holdsUpdateLock = false; try { const query = this.deps.getDeck() ? `"deck:${this.deps.getDeck()}" added:1` : 'added:1'; + // The read runs without the update lock: mining checks that lock and gives up when it is + // held, so holding it for a routine poll would drop a card mined at the wrong moment. const noteIds = await this.deps.findNotes(query, { maxRetries: 0, }); + // An update started during the read (its creator tracks any note it adds), so leave the + // new notes to the next poll. + if (this.deps.isUpdateInProgress()) return; + this.deps.setUpdateInProgress(true); + holdsUpdateLock = true; const currentNoteIds = new Set(noteIds); const previousNoteIds = this.deps.getTrackedNoteIds(); if (!this.initialized) { + // Keep notes mined while the read was pending; the read may have started before they existed. + for (const noteId of previousNoteIds) currentNoteIds.add(noteId); this.deps.setTrackedNoteIds(currentNoteIds); this.initialized = true; this.deps.logInfo(`AnkiConnect initialized with ${currentNoteIds.size} existing cards`); @@ -140,7 +152,8 @@ export class PollingRunner { } this.deps.logWarn((error as Error).message); } finally { - this.deps.setUpdateInProgress(false); + this.pollInFlight = false; + if (holdsUpdateLock) this.deps.setUpdateInProgress(false); } }