feat(ranker): rank the accounts that read their feed first

Closes #81 (closed).

Problem

A reader's personalized feed was on average about 11 hours old and up to about 22. The ranker gave every account in the rotation the same priority (44,858 accounts, 200 per cycle, stalest first), while a few hundred accounts ever open a feed. Reading the feed did not reach the ranker at all. Measurements are in #81 (closed).

What changes

  1. A feed read tells the ranker. get_personalized_feed calls pg_notify('haf_fyp_feed_read', username) on a page-1 read, inside the branch that already established the account has a cached feed. PostgREST runs a GET in a read-only transaction, which cannot change a table but can notify.
  2. The ranker listens on the session it already holds. No second connection and no thread: LISTEN is issued in _connect (so every reconnect repeats it) and the main loop drains the notifications on each pass.
  3. A read is stamped. New column active_users.last_read_at. Only accounts that already have a rotation row are stamped; reading never enrols anyone.
  4. A stale feed is re-ranked, through the existing _run_targeted_refresh, if it is older than READ_REFRESH_MIN_AGE_SECONDS and the cycle's budget is not spent.
  5. Recent readers go first in every scheduled cycle. _fetch_personalised_users takes accounts that read within READER_WINDOW_SECONDS and whose feed is older than READ_REFRESH_MIN_AGE_SECONDS, stalest first, then fills the rest of the cycle from everyone else in the order it used before.

Limits

The feed endpoint is public and takes any username, so a read is not evidence of a person. Each step has a ceiling:

Setting Default Bounds
READER_CYCLE_SHARE 0.5 (capped at 0.9) Share of MAX_USERS_PER_CYCLE readers may take. The rest always goes to the stalest of everyone else. 0 turns the reader lane off.
READER_WINDOW_SECONDS 1 day How long one read keeps an account eligible for the reader lane.
READ_REFRESH_MIN_AGE_SECONDS 600 A feed younger than this is not re-ranked on read and does not take a lane slot.
READ_REFRESH_MAX_PER_CYCLE cycle size x share, at most 300 (100 at the defaults) Immediate re-ranks per cycle period. Readers past it are stamped and left to the reader lane. 0 turns them off.
READ_REFRESH_BATCH_SECONDS 30 After one read-triggered re-rank, the next waits this long and takes everyone who became due meanwhile. One targeted refresh costs about 8 s before it ranks anyone (measured, below). The first read after a quiet spell is not held back.

In the function itself, a notification is sent only for page 1, never on a standby, not when haf_fyp.feed_read_notify is off for the role (off, false, no or 0, in any case), and at most once per account per ten minutes once the ranker has recorded the read (it reads last_read_at, which only the ranker writes). The connection holds at most 20,000 undrained notifications.

