mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
3 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
64d594380c
|
chore(scripts): add account inspector and account merge scripts for support (#6121)
Tooling for "please merge my two accounts" tickets, both under apps/readest-app/scripts/db and run with `node --env-file=.env --env-file=.env.local`. inspect-accounts.mjs is read-only: it resolves users by email through the GoTrue admin API and reports identities, per-table row counts, the plans row, payments, recent book titles for ownership verification, and the files rows checked against the objects actually present in R2, plus the book/file overlap between accounts. merge-accounts.mjs moves one account's cloud data into another account of the same person: server-side R2 CopyObject with a HEAD size check, re-pointing books / book_configs / book_notes / stat_* / replicas / files rows with the file_key prefix rewritten, newer-updated_at-wins on primary-key collisions, updated_at stamped on the tables whose sync pull keys on it, then plans.storage_usage_bytes recomputed on both users. Files rows with no object behind them (abandoned upload reservations) are left behind. Dry run by default; --apply writes. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
6834ee42ef
|
fix(stats): survive PostgREST's row cap when building archive segments (#5844)
* fix(stats): survive PostgREST's row cap when building archive segments stat_archive_rows is called through PostgREST, which caps every response at db-max-rows (1000 on Supabase). The LIMIT 10000 never survived the wire, so segments silently held 1000 rows, and the truncation could cut inside a run of rows sharing one updated_at (a push chunk shares one now()): the commit's range delete then removed rows that were never archived, surfacing as commit_mismatches during validation. Migration 021 makes the pair loss-proof under any proxy truncation: stat_archive_rows trims the trailing millisecond unless the page provably holds every row of it (whole-millisecond extension only for the single-millisecond page), so every result ends at a complete millisecond; and stat_archive_commit refuses with P0001, rolling back the manifest insert and the delete, when the range's delete count differs from the declared segment row count. The compact route now assembles each segment from sub-pages of at most 1000 rows, advancing p_from per sub-page until STATS_COMPACT_SEGMENT_ROWS or a drained user (only an empty page means drained; a short page can just mean the trailing millisecond was trimmed), writing one object and one commit per assembled segment, and counting a refused commit as a mismatch plus an error. The verification script applies 021 and asserts the trim, the equal-timestamp run, the covered-millisecond keep, the single-millisecond extension and the refusal rollback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(stats): keyset-paginate archive rows so no proxy row cap can wedge or lose data Review found the remaining hole in the trim design: a millisecond holding more rows than db-max-rows made the single-millisecond fallback return more than p_limit, PostgREST truncated it to the same first 1000 rows every time, the cursor stopped advancing and the sub-page loop repeated the identical page forever (or, cut differently, produced a refused commit). A restore can create such a millisecond: it re-inserts 500-row chunks, each stamping one now(). stat_archive_rows is now a plain keyset pager over (updated_at, book_hash, page, start_time) with three tie-cursor parameters (the 020 signature is dropped). Keyset pages are truncation-proof by construction: any cap only shortens a page, the cursor comes from rows actually received, and the tie columns paginate inside a millisecond of any size. The compaction route owns the boundary policy: assemble pages until the segment target plus a complete millisecond to cut at (or a drained user), trim the trailing millisecond unless it is provably closed (drained and ended at least 60 s before the window cutoff), defer a user whose only eligible rows sit in a still-fresh millisecond, and hard-stop a pathological millisecond beyond 50k rows. Regression tests: 1001 equal-timestamp rows in one millisecond become one segment with no repeated page and no refused commit; a mid-millisecond target cut trims and the next segment refetches the remainder; a still-fresh millisecond defers the user. The SQL script asserts keyset tiling, the tie-cursor resume inside an equal-timestamp run, and the refusal rollback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
9b33b52a40
|
feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window (#5835)
* feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window
stat_pages is an append-only per-user log of page events merged by longest
duration; the server never reads history for analytics and devices union-merge
everything locally, so keeping the whole history in Postgres is the most
expensive way to store it.
Migration 020 adds a second tier. Postgres keeps a hot window (updated_at
younger than 7 days by default); a cron job (POST /api/stats/compact, driven
by a scheduled() handler in a custom OpenNext worker entry) compacts older
rows per user into immutable JSON segments in R2, listed in the stat_archives
manifest. The commit RPC inserts the manifest row and deletes exactly the
archived (from, to] range in one transaction, compare-and-set on the user's
archived_to under a per-user advisory lock; segments never split a
millisecond, and objects are never deleted by the compaction path.
The stats pull composes pages server-side: hot rows are read before the
manifest (a concurrent commit can only duplicate, never lose), then the first
segment that still has rows past the cursor is served (paged, trailing
millisecond completed) or the hot rows; unpaginated pulls get every segment
then hot rows. The sync API, the app and the koplugin are unchanged.
Also: POST /api/stats/restore (rollback, re-inserts a user's segments through
upsert_stat_pages_as and drops the manifest rows; refuses while compaction is
enabled), account deletion removes the user's archive objects before the auth
user, a local PostgreSQL 15 verification script for the migration, and
docs/stats-archive.md. Ships disabled (STATS_COMPACT_ENABLED = "false").
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(stats): record one Analytics Engine point per archive-backed stats pull
Hot-only pulls write nothing; a pull that reads R2 segments writes one point
(indexes ['pull'], blobs ['paged'|'full'], doubles [segments_read, rows,
limit]) to STATS_COMPACT_AE. The share of pulls that reach the archive is the
number that should drive STATS_COMPACT_WINDOW_DAYS; we ship with 7 days.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(stats): targeted compaction run for one user, plus the deployment runbook
POST /api/stats/compact with a JSON body {"user_id"} compacts that user only:
no claiming, the enabled flag is ignored (operator action, usable while the
cron is off) and the batching thresholds are ignored (everything older than
the window is archived). Still token-guarded; malformed ids answer 400. This
is what lets the rollout validate on a known account in production before the
cron is enabled, and drain one heavy user by hand.
docs/stats-archive.md gains the step-by-step deployment guide: migration
check queries, bucket and secret creation, disabled deploy and its checks,
validation on one account (targeted run, manifest/object checks, fresh pull
on a device or through the API, optional restore), enabling the cron, the
Analytics Engine and Postgres checks to watch, the post-drain REINDEX, and
the window revisit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(stats): address review on the archive tier
- Account deletion: delete the identity first, then queue the user id in a
new service-role-only stat_archive_orphans table and delete the R2 prefix
best-effort; batch compaction runs sweep the queue (kill switch on or off)
until each prefix lists empty. Deleting objects before a failed deleteUser
would have left an active account with its history gone.
- stat_archive_state and stat_archive_orphans: RLS enabled and privileges
revoked from PUBLIC/anon/authenticated so PostgREST does not expose them;
the verify script asserts relrowsecurity on all three tables and that
anon/authenticated cannot read the service-role-only ones.
- Compact route: only an empty body is the cron's batch request; every other
body must be a valid {user_id} targeted request or it is a 400, so a typo
never starts a batch run. Guard: 503 (no token/bucket), 401, then the
kill switch, applied by the route after the orphan sweep.
- Paged stats pull fills a page across tiers: segments are read lazily until
they fill the page, short archive pages are topped up with hot rows and
the page is cut at limit with the trailing millisecond kept, so a client
that stops on a short page (the koplugin) never stalls on a tier boundary.
- Restore reads the manifest page by page (PostgREST caps responses at 1000
rows) until it is empty.
- Config knobs reject digit strings beyond the safe integer range.
- worker.ts logs a rejected cron fetch; the [limits] cpu_ms block is dropped
(the job is I/O-bound and the ceiling would apply to every request).
- Tests: PostgREST mocks now apply eq/gt filters and honor range/delete so
the query contract is exercised; rpcMock is cleared between tests.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(stats): refresh the compact route header comment for the reworked guard order
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(stats): address review round 2 on the archive tier
- The stats pull reads the stat_archives manifest in range pages (PostgREST
caps a response at 1000 rows) and appends hot rows only once a short final
page proves no archived rows remain past the cursor; a paged pull stops
fetching manifest pages as soon as its response page is full. A truncated
manifest list could otherwise let a client cursor skip segments. Regression
test with 1001 single-row segments, unpaginated and paged.
- Account deletion writes the stat_archive_orphans tombstone BEFORE anything
destructive and stops with 500 (retryable) if even that fails; a failed
deleteUser compensates the tombstone; the orphan sweep additionally skips,
keeping the row, any queued user that still exists, so a stale tombstone can
never wipe a living account.
- The compaction loop asserts each segment boundary advances past the previous
millisecond before writing the object. stat_archive_rows extends every
segment to the end of its last millisecond, so consecutive segments cannot
share an ms-keyed object name; the assertion turns a future SQL regression
into a loud per-user error instead of a silent object overwrite.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|