From 3bc452b5b72f88cd5ca79f1b91caa764f7b4befb Mon Sep 17 00:00:00 2001 From: Huang Xin Date: Sun, 29 Nov 2026 02:55:21 +0800 Subject: [PATCH] fix(sync): date page-event speed by its first sample, read events with it From CodeRabbit's review of 2d91afea8: - A page event's speed now keeps the start of its first sample, per language and unit (`startTimeMs` in ext), and its rows are dated by it. A sample that a later page carries after an idle pause stays on the day and quarter hour it was read in. Keyed by that millisecond, two pages of a book that start in the same second no longer share a key and drop one page's speed. - The push read and the merge push's read of a book's events take the write lock. An event and its speed are saved in two statements, and a push that read the event alone moved its cursor past the speed. - Backups write the page events as they are, so they now carry speed too. Applying events from another device or a backup keeps only the speed this version can read: an entry the table rejects would roll back the whole statistics restore. Verified: - Each new test fails without its fix on an assertion: "expected [] to deeply equal [ { startTimeMs: 86280000, ... } ]" (dated by the carrier), "count: 30 to deeply equal count: 60" (same-second pages), "expected [ undefined ] to deeply equal [ [ { lang: 'en', ... } ] ]" (push and merge reads), "promise rejected ... CHECK constraint failed ... instead of resolving" (unreadable speed from a backup). The tracker test fails on the missing sample start. - 6692 tests in 505 files (statistics, components/stats, pages/api, libs, services) and pnpm lint pass. - dev-web on the self-hosted stack with main's server schema, new account, two fresh devices: the server rows carry startTimeMs; both devices show English 388 words/min, the total of those rows. Co-Authored-By: Claude Opus 5.5 --- .../statistics/ReadingStatsTracker.test.tsx | 3 +- .../statistics/pageSpeedSync.test.ts | 11 +- .../__tests__/statistics/statisticsDb.test.ts | 121 +++++++++++++++++- .../__tests__/statistics/statsDelete.test.ts | 10 +- .../__tests__/statistics/statsMerge.test.ts | 10 +- .../src/services/statistics/readingSpeed.ts | 6 +- .../src/services/statistics/statisticsDb.ts | 52 +++++--- apps/readest-app/src/types/statistics.ts | 4 +- 8 files changed, 185 insertions(+), 32 deletions(-) diff --git a/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx b/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx index edb6d2df8..1e461ccfb 100644 --- a/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx +++ b/apps/readest-app/src/__tests__/statistics/ReadingStatsTracker.test.tsx @@ -145,6 +145,7 @@ describe('ReadingStatsTracker while TTS plays', () => { [750, 180_000], ])('saves the %i words passed during a forward turn after %i ms with a page event', async (words, ms) => { const openPage = pageOf(words); + const startTimeMs = Date.now(); openPage(0); const { rerender, unmount } = mount(); await settle(ms); @@ -156,7 +157,7 @@ describe('ReadingStatsTracker while TTS plays', () => { const saved = mocks.db.recordEvents.mock.calls.flatMap(([, events]) => events); expect(saved.filter((e) => e.speed).map((e) => e.speed)).toEqual([ - [{ lang: 'en', unit: 'words', count: words, durationMs: ms }], + [{ lang: 'en', unit: 'words', count: words, durationMs: ms, startTimeMs }], ]); }); diff --git a/apps/readest-app/src/__tests__/statistics/pageSpeedSync.test.ts b/apps/readest-app/src/__tests__/statistics/pageSpeedSync.test.ts index 62047866b..736e18e72 100644 --- a/apps/readest-app/src/__tests__/statistics/pageSpeedSync.test.ts +++ b/apps/readest-app/src/__tests__/statistics/pageSpeedSync.test.ts @@ -48,8 +48,14 @@ function server() { } const BOOK = { bookMd5: 'm1', title: 'Book', authors: 'A' }; -const en: PageSpeed = { lang: 'en', unit: 'words', count: 250, durationMs: 60_000 }; -const fr: PageSpeed = { lang: 'fr', unit: 'words', count: 40, durationMs: 15_000 }; +const en: PageSpeed = { + lang: 'en', + unit: 'words', + count: 250, + durationMs: 60_000, + startTimeMs: 100_000, +}; +const fr: PageSpeed = { ...en, lang: 'fr', count: 40, durationMs: 15_000, startTimeMs: 160_400 }; describe('reading speed in page events', () => { it('counts on another device, and once when a device pulls its own events', async () => { @@ -125,6 +131,7 @@ describe('reading speed in page events', () => { { ...en, count: -1 }, { ...en, durationMs: 1.5 }, { ...en, lang: 7 }, + { ...en, startTimeMs: undefined }, null, en, ], diff --git a/apps/readest-app/src/__tests__/statistics/statisticsDb.test.ts b/apps/readest-app/src/__tests__/statistics/statisticsDb.test.ts index d9e6760f2..9a5564219 100644 --- a/apps/readest-app/src/__tests__/statistics/statisticsDb.test.ts +++ b/apps/readest-app/src/__tests__/statistics/statisticsDb.test.ts @@ -6,6 +6,7 @@ import { getMigrations } from '@/services/database/migrations'; import type { DatabaseService } from '@/types/database'; import type { AppService } from '@/types/system'; import { StatisticsDb } from '@/services/statistics/statisticsDb'; +import type { PageSpeed } from '@/types/statistics'; async function freshStatsDb(): Promise { // In-memory libsql DB; run the same migrations production uses. @@ -114,7 +115,7 @@ describe('StatisticsDb', () => { stats = StatisticsDb.from(await freshStatsDb()); }); - // Speed is saved with the page event it rode on, and its rows start there. + // Speed is saved with the page event it rode on, from its first sample's start. const readAt = ( md5: string, startTime: number, @@ -122,9 +123,117 @@ describe('StatisticsDb', () => { title = md5, ) => stats.recordEvents({ bookMd5: md5, title, authors: '' }, [ - { page: 1, startTime, duration: speed.durationMs / 1000, totalPages: 9, speed: [speed] }, + { + page: 1, + startTime, + duration: speed.durationMs / 1000, + totalPages: 9, + speed: [{ ...speed, startTimeMs: startTime * 1000 }], + }, ]); + it('dates speed by its first sample, not by the page event that carried it', async () => { + // An idle pause saved the page; the next page, opened after midnight, carries its sample. + const midnight = 86_400_000; + const speed = { lang: 'en', unit: 'words' as const, count: 500, durationMs: 150_000 }; + await stats.recordEvents({ bookMd5: 'm1', title: 'm1', authors: '' }, [ + { + page: 2, + startTime: midnight / 1000 + 30, + duration: 20, + totalPages: 9, + speed: [{ ...speed, startTimeMs: midnight - 120_000 }], + }, + ]); + expect(await stats.getReadingSpeedSamples(midnight - 900_000, midnight)).toEqual([ + { startTimeMs: midnight - 120_000, unit: 'words', count: 500, durationMs: 150_000 }, + ]); + expect((await stats.getBookReadingSpeeds())[0]!.lastRead).toBe(midnight + 30_000); + }); + + it('keeps only the speed it can read from another device or a backup', async () => { + const speed = { lang: 'en', unit: 'words', count: 30, durationMs: 20_000, startTimeMs: 50_000 }; + const event = { + bookMd5: 'm1', + page: 1, + startTime: 50, + duration: 20, + totalPages: 9, + speed: [{ ...speed, unit: 'syllables' } as unknown as PageSpeed, speed as PageSpeed], + }; + await expect(stats.applyRemoteEvents([], [event])).resolves.toBeUndefined(); + expect(await stats.getReadingTotals()).toMatchObject({ seconds: 20 }); + expect(await stats.getReadingSpeedTotals()).toEqual([ + { unit: 'words', count: 30, durationMs: 20_000 }, + ]); + }); + + it('counts two pages of a book that start in the same second', async () => { + // e.g. the same book in both panes of split view, or on two devices + const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 }; + await stats.recordEvents({ bookMd5: 'm1', title: 'm1', authors: '' }, [ + { + page: 1, + startTime: 50, + duration: 20, + totalPages: 9, + speed: [{ ...speed, startTimeMs: 50_000 }], + }, + ]); + await stats.applyRemoteEvents( + [], + [ + { + bookMd5: 'm1', + page: 7, + startTime: 50, + duration: 20, + totalPages: 9, + speed: [{ ...speed, startTimeMs: 50_400 }], + }, + ], + ); + expect(await stats.getReadingSpeedTotals()).toEqual([ + { unit: 'words', count: 60, durationMs: 40_000 }, + ]); + }); + + it.each([ + ['getEventsForPush', (s: StatisticsDb) => s.getEventsForPush(0).then((r) => r.events)], + ['getBookEvents', (s: StatisticsDb) => s.getBookEvents('m1')], + ])('%s reads an event with its speed, not between the two', async (_, read) => { + // A push that read the event alone would move its cursor past the speed. + const db = await freshStatsDb(); + const shared = StatisticsDb.from(db); + const execute = db.execute.bind(db); + let release!: () => void; + const held = new Promise((resolve) => (release = resolve)); + let reached!: () => void; + const atSpeed = new Promise((resolve) => (reached = resolve)); + vi.spyOn(db, 'execute').mockImplementation(async (sql, params) => { + if (sql.includes('INSERT INTO readest_page_ext')) { + reached(); + await held; + } + return execute(sql, params); + }); + const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 }; + const write = shared.recordEvents({ bookMd5: 'm1', title: 'm1', authors: '' }, [ + { + page: 1, + startTime: 50, + duration: 20, + totalPages: 9, + speed: [{ ...speed, startTimeMs: 50_000 }], + }, + ]); + await atSpeed; + const events = read(shared); + release(); + await write; + expect((await events).map((e) => e.speed)).toEqual([[{ ...speed, startTimeMs: 50_000 }]]); + }); + it('keeps speed idempotent and queries intervals that start before the boundary', async () => { const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 }; await readAt('m1', 50, speed); @@ -220,7 +329,13 @@ describe('StatisticsDb', () => { const speed = { lang: 'en', unit: 'words' as const, count: 30, durationMs: 20_000 }; const write = shared.recordEvents({ bookMd5: 'local', title: 'Local', authors: '' }, [ - { page: 1, startTime: 50, duration: 20, totalPages: 9, speed: [speed] }, + { + page: 1, + startTime: 50, + duration: 20, + totalPages: 9, + speed: [{ ...speed, startTimeMs: 50_000 }], + }, ]); // If the insert bypasses the transaction queue, let it finish before rollback. if (execute.mock.calls.some(([sql]) => sql.includes('INSERT INTO readest_reading_speed'))) { diff --git a/apps/readest-app/src/__tests__/statistics/statsDelete.test.ts b/apps/readest-app/src/__tests__/statistics/statsDelete.test.ts index c765229ac..b71f95d7a 100644 --- a/apps/readest-app/src/__tests__/statistics/statsDelete.test.ts +++ b/apps/readest-app/src/__tests__/statistics/statsDelete.test.ts @@ -31,7 +31,15 @@ const event = (page: number, startTime: number, count: number) => ({ startTime, duration: 10, totalPages: 50, - speed: [{ lang: 'en', unit: 'words' as const, count, durationMs: 10_000 }], + speed: [ + { + lang: 'en', + unit: 'words' as const, + count, + durationMs: 10_000, + startTimeMs: startTime * 1000, + }, + ], }); const wirePage = (book_hash: string, start_time: number, extra: object = {}) => ({ diff --git a/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts b/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts index 99068653e..f0896981b 100644 --- a/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts +++ b/apps/readest-app/src/__tests__/statistics/statsMerge.test.ts @@ -58,7 +58,15 @@ describe('mergeBook', () => { startTime, duration: 10, totalPages: 50, - speed: [{ lang: 'en', unit: 'words' as const, count, durationMs: 10_000 }], + speed: [ + { + lang: 'en', + unit: 'words' as const, + count, + durationMs: 10_000, + startTimeMs: startTime * 1000, + }, + ], }); // split view can open page 1 of both books in the same second: after the // merge it is one event, and its speed counts once diff --git a/apps/readest-app/src/services/statistics/readingSpeed.ts b/apps/readest-app/src/services/statistics/readingSpeed.ts index 567951532..6fdd87b00 100644 --- a/apps/readest-app/src/services/statistics/readingSpeed.ts +++ b/apps/readest-app/src/services/statistics/readingSpeed.ts @@ -143,16 +143,16 @@ const countPassedUnits = (passed: Range, language: string) => { }; }; -/** Sum samples per language and unit, as a page event carries them. */ +/** Sum samples, oldest first, per language and unit, as a page event carries them. */ export const sumPageSpeed = (samples: ReadingSpeedSample[]): PageSpeed[] => { const sums = new Map(); - for (const { lang = '', unit, count, durationMs } of samples) { + for (const { lang = '', unit, count, durationMs, startTimeMs } of samples) { const sum = sums.get(`${lang}:${unit}`); if (sum) { sum.count += count; sum.durationMs += durationMs; } else { - sums.set(`${lang}:${unit}`, { lang, unit, count, durationMs }); + sums.set(`${lang}:${unit}`, { lang, unit, count, durationMs, startTimeMs }); } } return [...sums.values()]; diff --git a/apps/readest-app/src/services/statistics/statisticsDb.ts b/apps/readest-app/src/services/statistics/statisticsDb.ts index 7a382d9e8..c4e75dcaa 100644 --- a/apps/readest-app/src/services/statistics/statisticsDb.ts +++ b/apps/readest-app/src/services/statistics/statisticsDb.ts @@ -32,12 +32,13 @@ const MAX_PAGE_SECONDS = DEFAULT_STATS_TRACKING_CONFIG.maxEventSeconds; const isPositiveInt = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0; const isPageSpeed = (s: unknown): s is PageSpeed => { - const { lang, unit, count, durationMs } = (s ?? {}) as Partial; + const { lang, unit, count, durationMs, startTimeMs } = (s ?? {}) as Partial; return ( typeof lang === 'string' && (unit === 'words' || unit === 'characters') && isPositiveInt(count) && - isPositiveInt(durationMs) + isPositiveInt(durationMs) && + isPositiveInt(startTimeMs) ); }; @@ -48,9 +49,13 @@ const isPageSpeed = (s: unknown): s is PageSpeed => { export const readPageSpeed = (ext: unknown): PageSpeed[] | undefined => { const speed = (ext as { speed?: unknown } | null)?.speed; if (!Array.isArray(speed)) return undefined; - const valid = speed - .filter(isPageSpeed) - .map(({ lang, unit, count, durationMs }) => ({ lang, unit, count, durationMs })); + const valid = speed.filter(isPageSpeed).map(({ lang, unit, count, durationMs, startTimeMs }) => ({ + lang, + unit, + count, + durationMs, + startTimeMs, + })); return valid.length ? valid : undefined; }; @@ -274,9 +279,10 @@ export class StatisticsDb { /** * Keep the speed a page event carries: as the event's ext, and as rows for - * the speed queries, starting where the event does. Every device does this - * for every event it holds, so one it already has, such as its own coming - * back from the server, meets the same keys and changes nothing. + * the speed queries, dated by their first sample (a page can carry one that + * started before it). Every device does this for every event it holds, so + * one it already has, such as its own coming back from the server, meets + * the same keys and changes nothing. */ private async insertPageSpeed( md5: string, @@ -288,12 +294,11 @@ export class StatisticsDb { ON CONFLICT DO NOTHING`, [md5, e.page, e.startTime, JSON.stringify({ speed: e.speed })], ); - for (const [i, speed] of e.speed.entries()) { - // A millisecond apart: two languages in one event don't share a key. + for (const speed of e.speed) { await this.db.execute( `INSERT INTO readest_reading_speed (start_time_ms, book_md5, unit, count, duration_ms, lang) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`, - [e.startTime * 1000 + i, md5, speed.unit, speed.count, speed.durationMs, speed.lang], + [speed.startTimeMs, md5, speed.unit, speed.count, speed.durationMs, speed.lang], ); } } @@ -362,8 +367,11 @@ export class StatisticsDb { async getEventsForPush( sinceStartTime: number, ): Promise<{ events: PageStatEvent[]; books: StatBook[] }> { - const rows = await this.db.select( - `SELECT b.md5 AS bookMd5, b.title AS title, b.authors AS authors, + // Under the write lock: an event and its speed are saved in two statements, + // and a push that read the event alone would move its cursor past the speed. + const rows = await this.exclusive(() => + this.db.select( + `SELECT b.md5 AS bookMd5, b.title AS title, b.authors AS authors, p.page AS page, p.start_time AS startTime, p.duration AS duration, p.total_pages AS totalPages, x.ext AS ext FROM page_stat_data p JOIN book b ON b.id = p.id_book @@ -371,7 +379,8 @@ export class StatisticsDb { ON x.book_hash = b.md5 AND x.page = p.page AND x.start_time = p.start_time WHERE p.start_time > ? ORDER BY p.start_time ASC`, - [sinceStartTime], + [sinceStartTime], + ), ); const events: PageStatEvent[] = rows.map((r) => ({ bookMd5: String(r['bookMd5']), @@ -400,13 +409,13 @@ export class StatisticsDb { // one's still-open BEGIN ("cannot start a transaction within a transaction", // Sentry READEST-N). The per-op native lock can't make a multi-statement // transaction atomic on its own, so pulls and deletions run one at a time. - private async exclusive(work: () => Promise): Promise { + private async exclusive(work: () => Promise): Promise { const prev = this.writeLock; let release!: () => void; this.writeLock = new Promise((resolve) => (release = resolve)); await prev; try { - await work(); + return await work(); } finally { release(); } @@ -430,8 +439,12 @@ export class StatisticsDb { await this.exclusive(() => this.deleteEventsBefore(md5, Number.MAX_SAFE_INTEGER)); } - /** Every page event of a book, oldest first. */ + /** Every page event of a book with its speed, oldest first. */ async getBookEvents(md5: string): Promise { + return this.exclusive(() => this.selectBookEvents(md5)); + } + + private async selectBookEvents(md5: string): Promise { const rows = await this.db.select<{ page: number; startTime: number; @@ -474,7 +487,7 @@ export class StatisticsDb { await this.exclusive(async () => { await this.db.execute('BEGIN'); try { - const events = await this.getBookEvents(source); + const events = await this.selectBookEvents(source); const id = await this.upsertBook(target); for (const e of events) { await this.insertPageEvent(id, e); @@ -545,7 +558,8 @@ export class StatisticsDb { idByMd5.set(e.bookMd5, id); } await this.insertPageEvent(id, e); - await this.insertPageSpeed(e.bookMd5, e); + // From another device or a backup: keep only the speed this version can read. + await this.insertPageSpeed(e.bookMd5, { ...e, speed: readPageSpeed(e) }); touched.add(id); } for (const id of touched) await this.recomputeBookTotals(id); diff --git a/apps/readest-app/src/types/statistics.ts b/apps/readest-app/src/types/statistics.ts index 863851063..5597c641b 100644 --- a/apps/readest-app/src/types/statistics.ts +++ b/apps/readest-app/src/types/statistics.ts @@ -45,8 +45,8 @@ export type ReadingSpeed = { /** `lang` is the base language the text was counted in ('en', 'zh'), or '' when unknown. */ export type ReadingSpeedSample = ReadingSpeed & { startTimeMs: number; lang?: string }; -/** The speed samples a page event carries, summed per language and unit. */ -export type PageSpeed = ReadingSpeed & { lang: string }; +/** The speed samples a page event carries, summed per language and unit from the first one's start. */ +export type PageSpeed = ReadingSpeedSample & { lang: string }; /** Tunables for the tracker's flush/idle behavior. KOReader-aligned defaults. */ export interface StatsTrackingConfig {