news: the app never clusters - server storyId only
- Commit
2aef0c6a086468ee02184c1af7d3effc2e6d8a9b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-25 16:59 UTC (10 days ago)
- Parents
85fc08b
Owner rule: the reader makes no grouping decisions. All local clustering removed (union-find, title similarity, entity/keyword rules, bridge merges). Stories are mechanical: articles sharing the exact server storyId form one story; every article without one is a singleton. Server title/one-liner used verbatim; ranking only orders. Fallback-crawl articles render as single-article stories. Verified: 64 news tests + compile + lint green; grep confirms no local-merge code remains.
Diff
news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.ktindex 46ace866ed..f109d3d91f 100644--- a/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt@@ -16,10 +16,12 @@ data class FeedArticle( val language: String? = null, /** * Server story assignment (`story_id` in news.json): same value for- * every article the server grouped into one story. Server grouping- * (built server-side with full-text signals) wins over client- * clustering — see [StoryGrouping]. Null for the fallback crawl.- * Persisted in Room (CachedArticle.storyId) so it survives caching.+ * every article the server grouped into one story. This is the+ * *only* grouping key — the client makes no grouping decisions+ * (see [StoryGrouping]). Null/blank (always the case for the+ * fallback sitemap/RSS crawl) means the article is its own+ * singleton story. Persisted in Room (CachedArticle.storyId) so+ * it survives caching. */ val serverStoryId: String? = null, /**
news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.ktindex cb04bed396..3abfa28d27 100644--- a/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt@@ -9,10 +9,15 @@ enum class FeedSort(val label: String) { LATEST("Latest"), } -/** One ranked representative plus how many near-duplicate sources it collapsed. */+/** One ranked representative plus how many other sources its server story carries. */ data class RankedArticle( val article: FeedArticle,- /** Extra sources carrying the same story (0 = carried by one source only). */+ /**+ * Extra distinct sources in the same server-grouped story+ * (0 = singleton or single-source story). Derived only from+ * actual server `storyId` membership — never from headline+ * similarity (there is no client-side grouping).+ */ val alsoFromSources: Int = 0, ) @@ -24,27 +29,26 @@ data class RankedArticle( * * ## Top stories formula (no popularity data exists, so on-device signals only) *- * Score (per article, before clustering):+ * Score (per article, see [score]): * ``` * ageHours = max(0, (now - publishedAtMillis) / 3_600_000) // future stamps clamp to 0 * score = 100 * 0.5^(ageHours / 18) // 18 h half-life * + 5 if imageUrl != null * + 2 if keywords is non-empty * ```- * So a fresh story scores ~100–107, a story 18 h old ~50, 36 h old ~25,+ * So a fresh article scores ~100–107, one 18 h old ~50, 36 h old ~25, * 3 days old ~6 — day-old sinks but does not vanish. An unknown * timestamp (`publishedAtMillis <= 0`) scores 0 and sinks to the end.- * Ties break on newer `publishedAtMillis`, then URL, so the order is- * total and deterministic. *- * ## Story clustering (collapse before ranking)+ * ## Stories (group before ranking — mechanically, by server id only) *- * Clustering is [StoryGrouping] (see its KDoc for the algorithm,- * inverted-index candidate generation, merge rules, thresholds and- * time windows). Each story keeps one representative: earliest- * `publishedAtMillis` (wire copy originates once), tie-broken by- * fuller metadata (image, then more keywords, then URL); the- * representative reports `distinct sources - 1` as+ * Stories come from [StoryGrouping]: articles sharing the exact+ * server `storyId` form one story; every article without one is a+ * singleton. Ranking only *orders* those stories — it never merges,+ * splits, or otherwise influences membership. Each story keeps one+ * representative: earliest `publishedAtMillis`, tie-broken by fuller+ * metadata (image, then more keywords, then URL); the representative+ * reports `distinct sources - 1` (actual server membership only) as * [RankedArticle.alsoFromSources]. * * ## Top stories for stories ([rankStories] / [storyScore])@@ -56,8 +60,9 @@ data class RankedArticle( * + crossSourceBonus // see below, capped 30 * crossSourceBonus = 0 if 1 source else min(30, 10 * log2(sourceCount)) * ```- * Cross-source breadth is an honest prominence signal (independent- * outlets choosing to cover an event), folded in *alongside*+ * Cross-source breadth (counted only over actual server-story+ * membership) is an honest prominence signal (independent outlets+ * the server grouped into one story), folded in *alongside* * recency: 2 sources +10, 4 sources +20, 8+ +30. It breaks ties * between same-age stories and lifts a widely-covered day-old story * (50+20) above a single-source half-day story (~71 vs ~75 — close),@@ -77,8 +82,8 @@ data class RankedArticle( * the first screen always spans at least 7 sources when that many * have fresh stories. *- * Latest is a plain newest-first sort with the same clustering- * collapse (a duplicated wire story is one row in either order).+ * Latest is a plain newest-first sort of the same mechanical+ * stories (one row per server story / singleton, in either order). */ object FeedRanking { @@ -87,8 +92,6 @@ object FeedRanking { const val KEYWORD_BONUS = 2.0 const val FIRST_PAGE_SIZE = 20 const val FIRST_PAGE_PER_SOURCE = 3- const val NEAR_DUPLICATE_JACCARD = 0.85- const val MIN_TOKENS_FOR_NEAR_DUPLICATE = 4 /** Cap on the cross-source bonus in [storyScore]. */ const val MAX_CROSS_SOURCE_BONUS = 30.0 @@ -147,19 +150,6 @@ object FeedRanking { return score } - /** Normalised comparison form of a headline (see KDoc). */- fun normaliseTitle(title: String): String {- var text = title.trim().lowercase()- // Strip a leading "source:" / "source -" wire prefix, if it is short.- val separators = listOf(text.indexOf(": "), text.indexOf(" - ")).filter { it >= 0 }- val prefixEnd = separators.minOrNull() ?: -1- if (prefixEnd in 1..24) {- val skip = if (text.startsWith(": ", prefixEnd)) 2 else 3- text = text.substring(prefixEnd + skip).trim()- }- return text.replace(Regex("[^\\p{L}\\p{N}]+"), " ").trim().replace(Regex("\\s+"), " ")- }- private fun diversifyStories(stories: List<Story>, nowMillis: Long): List<Story> { val remaining = stories.sortedWith( compareByDescending<Story> { storyScore(it, nowMillis) }
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 7dfda3520a..945ed107b5 100644--- a/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt@@ -36,13 +36,14 @@ import kotlinx.serialization.json.jsonObject * [SourceCatalog] (see [NewsCategory]), and the feed/search filters * apply that mapping to the article's `sourceId`. Unresolved ids have * no category and match the feed's "All" filter only.- * - Story grouping (server-side, full-text signals): `story_id`- * (same for all articles of one story; server assignment wins over- * client clustering), `story_one_liner` (generated one-line summary- * — the only server text the client may display; extracted article- * text is NEVER served), and optional `story_title`. All optional:- * articles without them are client-clustered (fallback crawl path- * produces no story fields at all). Alias keys `story_oneliner` /+ * - Story grouping (server-side only; the client never groups):+ * `story_id` (same for all articles of one story — the client's+ * sole grouping key, used exactly), `story_one_liner` (generated+ * one-line summary — the only server text the client may display;+ * extracted article text is NEVER served), and optional+ * `story_title`. All optional: articles without a `story_id`+ * (the fallback crawl path produces no story fields at all) each+ * render as a single-article story. Alias keys `story_oneliner` / * `story_summary` are also accepted for the one-liner until the * server schema freezes. *
news/src/main/java/com/vayunmathur/news/domain/Story.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/Story.kt b/news/src/main/java/com/vayunmathur/news/domain/Story.ktindex f89741bca1..2cacd2a31a 100644--- a/news/src/main/java/com/vayunmathur/news/domain/Story.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/Story.kt@@ -1,39 +1,42 @@ package com.vayunmathur.news.domain -import kotlin.math.abs- /**- * A **story**: one real-world event/development told by one or more- * articles. The feed is a list of stories, not a flat article list.+ * A **story**: the articles the *server* grouped under one+ * `story_id`, or a single article when the server gave it no+ * `story_id`. The feed is a list of stories, not a flat article list.+ *+ * The client makes **no grouping decisions**: [StoryGrouping] is+ * purely mechanical (see its KDoc). It never compares headlines,+ * entities, keywords or timestamps to decide membership, so two+ * articles the server did not group are never shown as one story,+ * however similar they look. *- * [id] is stable from the representative (earliest article, see- * [StoryGrouping]): the normalised representative URL. It survives- * re-clustering as long as the earliest telling stays in the cache,- * which is exactly the wire-origin article. It is carried in+ * [id] is `srv:<serverStoryId>` for a server-grouped story, else the+ * normalised URL of its sole article. It is carried in * `Route.Story` — never in ViewModel selection state. * * [articles] are all members sorted earliest → latest (unknown * timestamps last, then URL), so a story page reads as a timeline of- * how coverage developed. [representative] is `articles.first()`- * when any timestamp is known, otherwise the deterministic first- * member; [title] and the feed card headline are the representative's.+ * how coverage developed. [representative] is the earliest member+ * (tie-broken by image, more keywords, then URL); [title] is the+ * server-provided `story_title` verbatim when present, else the+ * representative's own headline. */ data class Story( val id: String, val representative: FeedArticle, val articles: List<FeedArticle>, ) {- /** Server canonical title if grouped server-side, else representative's. */+ /** Server canonical title verbatim if present, else representative's. */ val title: String get() = articles.firstNotNullOfOrNull { it.serverStoryTitle?.takeIf { t -> t.isNotBlank() } } ?: representative.title /** Server one-liner summary (generated, never extracted text), if any. */ val oneLiner: String?- get() = representative.storyOneLiner?.takeIf { it.isNotBlank() }- ?: articles.firstNotNullOfOrNull { it.storyOneLiner?.takeIf { t -> t.isNotBlank() } }- /** Server story id when the server grouped (some of) these articles. */+ get() = articles.firstNotNullOfOrNull { it.storyOneLiner?.takeIf { t -> t.isNotBlank() } }+ /** Server story id of this story, or null for a singleton. */ val serverStoryId: String?- get() = articles.firstNotNullOfOrNull { it.serverStoryId }+ get() = articles.firstNotNullOfOrNull { it.serverStoryId?.takeIf { s -> s.isNotBlank() } } /** Distinct source ids carrying this story, sorted. */ val sources: List<String> get() = articles.map { it.sourceId }.distinct().sorted() /** Distinct source display names (catalog name, else id), sorted. */@@ -67,143 +70,42 @@ data class Story( } /**- * Deterministic, pure story clustering over a headline corpus.- * No ML / embeddings (no model deps in this app): token/entity- * overlap + keyword overlap + time proximity is the honest toolkit.+ * Mechanical story construction — the *only* grouping rule in the app: *- * ## Algorithm (inverted index, not O(n²))- * Pairwise union-find over 500–2,500 articles is measured in tests- * ([StoryGroupingTest]); naive O(n²) Jaccard at 2,500 is ~3.1M- * pairs. Instead candidate pairs are generated from an inverted- * index and only those pairs are scored:- * - exact normalised-title groups (hash map), and- * - postings for *discriminative* tokens: keyword tokens, entity- * tokens, and title tokens whose document frequency is- * ≤ [MAX_DOC_FREQ] (rare tokens). A posting longer than- * [MAX_POSTING] is skipped (too common to discriminate).- * Expected candidates are O(n · avg posting length) — orders of- * magnitude below n² — and every candidate is then judged by the- * full merge predicate below, so indexing only loses pairs that- * share no discriminative token at all (they could never pass the- * entity/keyword gate of the relaxed rules, and the strict rules- * need a near-identical title, which necessarily shares tokens).+ * - Articles sharing the exact same non-blank server `storyId`+ * (`FeedArticle.serverStoryId`, from `story_id` in `news.json`)+ * form one story, in that key only.+ * - Every article with a null/blank `storyId` is its own+ * single-article (singleton) story. That includes every article+ * from the fallback on-device sitemap/RSS crawl, which carries no+ * `storyId` at all. *- * ## Merge predicate (pairwise, then single-linkage union-find)- * Let `J` = Jaccard of stopword-filtered title token sets,- * `sharedEntity` = shared entity tokens (capitalised-name tokens- * when the headline is not all-Title-Case, plus keyword tokens),- * `sharedKeyword` = shared normalised keyword strings,- * `dt` = |Δ publishedAt| (unknown timestamps: `dt = 0` — no time- * evidence, fall back to text only).- * A pair merges when any rule fires (thresholds are `const`s so- * they are tunable in one place):- * 1. **Exact**: normalised titles equal and dt ≤ [EXACT_WINDOW_MS]- * (72h). Identical headlines 3 days apart are *not* merged by- * headline overlap alone — a recurring fixture/headline is a- * new story — but a chain A–B (≤72h), B–C (≤72h) still merges- * A,B,C via single linkage, so a developing story follows its- * updates across a longer total span.- * 2. **Near-duplicate** (legacy bar): `J ≥ 0.85`, ≥4 tokens each,- * dt ≤ [NEAR_DUP_WINDOW_MS] (48h). Wire-copy rewrites.- * 3. **Same event, rewritten**: `J ≥ 0.55` and- * (`sharedEntity ≥ 1` or `sharedKeyword ≥ 1`) and- * dt ≤ [EVENT_WINDOW_MS] (36h).- * 4. **Update of a known event**: `J ≥ 0.40` and- * `sharedEntity ≥ 2` and dt ≤ [EVENT_WINDOW_MS].- * 5. **Fast update chain**: `J ≥ 0.30`, `sharedEntity ≥ 1`,- * dt ≤ [UPDATE_WINDOW_MS] (12h) — a headline that evolves- * within hours around the same named people/places.- * Server grouping (`FeedArticle.serverStoryId`, from full-text- * server extraction) wins over all of the above: shared server ids- * are pre-unioned, and two components carrying different server ids- * are never merged, even transitively through an ungrouped article.- * Extracted article text is never served to the client; only the- * generated `story_one_liner` may accompany the assignment.- * Different events with similar *generic* headlines ("Markets rally- * on jobs data" vs "Markets rally on inflation data", J≈0.66 but- * no shared entity/keyword) fire no rule: rules 3–5 all require a- * shared entity/keyword, and rule 2 needs J ≥ 0.85. That gate is- * the precision guard; the recall gain over headline-Jaccard-only- * comes precisely from rules 3–5.- * Single-linkage chaining is intentional (updates follow into the- * story) and bounded by the per-pair windows: a chain can span- * days only through ≤window steps.+ * Nothing else influences membership: not headline similarity, not+ * entities or keywords, not timestamps, and not ranking (ranking in+ * [FeedRanking] only *orders* the stories built here). An ungrouped+ * article is never merged into a server story, and two different+ * server story ids are never merged — even when their headlines are+ * identical. Server-provided `story_title` / `story_one_liner` are+ * surfaced verbatim via [Story.title] / [Story.oneLiner]; extracted+ * article text is never served to or consumed by the client. *- * Representative: earliest `publishedAtMillis` (wire copy- * originates once), tie-broken by image, more keywords, then URL —- * the same rule the pre-story feed used, so story ids/titles are- * stable against the old representative choice.+ * Stories are returned in first-appearance order of their key in+ * [articles]; callers that display them re-order with [FeedRanking]. */ object StoryGrouping { - const val EXACT_WINDOW_MS = 72L * 3_600_000L- const val NEAR_DUP_WINDOW_MS = 48L * 3_600_000L- const val EVENT_WINDOW_MS = 36L * 3_600_000L- const val UPDATE_WINDOW_MS = 12L * 3_600_000L- const val NEAR_DUP_JACCARD = 0.85- const val EVENT_JACCARD = 0.55- const val UPDATE_JACCARD = 0.40- const val CHAIN_JACCARD = 0.30- const val MIN_TOKENS = 4- /** Tokens occurring in more articles than this are not discriminative. */- const val MAX_DOC_FREQ = 12- /** Postings longer than this are skipped during candidate generation. */- const val MAX_POSTING = 60-- private val STOPWORDS = setOf(- "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by",- "as", "is", "are", "was", "were", "be", "been", "has", "have", "had", "will", "would",- "can", "could", "says", "said", "after", "before", "over", "under", "amid", "into",- "from", "new", "live", "updates", "update", "latest",- )- fun group(articles: List<FeedArticle>): List<Story> { if (articles.isEmpty()) return emptyList()- val feats = articles.map { Features.of(it) }- val parent = IntArray(articles.size) { it }- fun find(x: Int): Int {- var r = x- while (parent[r] != r) r = parent[r]- var c = x- while (parent[c] != r) { val n = parent[c]; parent[c] = r; c = n }- return r- }-- // Per-root server-id sets (O(1) bridge guard, not a corpus scan per merge).- val rootServerIds = HashMap<Int, Set<String>>()- articles.forEachIndexed { i, art ->- rootServerIds[i] = art.serverStoryId?.takeIf { it.isNotBlank() }?.let { setOf(it) } ?: emptySet()- }- fun unionTracked(a: Int, b: Int) {- val ra = find(a); val rb = find(b)- if (ra == rb) return- val root = minOf(ra, rb); val other = maxOf(ra, rb)- parent[other] = root- rootServerIds[root] = (rootServerIds[ra].orEmpty() + rootServerIds[rb].orEmpty())- rootServerIds.remove(other)- }- // Server grouping wins: pre-union every shared serverStoryId.- articles.indices.groupBy { articles[it].serverStoryId }.forEach { (sid, idx) ->- if (!sid.isNullOrBlank() && idx.size > 1) {- for (k in 1 until idx.size) unionTracked(idx[0], idx[k])- }+ // Exact key only: non-blank server storyId, else a unique+ // singleton key per article (its index — never shared).+ val byKey = LinkedHashMap<String, MutableList<FeedArticle>>()+ articles.forEachIndexed { index, article ->+ val serverId = article.serverStoryId?.takeIf { it.isNotBlank() }+ val key = if (serverId != null) "srv:$serverId" else "one:$index"+ byKey.getOrPut(key) { mutableListOf() } += article }- val df = HashMap<String, Int>()- feats.forEach { f -> f.contentTokens.forEach { df[it] = (df[it] ?: 0) + 1 } }- val candidates = candidatePairs(feats, df).sortedWith(compareBy({ it.first }, { it.second }))- for ((i, j) in candidates) {- if (!shouldMerge(feats[i], feats[j])) continue- // Never merge components carrying different server stories,- // even transitively: an ungrouped article may join ONE- // server story, it must not bridge two of them.- val ri = find(i); val rj = find(j)- if (ri == rj) continue- val idsI = rootServerIds[ri].orEmpty(); val idsJ = rootServerIds[rj].orEmpty()- if (idsI.isNotEmpty() && idsJ.isNotEmpty() && idsI != idsJ) continue- unionTracked(i, j)- }- return articles.indices.groupBy { find(it) }.values.map { idx ->- val members = idx.map { articles[it] }.sortedWith(+ return byKey.entries.map { (key, membersUnsorted) ->+ val members = membersUnsorted.sortedWith( compareBy<FeedArticle> { if (it.publishedAtMillis > 0) it.publishedAtMillis else Long.MAX_VALUE } .thenBy { it.url }, )@@ -213,104 +115,20 @@ object StoryGrouping { .thenByDescending { it.keywords.size } .thenBy { it.url }, ) ?: members.first()- // Server-grouped stories keep the server id (prefixed so- // it can never collide with a client representative URL).- val serverId = members.firstNotNullOfOrNull { it.serverStoryId?.takeIf { s -> s.isNotBlank() } } Story(- id = if (serverId != null) "srv:$serverId" else FeedMerger.normaliseUrl(representative.url),+ id = if (key.startsWith("srv:")) key else FeedMerger.normaliseUrl(representative.url), representative = representative, articles = members, ) } }-- /** Candidate pairs from exact-title groups + discriminative-token postings. */- private fun candidatePairs(feats: List<Features>, df: Map<String, Int>): Set<Pair<Int, Int>> {- val pairs = HashSet<Pair<Int, Int>>()- fun add(a: Int, b: Int) { if (a != b) pairs += minOf(a, b) to maxOf(a, b) }- // Exact normalised titles.- feats.indices.groupBy { feats[it].normalised }.forEach { (norm, idx) ->- if (norm.isNotEmpty()) for (a in idx) for (b in idx) add(a, b)- }- val postings = HashMap<String, MutableList<Int>>()- feats.forEachIndexed { i, f ->- val keys = HashSet<String>()- f.contentTokens.filterTo(keys) { (df[it] ?: 0) <= MAX_DOC_FREQ }- keys += f.entityTokens.map { "e:$it" }- keys += f.keywordKeys.map { "k:$it" }- keys.forEach { k -> postings.getOrPut(k) { mutableListOf() } += i }- }- postings.values.forEach { posting ->- if (posting.size in 2..MAX_POSTING) {- for (a in posting) for (b in posting) add(a, b)- }- }- return pairs- }-- internal fun shouldMerge(a: Features, b: Features): Boolean {- if (a.normalised.isEmpty() || b.normalised.isEmpty()) return false- val dt = if (a.published > 0 && b.published > 0) abs(a.published - b.published) else 0L- if (a.normalised == b.normalised) return dt <= EXACT_WINDOW_MS- val unionSize = (a.contentTokens union b.contentTokens).size- if (unionSize == 0) return false- val shared = a.contentTokens intersect b.contentTokens- val j = shared.size.toDouble() / unionSize- val sharedEntity = (a.entityTokens intersect b.entityTokens).size- val sharedKeyword = (a.keywordKeys intersect b.keywordKeys).size- if (a.contentTokens.size >= MIN_TOKENS && b.contentTokens.size >= MIN_TOKENS &&- j >= NEAR_DUP_JACCARD && dt <= NEAR_DUP_WINDOW_MS- ) return true- // Relaxed rules require an entity/keyword gate: rare-token- // overlap alone is not enough (generic headlines share it).- if (j >= EVENT_JACCARD && (sharedEntity >= 1 || sharedKeyword >= 1) && dt <= EVENT_WINDOW_MS) return true- if (j >= UPDATE_JACCARD && sharedEntity >= 2 && dt <= EVENT_WINDOW_MS) return true- if (j >= CHAIN_JACCARD && sharedEntity >= 1 && dt <= UPDATE_WINDOW_MS) return true- return false- }-- /** Precomputed per-article comparison features. */- internal data class Features(- val normalised: String,- val contentTokens: Set<String>,- val entityTokens: Set<String>,- val keywordKeys: Set<String>,- val published: Long,- ) {- companion object {- fun of(article: FeedArticle): Features {- val normalised = FeedRanking.normaliseTitle(article.title)- val tokens = if (normalised.isEmpty()) emptySet() else normalised.split(' ').toSet()- val content = tokens - STOPWORDS- val keywordKeys = article.keywords.map { FeedRanking.normaliseTitle(it) }.filter { it.isNotEmpty() }.toSet()- val keywordTokens = keywordKeys.flatMap { it.split(' ') }.toSet() - STOPWORDS- return Features(normalised, content, entityTokens(article.title) + keywordTokens, keywordKeys, article.publishedAtMillis)- }-- /**- * Capitalised name tokens from the raw headline. When the- * headline is all Title Case (every word capitalised) caps- * carry no signal, so only keyword tokens (added by caller)- * count as entities.- */- private fun entityTokens(title: String): Set<String> {- val words = title.split(Regex("\\s+")).map { it.trim(',', '.', ':', ';', '"', '“', '”', '(', ')') }- .filter { it.isNotEmpty() }- if (words.size < 2) return emptySet()- // Sentence-initial capital is not a name; drop word 0.- val rest = words.drop(1)- val capitalised = rest.filter { it.first().isUpperCase() }- if (capitalised.size >= rest.size.coerceAtLeast(1)) return emptySet() // Title Case everywhere- return capitalised.map { FeedRanking.normaliseTitle(it) }.filter { it.length >= 3 }.toSet() - STOPWORDS- }- }- } } /** * Stories containing at least one of [hitUrlsInRankOrder] (search hit * article URLs in relevance order), in the order their best hit- * appears — an article match surfaces its whole story.+ * appears — an article match surfaces its whole (server-grouped or+ * singleton) story. */ fun List<Story>.orderedBySearchHits(hitUrlsInRankOrder: List<String>): List<Story> { if (hitUrlsInRankOrder.isEmpty()) return emptyList()
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 1e72860abf..a1fca53d95 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -28,13 +28,14 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /**- * Feed = stories. Grouping ([StoryGrouping], server assignment wins)- * is computed in-memory over the Room article cache per emission —- * no schema change for grouping itself (the two server story columns- * are the only v2 addition). A null category filter is "All"; a story- * matches a category when ANY member does. [FeedRanking] ranks- * stories (Top folds cross-source breadth into recency; Latest is by- * latest update). Search hits surface their whole story.+ * Feed = stories. Grouping ([StoryGrouping]) is purely mechanical —+ * exact server `storyId` key only, no client-side grouping — computed+ * in-memory over the Room article cache per emission (the two server+ * story columns are the only v2 addition). A null category filter is+ * "All"; a story matches a category when ANY member does.+ * [FeedRanking] only *orders* stories (Top folds cross-source+ * breadth — counted over actual server membership — into recency;+ * Latest is by latest update). Search hits surface their whole story. */ /** UI state and actions for feed, reader and saved screens. */@@ -65,7 +66,7 @@ class NewsViewModel( .map { all -> StoryGrouping.group(all.map { it.toFeedArticle() }) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) - /** Extra sources per feed-row URL, from story clustering (see [FeedRanking]). */+ /** Extra sources per feed-row URL, from actual server story membership only. */ val clusterCounts: StateFlow<Map<String, Int>> = allStories .map { stories -> stories.associate { it.representative.url to (it.sourceCount - 1).coerceAtLeast(0) } } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())@@ -114,7 +115,7 @@ class NewsViewModel( } } - /** Feed stories: full-corpus grouping, category = any-member, ranked. */+ /** Feed stories: mechanical grouping, category = any-member, ranked (order only). */ val stories: StateFlow<List<Story>> = combine( allStories, _categoryFilter, feedSort, localLocation, ) { grouped, category, sort, location ->
news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt b/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.ktindex ad106e98ac..1a674678d9 100644--- a/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt@@ -4,7 +4,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue -/** Top-stories ranking: decay, diversity cap, cluster collapse, Latest. */+/** Top-stories ranking: decay, diversity cap, mechanical story order, Latest. */ class FeedRankingTest { private val now = 1_700_000_000_000L@@ -17,7 +17,8 @@ class FeedRankingTest { published: Long, image: String? = null, keywords: List<String> = emptyList(),- ) = FeedArticle(url, source, title, published, image, keywords)+ serverStoryId: String? = null,+ ) = FeedArticle(url, source, title, published, image, keywords, serverStoryId = serverStoryId) @Test fun decayOrdersFreshBeforeDayOldBeforeThreeDaysOld() { val ranked = FeedRanking.rank(@@ -60,7 +61,7 @@ class FeedRankingTest { assertEquals(30, solo.size) } - @Test fun exactAndNearDuplicateTitlesCollapseToEarliest() {+ @Test fun identicalHeadlinesWithoutStoryIdDoNotCollapse() { val ranked = FeedRanking.rank( listOf( article("bbc", "https://e/b1", title = "Storm hits coast as winds rise", published = hoursAgo(2.0)),@@ -70,15 +71,28 @@ class FeedRankingTest { ), FeedSort.TOP, now, )- assertEquals(2, ranked.size, "three tellings of the storm story must collapse to one row")- val storm = ranked.first { it.article.title.contains("Storm") }- assertEquals("https://e/g1", storm.article.url, "representative is the earliest telling")- assertEquals(2, storm.alsoFromSources)- // Latest keeps the same collapse.+ assertEquals(4, ranked.size, "no storyId = no grouping, however similar the headlines")+ assertTrue(ranked.all { it.alsoFromSources == 0 })+ }++ @Test fun sharedStoryIdCollapsesToEarliestRepresentative() {+ val ranked = FeedRanking.rank(+ listOf(+ article("bbc", "https://e/b1", title = "Storm hits coast as winds rise", published = hoursAgo(2.0), serverStoryId = "s1"),+ article("g1", "https://e/g1", title = "Different wording entirely", published = hoursAgo(5.0), serverStoryId = "s1"),+ article("dw", "https://e/d1", title = "Winds rise as storm hits coast", published = hoursAgo(1.0), serverStoryId = "s1"),+ article("npr", "https://e/n1", title = "Markets rally on jobs data", published = hoursAgo(1.0)),+ ),+ FeedSort.TOP, now,+ )+ assertEquals(2, ranked.size, "only the server-grouped articles collapse to one row")+ val storm = ranked.first { it.alsoFromSources == 2 }+ assertEquals("https://e/g1", storm.article.url, "representative is the earliest member")+ // Latest keeps the same mechanical membership. val latest = FeedRanking.rank( listOf(- article("bbc", "https://e/b1", title = "Same headline", published = hoursAgo(2.0)),- article("g1", "https://e/g1", title = "Same headline", published = hoursAgo(5.0)),+ article("bbc", "https://e/b1", title = "Same headline", published = hoursAgo(2.0), serverStoryId = "s1"),+ article("g1", "https://e/g1", title = "Same headline", published = hoursAgo(5.0), serverStoryId = "s1"), ), FeedSort.LATEST, now, )
news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt b/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.ktindex 32c2542dc7..3fa8104f5d 100644--- a/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt@@ -2,10 +2,15 @@ package com.vayunmathur.news.domain import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertNotEquals+import kotlin.test.assertNull import kotlin.test.assertTrue -/** Story clustering precision/recall, model fields, server-wins, perf. */+/**+ * Mechanical story grouping: exact server `storyId` key only.+ * No client-side grouping exists — identical headlines, shared+ * entities/keywords and close timestamps must never merge articles+ * the server did not group.+ */ class StoryGroupingTest { private val now = 1_700_000_000_000L@@ -14,72 +19,108 @@ class StoryGroupingTest { source: String, url: String, title: String, published: Long, image: String? = null, keywords: List<String> = emptyList(), serverStoryId: String? = null, oneLiner: String? = null, lang: String? = null,- ) = FeedArticle(url, source, title, published, image, keywords, language = lang, serverStoryId = serverStoryId, storyOneLiner = oneLiner)+ serverStoryTitle: String? = null,+ ) = FeedArticle(+ url, source, title, published, image, keywords, language = lang,+ serverStoryId = serverStoryId, storyOneLiner = oneLiner, serverStoryTitle = serverStoryTitle,+ ) - @Test fun sameEventMultiOutletMerges() {+ @Test fun sameStoryIdGroupsRegardlessOfHeadlineOrTime() { val stories = StoryGrouping.group( listOf(- a("bbc", "https://e/b1", "Storm hits coast as winds rise", h(2.0)),- a("guardian", "https://e/g1", "Storm hits coast as winds rise!", h(5.0)),- a("dw", "https://e/d1", "Winds rise as storm hits coast", h(1.0)),+ a("bbc", "https://e/b1", "Storm hits coast as winds rise", h(50.0), serverStoryId = "s1"),+ a("dw", "https://e/d1", "Completely different wording here", h(1.0), serverStoryId = "s1"), a("npr", "https://e/n1", "Markets rally on jobs data", h(1.0)), ), ) assertEquals(2, stories.size)- val storm = stories.first { it.articles.size == 3 }- assertEquals(3, storm.sourceCount)- assertEquals("https://e/g1", storm.representative.url, "earliest telling is representative")- assertEquals(storm.representative.url.let { FeedMerger.normaliseUrl(it) }, storm.id)+ val grouped = stories.first { it.id == "srv:s1" }+ assertEquals(2, grouped.articles.size)+ assertEquals(2, grouped.sourceCount)+ assertEquals("s1", grouped.serverStoryId)+ // Timeline order is earliest -> latest within the server story.+ assertEquals(listOf("https://e/b1", "https://e/d1"), grouped.articles.map { it.url })+ assertEquals("https://e/b1", grouped.representative.url, "earliest member is representative") } - @Test fun differentEventsWithSimilarHeadlinesDontMerge() {+ @Test fun missingStoryIdIsAlwaysSingleton() { val stories = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Markets rally on jobs data", h(2.0)),- a("dw", "https://e/2", "Markets rally on inflation data", h(1.0)),- a("bbc", "https://e/3", "Council approves new housing plan", h(2.0)),- a("dw", "https://e/4", "Council approves new transport plan", h(1.0)),+ a("bbc", "https://e/1", "Storm hits coast as winds rise", h(2.0)),+ a("dw", "https://e/2", "Storm hits coast as winds rise", h(1.0)),+ a("npr", "https://e/3", "Storm hits coast as winds rise", h(1.0)), ), )- assertEquals(4, stories.size, "generic-headline lookalikes must stay separate")+ // Identical headlines + close timestamps: still no local merge.+ assertEquals(3, stories.size)+ assertTrue(stories.all { it.articles.size == 1 && it.serverStoryId == null })+ assertTrue(stories.all { it.sourceCount == 1 })+ assertEquals(+ setOf("https://e/1", "https://e/2", "https://e/3"),+ stories.map { it.representative.url }.toSet(),+ )+ // Singleton id is the normalised sole-article URL.+ assertTrue(stories.all { it.id == FeedMerger.normaliseUrl(it.representative.url) }) } - @Test fun timeWindowSplitsRecurringHeadline() {- val split = StoryGrouping.group(+ @Test fun blankStoryIdIsSingleton() {+ val stories = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Storm hits coast as winds rise", h(80.0)),- a("dw", "https://e/2", "Storm hits coast as winds rise", h(1.0)),+ a("bbc", "https://e/1", "Same headline", h(1.0), serverStoryId = ""),+ a("dw", "https://e/2", "Same headline", h(1.0), serverStoryId = " "), ), )- assertEquals(2, split.size, "identical headline >72h apart is a new story")- // But a chain through an intermediate (each step <=72h) follows updates.- val chained = StoryGrouping.group(+ assertEquals(2, stories.size)+ assertTrue(stories.all { it.articles.size == 1 })+ }++ @Test fun differentStoryIdsNeverMergedEvenWithIdenticalHeadlines() {+ val stories = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Storm hits coast as winds rise", h(80.0)),- a("dw", "https://e/2", "Storm hits coast as winds rise", h(40.0)),- a("npr", "https://e/3", "Storm hits coast as winds rise", h(1.0)),+ a("bbc", "https://e/1", "First angle on the event", h(1.0), serverStoryId = "s1", oneLiner = "One line."),+ a("dw", "https://e/2", "First angle on the event", h(1.0), serverStoryId = "s2"),+ // Ungrouped identical headline joins neither server story.+ a("guardian", "https://e/3", "First angle on the event", h(1.0)), ), )- assertEquals(1, chained.size)+ assertEquals(3, stories.size)+ val s1 = stories.first { it.id == "srv:s1" }+ assertEquals(listOf("https://e/1"), s1.articles.map { it.url })+ assertEquals("One line.", s1.oneLiner)+ val s2 = stories.first { it.id == "srv:s2" }+ assertEquals(listOf("https://e/2"), s2.articles.map { it.url })+ val singleton = stories.first { it.serverStoryId == null }+ assertEquals(listOf("https://e/3"), singleton.articles.map { it.url }) } - @Test fun updateChainMergesThroughEvolvingHeadlines() {- val stories = StoryGrouping.group(+ @Test fun serverTitleAndOneLinerUsedVerbatim() {+ val story = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Hurricane lands in Florida", h(10.0)),- a("dw", "https://e/2", "Hurricane death toll rises in Florida", h(6.0)),- a("npr", "https://e/3", "Death toll rises as Florida begins cleanup after hurricane", h(2.0)),+ a(+ "bbc", "https://e/1", "Outlet headline one", h(5.0),+ serverStoryId = "s1", serverStoryTitle = "Canonical server title",+ ),+ a(+ "dw", "https://e/2", "Outlet headline two", h(1.0),+ serverStoryId = "s1", oneLiner = "Server summary.",+ ), ),- )- assertEquals(1, stories.size, "updates around the same named event must follow into the story")- assertEquals(listOf("https://e/1", "https://e/2", "https://e/3"), stories[0].articles.map { it.url }, "timeline earliest to latest")+ ).single()+ assertEquals("Canonical server title", story.title)+ assertEquals("Server summary.", story.oneLiner)+ // Without a server title, the representative's headline is used.+ val noServerTitle = StoryGrouping.group(+ listOf(a("bbc", "https://e/1", "Only headline", h(1.0), serverStoryId = "s9")),+ ).single()+ assertEquals("Only headline", noServerTitle.title)+ assertNull(noServerTitle.oneLiner) } - @Test fun storyModelFields() {+ @Test fun storyModelFieldsFromActualMembers() { val story = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Storm hits coast", h(5.0), image = "https://e/old.jpg", lang = "en"),- a("techcrunch", "https://e/2", "Storm hits coast", h(1.0), image = "https://e/new.jpg", lang = "en"),+ a("bbc", "https://e/1", "Storm hits coast", h(5.0), image = "https://e/old.jpg", lang = "en", serverStoryId = "s1"),+ a("techcrunch", "https://e/2", "Storm hits coast", h(1.0), image = "https://e/new.jpg", lang = "en", serverStoryId = "s1"), ), ).single() assertEquals(h(5.0), story.firstSeenMillis)@@ -91,77 +132,76 @@ class StoryGroupingTest { assertTrue(story.matchesCategory(NewsCategory.TECHNOLOGY), "category matches any member") } - @Test fun serverGroupingWinsAndNeverMergesDifferentServerStories() {- val stories = StoryGrouping.group(- listOf(- // Server groups these despite unrelated headlines/times.- a("bbc", "https://e/1", "First angle on the event", h(50.0), serverStoryId = "s1", oneLiner = "One line."),- a("dw", "https://e/2", "Completely different wording here", h(1.0), serverStoryId = "s1"),- // Identical headline but a different server story: must not merge in.- a("npr", "https://e/3", "First angle on the event", h(1.0), serverStoryId = "s2"),- // Ungrouped identical headline may join s2's story via client rules? It has no server id,- // exact + within window vs e/3, so it joins s2 (allowed), never s1.- a("guardian", "https://e/4", "First angle on the event", h(1.0)),- ),- )- assertEquals(2, stories.size)- assertTrue(stories.none { story ->- story.articles.any { it.url == "https://e/1" } && story.articles.any { it.url == "https://e/3" }- }, "different server stories must never be bridged by an ungrouped article")- val s1 = stories.first { it.articles.any { a -> a.url == "https://e/1" } }- assertEquals("srv:s1", s1.id)- assertEquals("One line.", s1.oneLiner)- assertTrue(s1.articles.map { it.url }.containsAll(listOf("https://e/1", "https://e/2")))- assertNotEquals(s1.id, stories.first { it.serverStoryId == "s2" && it.id != s1.id }.id)- }-- @Test fun rankingFoldsCrossSourceBreadthAndLatestUsesLatestUpdate() {+ @Test fun rankingOrdersButNeverChangesMembership() {+ // Four same-headline articles the server grouped (s1) + a fresher singleton. val multi = (1..4).map { i ->- a("s$i", "https://e/m$i", "Storm hits coast as winds rise", h(24.0 - i))+ a("s$i", "https://e/m$i", "Storm hits coast as winds rise", h(24.0 - i), serverStoryId = "s1") } val single = listOf(a("solo", "https://e/solo", "Obscure local council meets", h(20.0))) val top = FeedRanking.rankStories(multi + single, FeedSort.TOP, now)- assertEquals("https://e/m1", top.first().representative.url, "4-source day-old beats 1-source fresher-ish")+ assertEquals(2, top.size, "ranking orders the 2 mechanical stories; it does not create or dissolve any")+ assertEquals(4, top.first { it.id == "srv:s1" }.articles.size) assertTrue(- FeedRanking.storyScore(top.first(), now) > FeedRanking.storyScore(- StoryGrouping.group(single).single(), now,- ),+ FeedRanking.storyScore(top.first { it.id == "srv:s1" }, now) >+ FeedRanking.storyScore(StoryGrouping.group(single).single(), now),+ "cross-source breadth (actual server membership) folds into Top ordering", )- // Latest: story whose latest update is newest wins even if it started earlier. val latest = FeedRanking.rankStories(multi + single, FeedSort.LATEST, now)- assertEquals(h(20.0).coerceAtLeast(0) * 0 + multi.maxOf { it.publishedAtMillis }, latest.first().latestMillis)+ assertEquals(2, latest.size)+ assertEquals(multi.maxOf { it.publishedAtMillis }, latest.first().latestMillis)+ // Without a shared storyId the same headlines stay 5 separate ranked rows.+ val ungrouped = (1..4).map { i ->+ a("s$i", "https://e/u$i", "Storm hits coast as winds rise", h(24.0 - i))+ }+ assertEquals(5, FeedRanking.rankStories(ungrouped + single, FeedSort.TOP, now).size) } @Test fun searchHitsSurfaceTheirStory() { val stories = StoryGrouping.group( listOf(- a("bbc", "https://e/1", "Storm hits coast as winds rise", h(5.0)),- a("dw", "https://e/2", "Winds rise as storm hits coast", h(1.0)),+ a("bbc", "https://e/1", "Storm hits coast as winds rise", h(5.0), serverStoryId = "s1"),+ a("dw", "https://e/2", "Winds rise as storm hits coast", h(1.0), serverStoryId = "s1"), a("npr", "https://e/3", "Markets rally on jobs data", h(1.0)), ), ) val surfaced = stories.orderedBySearchHits(listOf("https://e/3", "https://e/2")) assertEquals(2, surfaced.size) assertEquals(1, surfaced[0].articles.size)- assertEquals(2, surfaced[1].articles.size, "a body hit on one member surfaces the whole story")+ assertEquals(2, surfaced[1].articles.size, "a hit on one member surfaces its whole server story") } - @Test fun clustering2500ArticlesIsFastEnough() {- // 2,500 stubs: 500 repeating events x 5 outlets + distinct filler titles.- val articles = (0 until 500).flatMap { event ->+ @Test fun noLocalMergeCodePathsRemain() {+ // Grep-level equivalent (reflection, no file IO): StoryGrouping+ // exposes only the mechanical `group` entry point — no merge+ // predicate, candidate generation, feature extraction, or+ // similarity thresholds remain.+ val memberNames = StoryGrouping::class.java.declaredMethods.map { it.name } ++ StoryGrouping::class.java.declaredFields.map { it.name } ++ StoryGrouping::class.java.declaredClasses.map { it.simpleName }+ assertTrue(memberNames.none { it.contains("merge", ignoreCase = true) }, "local merge member remains: $memberNames")+ assertTrue(memberNames.none { it.contains("jaccard", ignoreCase = true) }, "similarity member remains: $memberNames")+ assertTrue(memberNames.none { it.contains("candidate", ignoreCase = true) }, "candidate generation remains: $memberNames")+ assertTrue(memberNames.none { it.contains("feature", ignoreCase = true) }, "feature extraction remains: $memberNames")+ assertTrue(memberNames.none { it.contains("window", ignoreCase = true) }, "time-window member remains: $memberNames")+ assertEquals(setOf("group"), StoryGrouping::class.java.declaredMethods.map { it.name }.filter { !it.startsWith("$") }.toSet())+ }++ @Test fun groupingManyArticlesIsMechanicalAndFast() {+ // 2,500 stubs: 500 server stories x 5 outlets + distinct filler titles+ // with identical wording but no storyId (must stay singleton).+ val grouped = (0 until 250).flatMap { event -> (0 until 5).map { outlet ->- a(- "s$outlet", "https://e/$event-$outlet",- "Event $event storm hits coast as winds rise",- h((event % 24).toDouble()),- )+ a("s$outlet", "https://e/$event-$outlet", "Event $event storm hits coast", h((event % 24).toDouble()), serverStoryId = "srv-$event") } }+ val ungrouped = (0 until 1250).map { i ->+ a("s${i % 5}", "https://e/u$i", "Event ${i % 250} storm hits coast", h(1.0))+ } val start = System.nanoTime()- val stories = StoryGrouping.group(articles)+ val stories = StoryGrouping.group(grouped + ungrouped) val elapsedMs = (System.nanoTime() - start) / 1_000_000- assertEquals(500, stories.size)+ assertEquals(250 + 1250, stories.size) println("StoryGrouping 2500 articles: ${elapsedMs}ms -> ${stories.size} stories")- assertTrue(elapsedMs < 5_000, "clustering 2500 took ${elapsedMs}ms")+ assertTrue(elapsedMs < 5_000, "grouping 2500 took ${elapsedMs}ms") } }
news/src/test/java/com/vayunmathur/news/domain/StoryServerFeedTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/StoryServerFeedTest.kt b/news/src/test/java/com/vayunmathur/news/domain/StoryServerFeedTest.ktindex f9ea688e83..13e064ec69 100644--- a/news/src/test/java/com/vayunmathur/news/domain/StoryServerFeedTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/StoryServerFeedTest.kt@@ -4,7 +4,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull -/** Server story fields: parsed when present, absent = client clustering. */+/** Server story fields: parsed when present, absent = singleton story (no client grouping). */ class StoryServerFeedTest { @Test fun parsesStoryFieldsAndIgnoresExtractedText() { val json = """@@ -21,8 +21,10 @@ class StoryServerFeedTest { assertEquals("A summary.", parsed[0].storyOneLiner) assertEquals("Canonical", parsed[0].serverStoryTitle) assertNull(parsed[1].serverStoryId)- // No field on FeedArticle can carry extracted text; grouping uses story_id.+ // No field on FeedArticle can carry extracted text; grouping uses story_id only. val stories = StoryGrouping.group(parsed)+ assertEquals(2, stories.size, "the article without story_id stays a singleton") assertEquals("srv:abc", stories.first { it.serverStoryId == "abc" }.id)+ assertEquals(1, stories.first { it.serverStoryId == null }.articles.size) } }