Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Agent Note: 今日选题滚动加载的分页口径

Status: implemented — #218,Worker 实施

## Problem

今日选题页 `/today-picks` 原来的「加载更多」按钮是**按累计条数重选**,不是**按页追加**:

- 前端把 `limit` 从 40 逐步放大(40 → 80 → 120 → 200),每次整表重新请求、整表替换。
- 每批都重传全量:第 4 次点击传 160 条完整卡片载荷,而不是新增的 40 条。
- 后端 `limit` 上限 200(`contents.py` 的 `le=200`),所以最多点 4 次,第 5 次必然 422——
越往后越加载不动。
- 交互割裂:必须主动点按钮才能看到后续内容。

## Decision

改成**后端真分页 + 滚动自动加载**:`GET /contents/today-picks` 增加 `offset` 参数,
前端用 `IntersectionObserver` 在滚动到底时自动接下一批,按钮保留作兜底
(触屏 / 无障碍 / 自动加载失败时仍可手动展开)。

### 为什么不能用「拉大 limit」当追加

这是本次最关键的一条:**当日精选的选池本身依赖 `limit`**。

`_select_personalized_slate(scored_rows, boosts, limit)` 里,探索位与个人位按 limit 的
比例分配(`explore_slots = min(limit-1, round(limit*0.2))`),个人位取
`limit - explore_slots` 条。limit 一变,选出来的**集合和顺序都会变**。

用 30 组随机 boosts / 评分实测 `limit=40 → 80 → 120`:

- 集合单调增(不会丢条目)✔
- 已显示条目的相对顺序保持 ✔
- **但不是严格前缀** ✘ —— 新条目会插到中间位置。

也就是说,拉大 limit 实为**重选**:用户点一次按钮,已经看过的卡片会被重新洗牌。
这既不是追加,也就谈不上增量加载。

### 选池改为按页推进

`_select_personalized_slate` 改成**逐页推进**:个人位与探索位各自从各自的序里往后取,
已发出的条目不再进入后续页。这样同一入选池 + 同一 limit 下,第 k 页一定是第 1 页的
**稳定延续**——追加后续页不会重排已展示的条目,也不会重复或漏项。`offset` 只做切片,
不参与选池。

无 boost(匿名 / 无兴趣向量)时走基础序切片,行为与旧实现完全一致。

## 三条边界

### 1. 缓存键必须含 offset

`TodayPicksCacheParams` 加了 `offset` 字段并进 key。否则第 2 页会命中第 1 页的缓存,
把首屏内容重复发出去——这是会直接表现为「加载更多但内容不变」的错误。

缓存命名空间同步从 v6 提到 v7:响应新增了 `offset` / `has_more`,`page` / `page_size`
从写死的假值改成如实反映窗口,v6 的旧载荷对新前端是误导。

### 2. `total` 不随 limit / offset 变化

侧边栏徽标 `today_count` 只为拿 `total`(用 `limit=1` 调一次)。`total` 必须恒等于
入选池总数,否则分页参数会把徽标数带偏。回归测试锁住这一点。

### 3. 前端合并按 id 去重

翻页窗口内可能有新内容入库导致 offset 位移,后一页会重复出现上一页已加载的条目。
前端用 `mergePickPage` 按 id 去重后再追加(与首页 `mergeItemsById` 同一口径)。
下一批的 `offset` 用**实际已加载条数**而不是已请求条数,这样位移造成的缺口能被补回。

### 4. 追加页的话题分组必须一起合并

后端每页只返回**该页条目涉及**的话题(`visible_topics` 按本页 `topic_ids` 过滤)。
话题视图按话题列表分组渲染,追加页引入的新话题如果不并进已加载话题,
该话题下的条目就会因为没有对应分组而**整个消失**。

实测(注入两个话题:话题 1 在第 1 页、话题 2 在第 2 页,滚动加载后展开全部):
不合并时只剩 40/80 条、话题 2 分组不渲染;合并后 80 条齐全。

顺带一提:话题分组默认折叠,每组只显示 3 条(`sortedItems.slice(0, 3)`),
这是既有设计不是缺陷——核对条目数量时要先展开,否则会误判为丢内容。

## 本页滚动容器的坑

今日选题页的滚动容器**不是 window**。`ClientLayout.tsx` 里是
`<div className="min-h-0 flex-1 overflow-auto">`,根节点 `h-dvh overflow-hidden`,
window 根本不滚动(实测 `HTML.scrollHeight === clientHeight === 900`)。

