news: speed up initial news.json load
- Commit
f4eb56e0033eae47d761b4a0780d6ae56ef6800b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 03:02 UTC (4 days ago)
- Parents
c398e51
Owner reported the news app is really slow to load news.json initially. Measured the initial-load path with a realistic 2,500-article fixture (the live feed on 2026-12-02 is 983 KB, 2,500 articles, 11,378 catalog sources at runtime): - ServerFeedParser.parse took 68-86 ms on the dev VM, of which ~60 ms was SourceCatalog.byId alone: byId/byName resolution was a linear scan over all 11,378 sources for every article, and the same scan ran per article in toFeedArticle, per story in grouping/category checks, and per rendered row. On a phone CPU this is several hundred milliseconds before the first frame, and it grows with every catalog scale-up. - The catalog itself costs ~178 ms to cold-load (Brotli + TSV). - A full server refresh (parse + FeedMerger + Room upsert of the capped 500 + prune) took 136-191 ms warm and ran in full on every cold start even when the feed was byte-identical: no generated_at/ETag/timestamp check existed, every row got a new fetchedAtMillis, Room re-emitted the whole feed, and the ViewModel re-grouped/re-ranked it on the main thread. Fixes, all inside news/ with no feed-contract or R2 change: - SourceCatalog builds by-id and by-name index maps once at first use; byId is now a map lookup. ServerFeedParser resolves each article's source once and reuses it for the language default. Parse of the benchmark fixture: 68-86 ms -> 9-21 ms, byId x2,500: 60 ms -> ~0 ms. Merge (2-4 ms) and group+rank (1-3 ms) were measured and left alone. - ServerFeedParser.feedStamp reads generated_at from a bounded 1 KB prefix scan. NewsRepository compares it with the stamp NewsPrefs persists for the last merged feed (plus an in-process copy) and skips parsing and the Room re-publish entirely when unchanged, so repeat cold starts within a server publishing cycle show the cached feed with no re-merge work. - NewsRepository.publish writes nothing when the batch already equals the cache (fetchedAtMillis excluded), so a regenerated but identical feed does not re-emit/re-group the whole list. DAO gains a one-shot allArticles snapshot for that comparison. - NewsViewModel runs story grouping and the by-URL cache map on Dispatchers.Default via flowOn instead of the main thread, so the cached feed's first frame never waits on grouping. Tests: new FeedLoadBenchmarkTest times parse+merge+group over the 2,500-article fixture and pins the counts; ServerFeedParserTest covers feedStamp; NewsServerFeedTest proves a fresh repository with the persisted stamp does not rewrite rows (fetchedAtMillis unchanged). news/AGENTS.md documents the stamp skip, indexed lookups, and off-main grouping. Verified: :news:lint green, :news:lintVitalRelease green, :news:testDevUnitTest green (91 tests, 0 failures).
Diff
news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex fafc51899a..c51bc4ffb3 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -18,7 +18,13 @@ server's background refresh on every cycle; there is no news endpoint on the origin — see `domain/ServerFeedParser` for the contract + assumptions). When the static copy is missing, failing, or older than 1 hour, refresh falls back to the on-device crawl below; the-result is merged into Room. Every source is always in the+result is merged into Room. A refresh whose downloaded `generated_at`+matches the last-merged stamp persisted by `NewsPrefs` skips parsing+and the Room re-publish entirely — the cached feed already shows+exactly those articles — and a batch identical to the cache writes+nothing. Catalog lookups (`SourceCatalog.byId`/`byName`) are indexed+maps built once at first use, not scans over the whole catalog, and+story grouping over the Room cache runs off the main thread. Every source is always in the corpus (no per-source toggle); category + search are the filters, and `domain/FeedRanking` orders the story feed client-side by descending source count, then newest first (search keeps its relevance order).
news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.ktindex a4de5d4570..2d46a1589c 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt@@ -56,6 +56,10 @@ interface NewsDao { @Query("SELECT * FROM CachedArticle WHERE url = :url") suspend fun article(url: String): CachedArticle? + /** One-shot snapshot of the whole cache (publish compares against it to skip no-op writes). */+ @Query("SELECT * FROM CachedArticle")+ suspend fun allArticles(): List<CachedArticle>+ /** Bookmarked subset of [urls], in one query (publish must not query per article). */ @Query("SELECT url FROM CachedArticle WHERE bookmarked = 1 AND url IN (:urls)") suspend fun bookmarkedUrls(urls: List<String>): List<String>
news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.ktindex 7904639c14..66feebf242 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt@@ -39,16 +39,33 @@ class NewsPrefs(context: Context) { /** * Manually picked Local news location (a catalog region string or a- * free place name the user typed); null when unset, in which case- * Local shows nothing. This is a preference only — never device+ * free place name the user typed); null when unset, in which case all+ * local sources are equal. This is a preference only — never device * location. Blank stored values read as unset. */ val localLocation: Flow<String?> = safeData.map { it[LOCAL_LOCATION]?.takeIf { v -> v.isNotBlank() } } - /** Drops retired per-source preference state, if an old install left any. */+ /**+ * `generated_at` stamp of the server feed last merged into Room.+ * A refresh whose downloaded feed carries the same stamp skips the+ * parse and Room re-publish entirely (see NewsRepository); null+ * until the first successful server-feed merge.+ */+ val serverFeedStamp: Flow<String?> = safeData.map { it[SERVER_FEED_STAMP]?.takeIf { v -> v.isNotBlank() } }++ /** Persists the last-merged server feed stamp; null or blank clears it. */+ suspend fun setServerFeedStamp(stamp: String?) {+ appContext.newsDataStore.edit { prefs ->+ val trimmed = stamp?.trim().orEmpty()+ if (trimmed.isEmpty()) prefs.remove(SERVER_FEED_STAMP) else prefs[SERVER_FEED_STAMP] = trimmed+ }+ }++ /** Drops retired preference state, if an old install left any. */ suspend fun clearLegacySourcePrefs() { appContext.newsDataStore.edit { prefs -> if (prefs.contains(LEGACY_DISABLED_SOURCES)) prefs.remove(LEGACY_DISABLED_SOURCES)+ if (prefs.contains(LEGACY_FEED_SORT)) prefs.remove(LEGACY_FEED_SORT) } } @@ -73,7 +90,9 @@ class NewsPrefs(context: Context) { const val MIN_TEXT_SP = 13 const val MAX_TEXT_SP = 24 private val LEGACY_DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")+ private val LEGACY_FEED_SORT = stringPreferencesKey("feed_sort") private val LOCAL_LOCATION = stringPreferencesKey("local_location")+ private val SERVER_FEED_STAMP = stringPreferencesKey("server_feed_stamp") private val TEXT_SP = intPreferencesKey("reader_text_sp") private val SERIF = booleanPreferencesKey("reader_serif") }
news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.ktindex 91a798f3b3..71db088655 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -21,6 +21,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.builtins.ListSerializer@@ -49,9 +50,15 @@ class NewsRepository internal constructor( private val feedDispatcher: CoroutineDispatcher = Dispatchers.Default, private val sourceTimeoutMs: Long = SOURCE_TIMEOUT_MS, private val serverFeedFetch: suspend () -> String = { Networking.fetchServerFeedText() },+ private val prefs: NewsPrefs? = null, ) : RoomRepository<NewsDatabase>(context, NewsDatabase::class, DB_NAME) { - constructor(context: Context) : this(context, Networking::fetchText)+ constructor(context: Context) : this(+ context, Networking::fetchText, prefs = NewsPrefs(context),+ )++ /** Stamp of the feed this process already merged (cold-start persistence is [prefs]). */+ @Volatile private var mergedFeedStamp: String? = null private val dao get() = db.newsDao() private val json = Json { ignoreUnknownKeys = true }@@ -81,11 +88,18 @@ class NewsRepository internal constructor( * fallback) returns an empty list. */ suspend fun refresh(sources: List<NewsSource>): List<String> {- val serverArticles = fetchServerFeed()- if (serverArticles != null) {- val capped = FeedMerger.merge(listOf(serverArticles), limit = MAX_CACHED_ARTICLES)- if (capped.isNotEmpty()) publish(capped)- dao.pruneArticles(keep = MAX_CACHED_ARTICLES)+ val serverFeed = fetchServerFeed()+ if (serverFeed != null) {+ if (serverFeed.unchanged) {+ Log.dev(TAG, "refresh server feed unchanged stamp=${serverFeed.stamp}; skipping merge")+ return emptyList()+ }+ val capped = FeedMerger.merge(listOf(serverFeed.articles), limit = MAX_CACHED_ARTICLES)+ if (capped.isNotEmpty()) {+ publish(capped)+ dao.pruneArticles(keep = MAX_CACHED_ARTICLES)+ }+ if (capped.isNotEmpty()) rememberFeedStamp(serverFeed.stamp) Log.dev(TAG, "refresh server feed landed articles=${capped.size}") return emptyList() }@@ -93,11 +107,38 @@ class NewsRepository internal constructor( return refreshFromSources(sources) } - /** Server feed articles, or null on transport failure / timeout / empty parse. */- private suspend fun fetchServerFeed(): List<FeedArticle>? {- val articles = try {+ /** A fetched server feed: parsed [articles], or [unchanged] when its stamp is already merged. */+ private class ServerFeed(val articles: List<FeedArticle>, val stamp: String?, val unchanged: Boolean)++ private suspend fun rememberFeedStamp(stamp: String?) {+ if (stamp == null) return+ mergedFeedStamp = stamp+ runCatching { prefs?.setServerFeedStamp(stamp) }+ }++ private suspend fun knownFeedStamp(): String? =+ mergedFeedStamp ?: prefs?.let { runCatching { it.serverFeedStamp.first() }.getOrNull() }+ ?.also { mergedFeedStamp = it }++ /**+ * Server feed, or null on transport failure / timeout / empty parse.+ * When the downloaded document's `generated_at` stamp matches the+ * last merged feed, parsing (the expensive step at 11k+ catalog+ * sources) and the Room re-publish are skipped entirely: the cached+ * feed already shows exactly these articles.+ */+ private suspend fun fetchServerFeed(): ServerFeed? {+ val fetched = try { withTimeoutOrNull(sourceTimeoutMs) {- withContext(feedDispatcher) { ServerFeedParser.parse(serverFeedFetch()) }+ withContext(feedDispatcher) {+ val text = serverFeedFetch()+ val stamp = ServerFeedParser.feedStamp(text)+ if (stamp != null && stamp == knownFeedStamp()) {+ ServerFeed(emptyList(), stamp, unchanged = true)+ } else {+ ServerFeed(ServerFeedParser.parse(text), stamp, unchanged = false)+ }+ } } } catch (e: CancellationException) { throw e@@ -105,7 +146,7 @@ class NewsRepository internal constructor( Log.dev(TAG, "server feed failed ${e.javaClass.simpleName}") null }- return articles?.takeIf { it.isNotEmpty() }+ return fetched?.takeIf { it.unchanged || it.articles.isNotEmpty() } } /**@@ -188,8 +229,14 @@ class NewsRepository internal constructor( return null } - /** Upserts one landed source's articles, preserving existing bookmark flags. */- private suspend fun publish(articles: List<FeedArticle>) {+ /**+ * Upserts one landed batch, preserving existing bookmark flags.+ * Returns false (and writes nothing) when the batch is already the+ * cached content: re-writing identical rows on every cold start+ * would re-emit the whole feed and re-run grouping for no change.+ * `fetchedAtMillis` is excluded from the comparison for that check.+ */+ private suspend fun publish(articles: List<FeedArticle>): Boolean { val now = System.currentTimeMillis() val bookmarked = dao.bookmarkedUrls(articles.map { it.url }).toSet() val rows = articles.map { article ->@@ -202,7 +249,13 @@ class NewsRepository internal constructor( storyTitle = article.serverStoryTitle, ) }+ val existingByUrl = dao.allArticles().associateBy { it.url }+ val unchanged = rows.all { row ->+ existingByUrl[row.url]?.let { it.copy(fetchedAtMillis = row.fetchedAtMillis) == row } == true+ }+ if (unchanged) return false dao.upsertArticles(rows)+ return true } /**
news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.ktindex fdc125226d..b1d8e7e817 100644--- a/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt@@ -67,11 +67,33 @@ object ServerFeedParser { } } + /**+ * The document's `generated_at` stamp, read without parsing the whole+ * document: it sits in the prologue before `articles`, so a bounded+ * prefix scan finds it. The repository uses this as the feed's identity:+ * an unchanged stamp means the (potentially large) article array is the+ * one already merged into Room, so re-parsing and re-publishing it on+ * every cold start is skipped. Null when absent or not in the prefix.+ */+ fun feedStamp(text: String): String? {+ val prefix = text.substring(0, minOf(text.length, STAMP_SCAN_CHARS))+ val key = prefix.indexOf("\"generated_at\"")+ if (key < 0) return null+ val colon = prefix.indexOf(':', key)+ if (colon < 0) return null+ val start = prefix.indexOf('"', colon)+ if (start < 0) return null+ val end = prefix.indexOf('"', start + 1)+ if (end < 0) return null+ return prefix.substring(start + 1, end).takeIf { it.isNotEmpty() }+ }+ private fun parseArticle(obj: JsonObject): FeedArticle? { val url = obj.string("url")?.takeIf { it.startsWith("http") } ?: return null val title = obj.string("title")?.takeIf { it.isNotBlank() } ?: return null val sourceRaw = obj.string("source")?.takeIf { it.isNotBlank() } ?: return null- val sourceId = resolveSourceId(sourceRaw)+ val source = resolveSource(sourceRaw)+ val sourceId = source?.id ?: sourceRaw.trim() return FeedArticle( url = url, sourceId = sourceId,@@ -79,7 +101,7 @@ object ServerFeedParser { publishedAtMillis = parsePublishedAt(obj["published_at"]), imageUrl = obj.string("image_url"), metered = (obj["metered"] as? JsonPrimitive)?.contentOrNull?.toBooleanStrictOrNull() ?: false,- language = obj.string("language") ?: SourceCatalog.byId(sourceId)?.language,+ language = obj.string("language") ?: source?.language, serverStoryId = obj.string("story_id"), storyOneLiner = obj.string("story_one_liner") ?: obj.string("story_oneliner") ?: obj.string("story_summary"),@@ -88,12 +110,16 @@ object ServerFeedParser { } /** Catalog id for a catalog id or exact catalog name; otherwise [raw] verbatim. */- fun resolveSourceId(raw: String): String {+ fun resolveSourceId(raw: String): String = resolveSource(raw)?.id ?: raw.trim()++ /** Catalog source for a catalog id or exact catalog name; null when unresolved (kept verbatim). */+ fun resolveSource(raw: String): NewsSource? { val trimmed = raw.trim()- SourceCatalog.byId(trimmed)?.let { return it.id }- return SourceCatalog.sources.firstOrNull { it.name.equals(trimmed, ignoreCase = true) }?.id ?: trimmed+ return SourceCatalog.byId(trimmed) ?: SourceCatalog.byName(trimmed) } + private const val STAMP_SCAN_CHARS = 1024+ private fun parsePublishedAt(element: kotlinx.serialization.json.JsonElement?): Long { val primitive = element as? JsonPrimitive ?: return 0L if (primitive.isString) return DateParsing.parseMillis(primitive.contentOrNull) ?: 0L
news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt b/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.ktindex c1147a64f3..2b42e9c1b7 100644--- a/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt@@ -66,7 +66,20 @@ object SourceCatalog { val sources: List<NewsSource> by lazy { loadCatalog() } - fun byId(id: String): NewsSource? = sources.firstOrNull { it.id == id }+ // Indexes built once at first lookup: byId/byName are called per article+ // during feed parsing and per row in the UI, so a linear scan over the+ // whole catalog (11k+ sources) per call dominated initial feed load.+ private val byIdIndex: Map<String, NewsSource> by lazy { sources.associateBy { it.id } }+ private val byNameIndex: Map<String, NewsSource> by lazy {+ val byName = LinkedHashMap<String, NewsSource>()+ for (source in sources) byName.putIfAbsent(source.name.lowercase(), source)+ byName+ }++ fun byId(id: String): NewsSource? = byIdIndex[id]++ /** Source whose display name matches [name] case-insensitively (trimmed); first wins on duplicates. */+ fun byName(name: String): NewsSource? = byNameIndex[name.trim().lowercase()] /** Category tags for [sourceId]; empty for an id not in the catalog. */ fun categoriesOf(sourceId: String): List<NewsCategory> = byId(sourceId)?.categories.orEmpty()
news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt
diff --git a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.ktindex 30eddb3a11..653191bb81 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -16,11 +16,13 @@ import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.domain.Story import com.vayunmathur.news.domain.StoryGrouping import com.vayunmathur.news.domain.orderedBySearchHits+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch@@ -56,9 +58,15 @@ class NewsViewModel( val localLocation: StateFlow<String?> = prefs.localLocation .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) - /** All stories over the full cache (unfiltered), grouped once per emission. */+ /**+ * All stories over the full cache (unfiltered), grouped once per+ * emission. Grouping (with its per-article catalog lookups) runs on+ * Dispatchers.Default via flowOn, never on Main: the cached feed's+ * first frame must not wait on it.+ */ val allStories: StateFlow<List<Story>> = repository.articles .map { all -> StoryGrouping.group(all.map { it.toFeedArticle() }) }+ .flowOn(Dispatchers.Default) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) private val _searchQuery = MutableStateFlow("")@@ -119,6 +127,7 @@ class NewsViewModel( /** Cached lookup by article URL, for story cards/pages. */ val cachedByUrl: StateFlow<Map<String, CachedArticle>> = repository.articles .map { all -> all.associateBy { it.url } }+ .flowOn(Dispatchers.Default) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) /** Representative articles in feed order (kept for existing callers/tests). */
news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.ktindex ff659a95ea..7fa1dfa858 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt@@ -57,6 +57,28 @@ class NewsServerFeedTest { assertTrue(cached.any { it.title == "Server Alpha Volcano" }) } + @Test fun unchangedFeedStampSkipsRepublishAcrossRepositoryInstances() = runBlocking {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val prefs = NewsPrefs(context)+ prefs.setServerFeedStamp(null)+ val repo = NewsRepository(context, fetch = { serverJson }, serverFeedFetch = { serverJson }, prefs = prefs)+ repo.refresh(SourceCatalog.sources)+ val first = withTimeout(10_000) {+ repo.articles.first { a -> a.any { it.url == "https://srv.example/alpha" } }+ }+ val fetchedAt = first.first { it.url == "https://srv.example/alpha" }.fetchedAtMillis+ // A fresh repository (cold start) with the persisted stamp must not+ // re-parse/re-write the identical feed: fetchedAt stays untouched.+ val repo2 = NewsRepository(context, fetch = { serverJson }, serverFeedFetch = { serverJson }, prefs = prefs)+ assertTrue(repo2.refresh(SourceCatalog.sources).isEmpty())+ val second = repo2.articles.first { a -> a.any { it.url == "https://srv.example/alpha" } }+ assertEquals(+ fetchedAt, second.first { it.url == "https://srv.example/alpha" }.fetchedAtMillis,+ "unchanged generated_at stamp must skip the Room re-publish",+ )+ prefs.setServerFeedStamp(null)+ }+ @Test fun staticFeedUrlIsTheOnlyDistributionCopy() { // The contract the server publishes to (location_share_server // NEWS_R2_KEY). There is no origin news endpoint and no origin
news/src/test/java/com/vayunmathur/news/domain/FeedLoadBenchmarkTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/FeedLoadBenchmarkTest.kt b/news/src/test/java/com/vayunmathur/news/domain/FeedLoadBenchmarkTest.ktnew file mode 100644index 0000000000..2f327fbc0a--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/FeedLoadBenchmarkTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals++/** Local timing harness: realistic 2,500-article feed (real size 2026-12-02). */+class FeedLoadBenchmarkTest {+ @Test fun benchmarkParseMergeGroup() {+ val ids = SourceCatalog.sources.map { it.id }+ println("BENCH catalog sources=${ids.size}")+ // Worst-realistic: sources spread across whole catalog (late ids scan farthest)+ val sb = StringBuilder()+ sb.append("{\"generated_at\":\"2026-12-02T02:12:04Z\",\"articles\":[")+ for (i in 0 until 2500) {+ if (i > 0) sb.append(',')+ val src = ids[(i * 37) % ids.size]+ sb.append("{\"title\":\"Benchmark story number $i about a developing event\",\"url\":\"https://example.com/a$i\",\"source\":\"$src\",\"published_at\":\"2026-12-02T01:00:00Z\",\"metered\":false,\"language\":\"en\",\"story_id\":\"s-${i / 2}\"}")+ }+ sb.append("]}")+ val text = sb.toString()+ println("BENCH fixture bytes=${text.length}")+ // warm (catalog load)+ ServerFeedParser.parse(text)+ repeat(5) { iter ->+ var t0 = System.nanoTime()+ val parsed = ServerFeedParser.parse(text)+ val tParse = (System.nanoTime() - t0) / 1_000_000+ t0 = System.nanoTime()+ val merged = FeedMerger.merge(listOf(parsed), limit = 500)+ val tMerge = (System.nanoTime() - t0) / 1_000_000+ t0 = System.nanoTime()+ val stories = FeedRanking.rankGroupedStories(StoryGrouping.group(merged))+ val tGroup = (System.nanoTime() - t0) / 1_000_000+ println("BENCH iter=$iter parsed=${parsed.size} merged=${merged.size} stories=${stories.size} parseMs=$tParse mergeMs=$tMerge groupRankMs=$tGroup")+ assertEquals(2500, parsed.size)+ }+ // catalog lookup micro+ var t0 = System.nanoTime()+ var hits = 0+ repeat(2500) { i -> if (SourceCatalog.byId(ids[(i * 37) % ids.size]) != null) hits++ }+ println("BENCH byId x2500 ms=${(System.nanoTime() - t0) / 1_000_000} hits=$hits")+ }+}
news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt b/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.ktindex e891e07a72..ecd4d6f409 100644--- a/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt@@ -34,6 +34,13 @@ class ServerFeedParserTest { assertEquals("de", articles[3].language, "non-English catalog default") } + @Test fun feedStampReadsGeneratedAtWithoutFullParse() {+ assertEquals("2026-11-23T12:00:00Z", ServerFeedParser.feedStamp(fixture))+ assertEquals(null, ServerFeedParser.feedStamp("""{"articles":[]}"""))+ assertEquals(null, ServerFeedParser.feedStamp("not json"))+ assertEquals(null, ServerFeedParser.feedStamp("""{"generated_at":""}"""))+ }+ @Test fun malformedInputIsEmptyNotThrowing() { assertTrue(ServerFeedParser.parse("not json").isEmpty()) assertTrue(ServerFeedParser.parse("""{"articles":[{"title":"x"}]}""").isEmpty())