What this costs, and what it does not fix

  • Everyone who is not in the lane rotates more slowly while it is in use, by up to 1 / (1 - share): twice as slowly at the default when the lane is full. That includes the first load of someone who has not read for longer than the window. On the node measured, 79 distinct accounts requested a feed in the two weeks to 2026-09-22 (314 since June). Even if all 79 read on the same day they would not fill the 100 lane slots a cycle has at the defaults, so at today's usage the lane is not full; the cycle checked on the node took 6 of 1500.
  • One caller can cancel the benefit, or slow everyone else. Requesting every account's first page (about 75 minutes at ten requests a second, which is the gateway's default limit for one client address in haf_api_node; this app puts no limit of its own on the feed GET) puts the whole rotation in the lane, and real readers are back to the old round-robin. The cheaper way to hurt is smaller: keeping about twice the lane's slots in the window (200 accounts at the defaults: an account ranked in one cycle is under the minimum age for the next) holds everyone else at 1 - share of the old rotation speed, half at the default, for as long as it is kept up. That is the worst this can do. The signal can also be sent by any database role directly; the ranker's ceilings are the same either way. Telling a reader from a crawler needs an authenticated read, which this app does not have; db/active_users_maintenance.sql already says so. The ranker's line after each cycle reports reads heard and lane occupancy, which is where either shows.
  • A notifying commit is not free. It takes a transaction id and a brief cluster-wide lock (PreCommit_Notify). While the ranker is running, the ration bounds that to about one per account per ten minutes. The ranker records reads between passes, so during a scheduled cycle, and for as long as the ranker is stopped or older than this change, every first-page request notifies. The README says to switch the signal off if the ranker will be down for long.
  • Latency. With the ranker between cycles, the refresh takes about 8 s once the ranker looks, which is up to 5 s after the read (one measurement, below: 9 s end to end), or up to READ_REFRESH_BATCH_SECONDS later if another reader was served just before. A read that arrives during a scheduled cycle is handled when that ends. A reader still waiting for its group when a scheduled cycle comes due leaves the queue only if that cycle ranked it. At 200 per cycle a cycle works for about 43 seconds (from #81 (closed)); on a node that ranks thousands per cycle it is several minutes.
  • Paging. A feed rewritten while someone is scrolling can repeat or skip a post between page 1 and page 2. That was already true for whichever accounts a cycle reached; it is now more frequent for readers.

Things worth a reviewer's attention

  • Lock order. The stamp is a second multi-row writer on active_users, next to the block processor's upsert. It locks its rows FOR UPDATE SKIP LOCKED and then updates only those, so it never waits for a row while holding another; a locked row misses one stamp. It touches only active_users, so the active_users before feed_cache rule is not involved.
  • A ranker newer than the installed SQL. An install run while the ranker is up installs nothing on a HAF with application locks (the ranker holds the lock the install waits for), and the two images are versioned separately. The ranker checks for the column on each connection, and after each cycle for as long as it is missing; without it, it ranks without the reader lane and says so in a warning repeated hourly, where the first version of this MR would have failed every scheduled cycle. On a HAF with locks that state lasts until an operator stops the processor and the ranker and runs the install.
  • A session inside a transaction hears nothing. Two existing paths end a pass with a SELECT's transaction open. The drain rolls back first. Every writer in the loop commits before it returns, and HAF's application lock is a session-level advisory lock, so nothing is lost by it.
  • A closed connection is now replaced. main() reconnected only on OperationalError; a connection that is already closed raises InterfaceError. That state could arise before this MR (one failed cycle every five minutes until restart). The loop now checks conn.closed, and every block reconnects on either error.
  • The budget is per cycle period, not per successful cycle, so a standing cycle failure does not leave immediate re-ranks switched off.
  • The function stays STABLE although it now has a side effect, because PostgREST keeps a STABLE function read-only on POST too. A comment says so.
  • Logging. A targeted refresh of more than 20 accounts logs a count instead of one line per account; smaller ones (Redis opt-ins, ordinary reads) log exactly as before.
  • Eviction is unchanged. A recent read does not protect an account from evict_unproductive_users: a read can be forged.
  • haf_api_node: PostgREST reaches the database through PgBouncer there. NOTIFY is an ordinary statement and passes through transaction pooling; the ranker, which is the side that needs a session, connects directly in that module's compose file.

Considered and left out: recording reads during a scheduled cycle (it would close the gap in the ration on nodes with long cycles, at the cost of running the stamp inside the ranking loop), and an EXCEPTION block around the notify (a subtransaction per read).

On a node

Deployed on 2026-10-07 to a full node (PostgreSQL 17.9, PostgREST 12.2.3 connected directly, 44,863 accounts in the rotation, MAX_USERS_PER_CYCLE=3000, READ_REFRESH_MAX_PER_CYCLE=200), as the first three commits of this MR on top of the version that node was running; the code files they touch were identical to this branch at that point. The later commits were deployed afterwards (below). The install added the column and index in place; three seconds passed between starting it and finding both in the catalog. Only the block processor and the ranker were restarted.

Check Result
First-page read through the gateway, ranker between cycles, feed over two hours old notification; last_read_at set at once; feed rewritten 9 s after the request
Same read again inside ten minutes no notification
Page 2; an account with no feed no notification
Reads during a scheduled cycle each notified (the ration is not armed until the ranker stamps); stamped and re-ranked 24 s after the cycle ended (the hourly maintenance ran first)
Reader lane the cycle that started under ten minutes after the re-ranks took none of them (reader lane 0 of 1500 slot(s)); the next took all six (their last_scored_at is within four seconds of that cycle's start)
Per-cycle line feed reads since the last cycle: 6 account(s) heard, 6 re-ranked at once; reader lane 0 of 1500 slot(s), then ... reader lane 6 of 1500 slot(s) after the next cycle (the wording has since become "queued for an early re-rank")
Off switch, set to 'OFF', applied by ending PostgREST's idle sessions three reads: no notification, no stamp, all 200; after RESET and the same again, the next read notified
pg_notification_queue_usage() 0 throughout

One real reader was heard during the checks and handled the same way.

The fixed cost of a targeted refresh is about 8 s on that node (candidates, vectors, credibility: 8.3 s for one account, 8.0 s to the first of four), against well under half a second per account. That is why read-triggered refreshes are grouped (READ_REFRESH_BATCH_SECONDS), which was added after this first deploy.

The whole branch has since run on that node (ranker redeployed 2026-10-07 20:20 UTC at 1b16af13; the ranker file identical to this branch). Three stale, never-read accounts read 0, 7 and 15 seconds apart: the first was re-ranked at once (fresh 9 s after the read), the other two together in one refresh 34 s after the first began. The line after the next cycle read 3 account(s) heard, 3 queued for an early re-rank; reader lane 7 of 1500 slot(s). The ranker was still running normally fourteen hours later.

Cycle duration varies on that node, with or without this MR. Cycles of 3000 accounts took 7.5 to 9 minutes the day before the deploy, and between 4.4 and 20.5 minutes after it. To separate the two, the pre-MR ranker image and this one were run back to back on the same evening, two cycles each: 21.5 and 4.3 minutes on the old image, 4.3 and 10.3 on this one. The per-account ranking path is not touched by this MR (scoring.py, embeddings.py, credibility.py and _rank_user are unchanged). What makes a cycle slow on that node was not identified.

Tested

  • tests/unit/test_reader_first.py (95 tests) and tests/unit/test_reader_first_loop.py (23): the block in main() driven through the real loop with a clock, including every block's handling of a lost connection and of a failed pass; the settings read in a fresh interpreter; the SQL guard checked with comments stripped; what run_cycle reports back.
  • tests/integration/test_reader_first_db.py: 41 tests against a real server. They cover who is stamped and who is re-ranked, a row locked by another session being skipped, the cycle order and the lane's minimum age, a server that is not on UTC, a session left inside a transaction, the bounded backlog, a schema without the column, the in-place upgrade DDL, and the shipped get_personalized_feed (its text re-homed into a throwaway schema and called in a read-only transaction): page 1 notifies, page 2 and an account without a feed do not, the ten-minute ration, and the off switch in each spelling.
  • tests/integration/ passes in full (154) on PostgreSQL 14 and 17. CI runs it on postgres:14-alpine; the PostgreSQL 17 run was mine, in a throwaway server, because the first node this goes to runs 17.
  • Mutations of the new code, SQL and schema, each of which fails one of the two files: 47 after the first review round, 29 after the second, 10 for the grouping and 11 for the last commit, with an identity mutation passing both. Reviewers ran their own (53, 87 and 44); the tests they showed were missing are in.

Not tested

  • The path through PgBouncer, including applying the off switch there.
  • The standby guard.
  • On a node: readers kept waiting past a cycle that did not rank them (it needs a failed cycle or a full lane; unit tests only).
  • The off switch applied by restarting PostgREST (on the node it was applied by ending PostgREST's idle sessions).
  • A flood: many accounts read at once on a node.
Edited by mcfarhat

Merge request reports

Loading
Loading