所以滚动加载必须用 `IntersectionObserver`,不能用 window scroll 事件——scroll 事件不
冒泡到 window,监听 window 收不到。同 `admin/settings` 的既有做法。

## Alternatives considered

- **保留「拉大 limit」,只在前端按 id 去重**:能消除重复卡片,但已看条目仍会被重新洗牌,
且每批重传全量、200 条天花板依旧。不解决根本问题。
- **给今日选题也绑浏览快照(首页那套 `feed_snapshot` + 409)**:首页需要是因为它的
折叠事件顺序会随归并纠错变化。today-picks 不走事件折叠快照,且本次目标是滚动加载,
引入快照会让「顺序变了就 409、要求刷新列表」变成常态体验。先不做;真出现顺序漂移
问题再评估。
- **纯滚动加载、去掉按钮**:触屏与无障碍场景失去手动展开的入口。保留按钮兜底。

## Consequences

- 今日选题与首页的加载策略一致了:都是真分页 + 按 id 去重追加。
- 后端每批只返回新增条目,传输量随批次线性增长而不是平方增长。
- 200 条天花板解除。
- 本地库的分数在 percentile 门槛下可能全被筛掉(`selected` 全为 false),此时
today-picks 返回 0 条属既有环境状态,不是本次改动引入的。

## 回归入口

