flashcards: 'new cards per day' is now actually per day
- Commit
48888b67d2264fb78a4bfbc41ca431d443b430ad- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 21:42 UTC (5 days ago)
- Parents
76b9fef
The setting promised a daily cap, but the only consumer applied it per session: startSessionImpl passed deck.newPerDay verbatim as the session's .take() limit and nothing counted today's introductions, so restarting study sessions the same day served a fresh allowance every time (a 2/day deck could introduce 4+ in a day). The Deck KDoc even documented the buggy per-session semantics. The single session factory now computes today's introductions from the review log (distinct cards whose first-ever review is today — ReviewSession.newCardsIntroducedSince, pure) and passes (newPerDay - introducedToday) clamped at 0. Undo restores allowance since it deletes its log; custom-study modes don't use newPerDay and are unaffected. FSRS math, overdue handling, undo, media round-trips and stats were audited and cleared. Verified: :flashcards:testDevUnitTest 171 tests pass (new same-day regression failed pre-fix); lint errors are pre-existing on untouched files.
Diff
flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.ktindex 39af5aa408..8c1e93aef5 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/data/Deck.kt@@ -8,8 +8,10 @@ import kotlinx.serialization.Serializable /** * A deck of [Card]s plus its per-deck study configuration. *- * [newPerDay]/[maxReviewsPerDay] cap how many cards a session introduces, and- * [desiredRetention] (0..1) is the FSRS target recall probability that drives the+ * [newPerDay] caps how many new cards are introduced per calendar day across+ * all sessions (the session factory subtracts today's introductions from the+ * review log); [maxReviewsPerDay] caps how many review cards one session+ * serves. [desiredRetention] (0..1) is the FSRS target recall probability that drives the * scheduled intervals. [fsrsWeights] holds a JSON array of 19 FSRS doubles * (empty = use `Scheduler.DEFAULT_W`) and [leechThreshold] is the number of lapses * before a card is auto-suspended as a leech (0 = disabled).
flashcards/src/main/java/com/vayunmathur/flashcards/domain/ReviewSession.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/domain/ReviewSession.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/domain/ReviewSession.ktindex 4869c11411..b373bca960 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/domain/ReviewSession.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/domain/ReviewSession.kt@@ -4,13 +4,16 @@ import com.vayunmathur.flashcards.ui.StudyParams import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.data.CardState+import com.vayunmathur.flashcards.data.ReviewLog /** * An in-memory review queue for a single study session. Pure Kotlin (no Android * dependency) so it can be unit-tested directly. * * The queue is seeded from the deck's due cards, capped at [newPerDay] new cards- * and [maxReviews] review cards. Grading runs the [Scheduler]; cards that land in+ * (the *remaining* daily allowance: the session factory subtracts the new cards+ * already introduced today, see [newCardsIntroducedSince]) and [maxReviews]+ * review cards. Grading runs the [Scheduler]; cards that land in * a learning/relearning step (e.g. after `AGAIN`) are re-inserted a few positions * back so they resurface later in *this* session instead of dropping out, while * graduated cards leave the queue and count towards [progress].@@ -147,5 +150,17 @@ class ReviewSession( /** How many cards ahead a failed card is re-queued in a session. */ companion object { private const val RE_QUEUE_GAP = 3++ /**+ * Distinct cards whose first-ever review in [logs] happened at or after+ * [sinceMs]: the new cards already introduced in the current day, which+ * count against a deck's daily new-card limit. A card first reviewed+ * before [sinceMs] never counts, however often it was reviewed since,+ * and a card reviewed many times today counts once.+ */+ fun newCardsIntroducedSince(logs: List<ReviewLog>, sinceMs: Long): Int =+ logs.groupBy { it.cardId }.values.count { cardLogs ->+ cardLogs.minOf { it.reviewedAt } >= sinceMs+ } } }
flashcards/src/main/java/com/vayunmathur/flashcards/platform/FlashcardsSettingsOps.kt
diff --git a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/FlashcardsSettingsOps.kt b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/FlashcardsSettingsOps.ktindex 7d246b3b9b..5757d88a6e 100644--- a/flashcards/src/main/java/com/vayunmathur/flashcards/platform/FlashcardsSettingsOps.kt+++ b/flashcards/src/main/java/com/vayunmathur/flashcards/platform/FlashcardsSettingsOps.kt@@ -173,9 +173,21 @@ internal fun FlashcardsViewModel.startSessionImpl( allCards.filter { it.noteId in allowedNoteIds } } val now = System.currentTimeMillis()+ // newPerDay is a *daily* limit ("New cards per day"), not a per-session+ // one: subtract the new cards already introduced today (their first-ever+ // review is in today's log) so restarting a session cannot exceed it.+ // Explicit custom-study modes ignore newPerDay and are unaffected.+ val dayStartMs = java.time.LocalDate.now()+ .atStartOfDay(java.time.ZoneId.systemDefault())+ .toInstant()+ .toEpochMilli()+ val introducedToday = ReviewSession.newCardsIntroducedSince(+ repository.getReviewLogsByDeckOrderedImpl(deckId),+ dayStartMs,+ ) session = ReviewSession( cards = cards,- newPerDay = deck.newPerDay,+ newPerDay = (deck.newPerDay - introducedToday).coerceAtLeast(0), maxReviews = deck.maxReviewsPerDay, now = now, desiredRetention = deck.desiredRetention,
flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsNewPerDayTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsNewPerDayTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsNewPerDayTest.ktnew file mode 100644index 0000000000..93a14ebfd4--- /dev/null+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/util/FlashcardsNewPerDayTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.flashcards.util++// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+import android.app.Application+import android.os.Looper+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.flashcards.data.CardState+import com.vayunmathur.flashcards.data.FlashcardsDatabase+import com.vayunmathur.flashcards.data.FlashcardsRepository+import com.vayunmathur.flashcards.data.getCardsByDeckImpl+import com.vayunmathur.flashcards.data.getCardsByNoteImpl+import com.vayunmathur.flashcards.data.getReviewLogsByDeckOrderedImpl+import com.vayunmathur.flashcards.data.upsertCardsImpl+import com.vayunmathur.flashcards.domain.Grade+import com.vayunmathur.flashcards.platform.FlashcardsViewModel+import com.vayunmathur.flashcards.platform.addDeckImpl+import com.vayunmathur.flashcards.platform.gradeCurrentImpl+import com.vayunmathur.flashcards.platform.saveNoteImpl+import com.vayunmathur.flashcards.platform.startSessionImpl+import com.vayunmathur.flashcards.platform.upsertDeckImpl+import com.vayunmathur.library.util.databases+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Regression coverage for the daily new-card limit:+ * [com.vayunmathur.flashcards.data.Deck.newPerDay] ("New cards per day") must+ * hold across study sessions started on the same day, not reset per session.+ */+@RunWith(RobolectricTestRunner::class)+class FlashcardsNewPerDayTest {++ private lateinit var app: Application+ private lateinit var repo: FlashcardsRepository+ private lateinit var vm: FlashcardsViewModel+ private lateinit var scope: CoroutineScope++ @BeforeTest+ fun setUp() {+ app = ApplicationProvider.getApplicationContext<Application>()+ val mem = Room.inMemoryDatabaseBuilder(app, FlashcardsDatabase::class.java)+ .allowMainThreadQueries().build()+ synchronized(databases) { databases[FlashcardsDatabase::class] = mem }+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ repo = FlashcardsRepository.get(app)+ vm = FlashcardsViewModel(app, repo)+ scope = CoroutineScope(Dispatchers.Default + Job())+ scope.launch { vm.noteTypes.collect {} }+ scope.launch { vm.decks.collect {} }+ scope.launch { vm.cards.collect {} }+ scope.launch { vm.notes.collect {} }+ scope.launch { vm.settings.collect {} }+ await("built-in note types fully loaded") {+ val byId = vm.noteTypes.value.associateBy { it.noteType.id }+ byId[1L]?.fields?.map { it.name } == listOf("Front", "Back") &&+ byId[1L]?.templates?.size == 1 &&+ byId[2L]?.fields?.map { it.name } == listOf("Front", "Back") &&+ byId[2L]?.templates?.size == 2 &&+ byId[3L]?.fields?.size == 2 &&+ byId[3L]?.templates?.size == 1+ }+ }++ private fun await(label: String, condition: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 20_000+ while (System.currentTimeMillis() < deadline) {+ shadowOf(Looper.getMainLooper()).idle()+ if (condition()) return+ Thread.sleep(50)+ }+ error("timed out waiting for $label: decks=${vm.decks.value} types=${vm.noteTypes.value.size}")+ }++ private fun deckWithNewLimit(name: String, newPerDay: Int): Long {+ vm.addDeckImpl(name)+ await("deck $name") { vm.decks.value.any { it.name == name } }+ val deck = vm.decks.value.first { it.name == name }+ vm.upsertDeckImpl(deck.copy(newPerDay = newPerDay, maxReviewsPerDay = 200))+ await("deck $name limit applied") {+ vm.decks.value.any { it.id == deck.id && it.newPerDay == newPerDay }+ }+ return deck.id+ }++ private fun saveNote(deckId: Long, front: String) {+ vm.saveNoteImpl(0, FlashcardsViewModel.BASIC_NOTE_TYPE_ID, deckId, listOf(front, "back-$front"), "")+ await("note $front cards") {+ val noteId = vm.notes.value+ .firstOrNull { it.sortField == front && it.deckId == deckId }?.id ?: -1L+ noteId > 0 && runBlocking { repo.getCardsByNoteImpl(noteId) }.isNotEmpty()+ }+ }++ @Test+ fun newPerDayLimitHoldsAcrossSessionsOnTheSameDay() {+ val deckId = deckWithNewLimit("DailyLimitDeck", newPerDay = 2)+ listOf("DailyA", "DailyB", "DailyC", "DailyD", "DailyE").forEach { saveNote(deckId, it) }++ // First session: exactly the daily allowance of new cards is served.+ vm.startSessionImpl(deckId)+ await("first session serves 2 new cards") { vm.review.value.newCount == 2 }+ assertEquals(2, vm.review.value.newCount)++ // Introduce both: each grades GOOD and leaves the NEW state for good.+ vm.gradeCurrentImpl(Grade.GOOD)+ await("first introduction logged") {+ runBlocking { repo.getReviewLogsByDeckOrderedImpl(deckId) }.size == 1+ }+ vm.gradeCurrentImpl(Grade.GOOD)+ await("second introduction logged") {+ runBlocking { repo.getReviewLogsByDeckOrderedImpl(deckId) }.size == 2+ }++ // Make one introduced card due again so the next session is observably+ // non-empty (a graded review card is on screen), independent of new cards.+ val introduced = runBlocking { repo.getCardsByDeckImpl(deckId) }+ .first { it.state == CardState.REVIEW }+ runBlocking {+ repo.upsertCardsImpl(+ listOf(introduced.copy(dueDate = System.currentTimeMillis() - 1_000)),+ )+ }++ // A second session on the same day must serve no further new cards:+ // today's allowance of 2 has already been introduced.+ vm.startSessionImpl(deckId)+ await("second session shows the due review") { vm.review.value.reviewCount == 1 }+ assertEquals(1, vm.review.value.reviewCount)+ assertEquals(+ 0,+ vm.review.value.newCount,+ "second same-day session must not exceed the daily new-card limit",+ )++ // The three untouched cards are still NEW (never introduced).+ assertEquals(+ 3,+ vm.cards.value.count { it.deckId == deckId && it.state == CardState.NEW },+ )+ }+}
flashcards/src/test/java/com/vayunmathur/flashcards/util/ReviewSessionTest.kt
diff --git a/flashcards/src/test/java/com/vayunmathur/flashcards/util/ReviewSessionTest.kt b/flashcards/src/test/java/com/vayunmathur/flashcards/util/ReviewSessionTest.ktindex e3b89e0e78..c934ca2b0d 100644--- a/flashcards/src/test/java/com/vayunmathur/flashcards/util/ReviewSessionTest.kt+++ b/flashcards/src/test/java/com/vayunmathur/flashcards/util/ReviewSessionTest.kt@@ -7,6 +7,7 @@ import com.vayunmathur.flashcards.ui.StudyParams import com.vayunmathur.flashcards.data.Card import com.vayunmathur.flashcards.data.CardState+import com.vayunmathur.flashcards.data.ReviewLog import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull@@ -147,6 +148,29 @@ class ReviewSessionTest { assertTrue(session.previewOnly) } + private fun log(cardId: Long, reviewedAt: Long) = ReviewLog(+ cardId = cardId, deckId = 1, reviewedAt = reviewedAt,+ grade = 3, elapsedDays = 0.0, scheduledDays = 1.0, state = 2,+ )++ @Test+ fun introducedTodayCountsOnlyCardsFirstReviewedToday() {+ val dayStart = now - 12 * 60 * 60 * 1000L // earlier today+ val yesterday = dayStart - Scheduler.DAY_MS+ val logs = listOf(+ // Introduced today, then re-reviewed in a learning step: counts once.+ log(cardId = 1, reviewedAt = dayStart + 1_000),+ log(cardId = 1, reviewedAt = dayStart + 61_000),+ // Introduced yesterday, reviewed again today: not a new introduction.+ log(cardId = 2, reviewedAt = yesterday),+ log(cardId = 2, reviewedAt = dayStart + 2_000),+ // At the boundary: exactly at day start counts as today.+ log(cardId = 3, reviewedAt = dayStart),+ )+ assertEquals(2, ReviewSession.newCardsIntroducedSince(logs, dayStart))+ assertEquals(0, ReviewSession.newCardsIntroducedSince(emptyList(), dayStart))+ }+ @Test fun lapsesModeSelectsLapsedCards() { val lapsed = dueReviewCard(1).copy(lapses = 2)