```bash
cd backend && .venv/bin/python -m pytest tests/test_today_picks.py -q
cd frontend && npx vitest run src/app/today-picks/_paging.test.ts
```
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ TopicEye 是内容创作者的选题雷达。agent 接口见 [AGENT_API.md](AGEN
| 范围 | 入口 |
|---|---|
| 事件归并、分页与生产启用门槛 | [事件合同与启用边界](.agents/notes/implemented/feature/2026-10-24-content-event-contract.md) |
| 今日选题滚动加载与分页口径 | [今日选题分页口径](.agents/notes/implemented/feature/2026-11-03-today-picks-scroll-paging.md) |
| MCP OAuth 与 client 清理运维 | [client 清理理由与运行合同](.agents/notes/implemented/architecture/2026-10-24-mcp-client-gc-history.md) |
| SelectBench 手动抽样、校准与导入 | [离线校准与导入合同](.agents/notes/implemented/verification/2026-10-24-selectbench-contract.md) |
| 依赖审计口径与例外复核 | [审计口径与例外复核](.agents/notes/implemented/risk/2026-10-24-dependency-audit-contract.md) |
Expand Down
3 changes: 3 additions & 0 deletions backend/app/api/v1/contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ async def today_picks(
content_type: str | None = Query(None, description="Filter by content type (论文/技术/资讯/...)"),
time_range: str | None = Query(None, description="Time range: 24h, 48h, 7d"),
limit: int | None = Query(None, ge=1, le=200, description="Limit returned items while preserving total"),
offset: int = Query(0, ge=0, description="已加载条数:从第 offset 条继续取,用于滚动加载后续页"),
current_user: User | None = Depends(get_optional_current_user),
):
"""Top picks visible to the current user (public pool plus own private sources)."""
Expand All @@ -343,6 +344,7 @@ async def today_picks(
content_type=content_type,
hours={"24h": 24, "7d": 168}.get(time_range or "", 48),
limit=limit,
offset=offset,
user_id=current_user.id if current_user is not None else None,
)
try:
Expand Down Expand Up @@ -373,6 +375,7 @@ async def today_picks(
"content_type": content_type,
"hours": params.hours,
"limit": params.limit,
"offset": params.offset,
}
if current_user is not None:
build_kwargs["owner_user_id"] = current_user.id
Expand Down
85 changes: 61 additions & 24 deletions backend/app/services/today_picks.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,21 @@ def _select_personalized_slate(
scored_rows: list[tuple[ScoreBreakdown, dict]],
boosts: dict[int, float],
limit: int | None,
*,
offset: int = 0,
) -> list[tuple[ScoreBreakdown, dict]]:
"""个性化优先的最终页选择(纯函数,便于测试)。

- boosts 为空(匿名 / 无兴趣向量 / 无任何标签匹配):返回与基础
排序完全一致的前 limit 条——新用户与匿名行为不变;
- 有 boost:先按 ``final_score + boost`` 取 personal_slots 条,再从
基础序补 explore_slots 条探索位,最终 slate 按加成分排序。
截断前对完整入选池生效,基础排名靠后的高兴趣内容可以进入首屏。
排序完全一致的第 offset 起 limit 条——新用户与匿名行为不变;
- 有 boost:按「个人位 + 探索位」逐页推进,每页 personal_slots 条按
``final_score + boost`` 排,explore_slots 条从基础序补探索位,页内
再按加成分排序。截断前对完整入选池生效,基础排名靠后的高兴趣内容
可以进入首屏。

选池按页推进(而不是按累计条数重选),因此同一入选池 + 同一 limit 下
第 k 页一定是第 1 页的稳定延续:追加后续页不会重排已展示的条目,也不
会重复或漏项(#218)。offset 只做切片,不参与选池。
"""

def boosted_key(idx: int) -> float:
Expand All @@ -58,35 +65,51 @@ def boosted_key(idx: int) -> float:

if not limit:
if not boosts:
return list(scored_rows)
return list(scored_rows[offset:])
ordered = sorted(range(len(scored_rows)), key=lambda i: (-boosted_key(i), i))
return [scored_rows[i] for i in ordered]
return [scored_rows[i] for i in ordered[offset:]]

if not boosts:
return list(scored_rows[:limit])
return list(scored_rows[offset : offset + limit])

explore_slots = min(limit - 1, round(limit * _EXPLORE_RATIO)) if limit > 1 else 0
personal_slots = limit - explore_slots

base_order = sorted(range(len(scored_rows)), key=lambda i: (-scored_rows[i][0].final_score, i))
personal_order = sorted(range(len(scored_rows)), key=lambda i: (-boosted_key(i), i))

slate: list[int] = []
seen: set[int] = set()
for i in personal_order:
if len(slate) >= personal_slots:
break
slate.append(i)
seen.add(i)
for i in base_order:
if len(slate) >= limit:
# 逐页推进:个人位与探索位各自从各自的序里往后取,已发出的条目不再
# 重复进入后续页。这样第 k 页的内容与前 k-1 页不重叠,页内顺序也稳定。
emitted: set[int] = set()
personal_cursor = 0
base_cursor = 0
selected: list[tuple[ScoreBreakdown, dict]] = []
page_start = 0
while page_start < offset + limit:
page: list[int] = []
while len(page) < personal_slots and personal_cursor < len(personal_order):
idx = personal_order[personal_cursor]
personal_cursor += 1
if idx in emitted:
continue
page.append(idx)
emitted.add(idx)
while len(page) < limit and base_cursor < len(base_order):
idx = base_order[base_cursor]
base_cursor += 1
if idx in emitted:
continue
page.append(idx)
emitted.add(idx)
if not page:
break
if i not in seen:
slate.append(i)
seen.add(i)
page.sort(key=lambda i: (-boosted_key(i), i))
if page_start + len(page) > offset:
skip = max(0, offset - page_start)
selected.extend(scored_rows[i] for i in page[skip:])
page_start += len(page)

slate.sort(key=lambda i: (-boosted_key(i), i))
return [scored_rows[i] for i in slate]
return selected[:limit]


@dataclass
Expand Down Expand Up @@ -206,6 +229,7 @@ async def build_today_picks(
content_type: str | None = None,
hours: int = 48,
limit: int | None = None,
offset: int = 0,
owner_user_id: int | None = None,
) -> dict:
"""Return today-picks payload through DuckDB, with OLTP fallback.
Expand Down Expand Up @@ -272,7 +296,7 @@ async def build_today_picks(
logger.warning("personalization boost computation failed; using base order", exc_info=True)
boosts = {}

visible_rows = _select_personalized_slate(scored_rows, boosts, limit)
visible_rows = _select_personalized_slate(scored_rows, boosts, limit, offset=offset)
response_items = [_row_to_content_payload(row, breakdown) for breakdown, row in visible_rows]
for item in response_items:
boost = boosts.get(int(item["id"]), 0.0)
Expand Down Expand Up @@ -320,6 +344,8 @@ async def build_today_picks(
total=total,
event_members_hidden=hidden_member_count,
pending_review=pending_review,
limit=limit,
offset=offset,
)


Expand Down Expand Up @@ -484,6 +510,9 @@ def _empty_payload() -> dict:
"topics": [],
"page": 1,
"page_size": 0,
# 空结果也要带齐分页字段:前端据此判断是否还有下一页(#218)
"offset": 0,
"has_more": False,
}


Expand Down Expand Up @@ -678,15 +707,23 @@ def _pack_today_picks(
total: int,
event_members_hidden: int = 0,
pending_review: dict | None = None,
limit: int | None = None,
offset: int = 0,
) -> dict:
topic_ids = {item.get("topic_id") for item in items if item.get("topic_id")}
visible_topics = [topic for topic in topic_map.values() if topic["id"] in topic_ids]
# 分页信息:page / page_size 如实反映本次请求的窗口,has_more 说明后面还有内容。
# 旧实现把 page 写死为 1、page_size 写成实际返回条数,前端无法据此判断是否还有下一页。
page_size = len(items)
page = (offset // page_size + 1) if page_size else 1
return {
"items": items,
"total": total,
"event_members_hidden": event_members_hidden,
"topics": visible_topics,
"pending_review": pending_review or {"items": [], "total": 0},
"page": 1,
"page_size": len(items),
"page": page,
"page_size": page_size,
"offset": offset,
"has_more": offset + page_size < total,
}
10 changes: 8 additions & 2 deletions backend/app/services/today_picks_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
# would make an older serialized payload unsafe or misleading to display.
# This prevents pre-cleanup AI summaries from being served until their TTL.
TODAY_PICKS_LEGACY_CACHE_PREFIX = "contents:today-picks:"
TODAY_PICKS_CACHE_PREFIX = "contents:today-picks:v6:"
# v7:分页响应新增 offset / has_more,page / page_size 改为如实反映窗口(#218)。
# v6 的载荷对新的分页前端是误导,不能继续命中。
TODAY_PICKS_CACHE_PREFIX = "contents:today-picks:v7:"
# The page opens on the rolling 24-hour window and requests the first 40 picks.
# Keep the startup warmup key identical so the first visit can hit the cache.
TODAY_PICKS_DEFAULT_CACHE_LABEL = "contents:today-picks:v6:hours=24&limit=40"
TODAY_PICKS_DEFAULT_CACHE_LABEL = "contents:today-picks:v7:hours=24&limit=40"
TODAY_PICKS_INITIAL_LIMIT = 40


Expand All @@ -22,6 +24,8 @@ class TodayPicksCacheParams:
category: str | None = None
content_type: str | None = None
limit: int | None = None
# 分页偏移:必须进缓存键,否则第 2 页会命中第 1 页的缓存,把首屏内容重复发出去(#218)。
offset: int = 0
# None = anonymous public pool; int = public pool plus this user's private content.
user_id: int | None = None
event_revision: str = ""
Expand All @@ -35,6 +39,8 @@ def key(self) -> str:
params["content_type"] = self.content_type
if self.limit:
params["limit"] = self.limit
if self.offset:
params["offset"] = self.offset
params["user_id"] = "" if self.user_id is None else str(self.user_id)
if self.event_revision:
params["event_revision"] = self.event_revision
Expand Down
8 changes: 6 additions & 2 deletions backend/tests/test_cache_warmup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
invalidate_scoring_flow_cache,
)
from app.services.source_cache import default_source_list_cache_params
from app.services.today_picks_cache import default_today_picks_cache_params
from app.services.today_picks_cache import (
TODAY_PICKS_DEFAULT_CACHE_LABEL,
default_today_picks_cache_params,
)

STATS_WORKSPACE_CACHE_KEYS = {
"stats:overview:30",
Expand Down Expand Up @@ -143,7 +146,8 @@ async def test_warmup_read_caches_populates_hot_read_cache_keys(cache_warmup_ses
expected_warmed = {
"sources:list:1:20",
"contents:list:1:40:24",
"contents:today-picks:v6:hours=24&limit=40",
# 引用常量而不是硬编码版本号:缓存命名空间 bump 时不必再改这里(#218)
TODAY_PICKS_DEFAULT_CACHE_LABEL,
"contents:favorites:list:1:20",
}
expected_warmed.update(STATS_WORKSPACE_CACHE_KEYS)
Expand Down
3 changes: 3 additions & 0 deletions backend/tests/test_content_event_consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,9 @@ async def fail_resolution(*_args, **_kwargs):
"topics": [],
"page": 1,
"page_size": 0,
# 空结果也要带齐分页字段,前端据此判断是否还有下一页(#218)
"offset": 0,
"has_more": False,
}


Expand Down
Loading
Loading