Skip to content

feat(analytics): rank nodes by neighbour count (#2100) - #2457

Merged
efiten merged 4 commits into
Kpa-clawbot:masterfrom
zfouts:feat/neighbor-rank-2100
Nov 28, 2026
Merged

efiten merged 4 commits into
Kpa-clawbot:masterfrom
zfouts:feat/neighbor-rank-2100

Conversation

@zfouts

@zfouts zfouts commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Answers #2100: "My node is Rank #X on its Reach page — who is #1?"

A new Neighbor Rank tab on the Analytics page lists every ranked node by all-time neighbour count. Each row shows the node's placement, name, role and neighbour count, with a link to its Reach page. The tab has search, a role filter, paging and deep links. The Reach page's Rank card now links to it and opens the list at the node's own row.

Inspired by dborup's Reach leaderboard in their fork (dborup#69). This is a fresh implementation on current master.

What changed

  • API: GET /api/nodes/neighbor-rank?q=&role=&offset=&limit=&focus= returns a typed NeighborRankResponse: entries, total, offset, ranked, snapshot_at. focus=<pubkey> returns the page that contains that node, so a link to a node deep inside a large tie group still lands on its row.
  • One rank, two views: the endpoint and the Reach card's Rank use the same cached rank view, so they always agree.
    • Ties share a placement (1, 1, 3).
    • A search or role filter narrows the list but never renumbers it.
    • Only valid 64-hex pubkeys that have a nodes row are ranked.
    • Only edges whose two ends are both valid pubkeys count toward a degree. The e2e fixture has 55 edges with an empty node_a, which used to show up as a nameless Feed panel overflow:hidden silently clips items instead of scrolling #1.
  • Visibility: the ranked population follows the /api/nodes rule (blacklist, hidden name prefixes, geo_filter), so hidden nodes are never listed. The view is rebuilt when the degree snapshot, the visibility rules or the node cache change. The reach cache key now includes the visibility generation.
  • Reach card: shows "Not ranked" instead of #0 / N, plus a View leaderboard link.
  • Frontend: a self-contained public/neighbor-rank.js with pure helpers, unit-tested via vm. Search is debounced, only the tbody is replaced, and stale responses are dropped. A debounced search or a response that arrives after the user leaves the tab does nothing (it checks the tab's own rows, not the shared #analyticsContent). The tab has loading, empty, no-match and error-with-Retry states. All colours are CSS variables (--link-color, --accent-strong). It fits a 360 px phone without sideways scrolling.

Performance

Operation, 10,000 ranked nodes Time
Build the rank view (once per 60 s snapshot, or on a visibility or node-cache change) 5.6 ms
Serve a cached page with q and role filters 0.15 ms

TestNeighborRankCachedPageUnder5msFor10kNodes asserts the serve time.

Tests

  • Go: the 64-character q limit counts characters, not bytes (multi-byte cases at 64 and 65), ties, degree-0 nodes, hidden and blacklisted nodes excluded from both the list and the card, card == list, filters don't renumber, paging, every bad parameter returns 400, 503 without a snapshot, invalid and empty pubkeys, a node without a row excluded, a rename into a hidden prefix, a stale-view race, and focus across a 130-node tie group.
  • Frontend unit: tests/unit/test-neighbor-rank.js (21 tests), including the client's 64-character cap on accented text and emoji, in the URL state and in the search box (code points, not UTF-16 units).
  • E2E: tests/e2e/test-neighbor-rank-e2e.js, added to deploy.yml (shard 1). Step 7 leaves the tab during the debounce and with a held request; it fails on the code before 5e372f47. Step 4b pastes 62 letters, 📡 and Z (64 code points) and checks the box keeps all of them and cuts a 65th. The tab is added to the axe suite (108 cells, 0 violations).

Local runs:

  • full cmd/server suite, plus -race on the new tests
  • test-all.sh
  • all 138 browser suites on the e2e fixture. Failures matched master or were setup-only: user-management, the split frontend, and the known flaky test-issue-1147.
  • screenshots at 1440×900, 390×844 and 360×740, light and dark

Notes for reviewers

  • Review fixes are in 5e372f47; see the reply comment.

  • The Reach card's rank and total change slightly on instances that hide nodes, because hidden nodes are no longer counted. This is intentional, so the card and the list agree.

  • The Reach response is cached for 5 minutes, so the number on the card can trail the list by up to that long. The leaderboard link still lands on the right row, because the server resolves it with focus.

  • Paging and filters update the URL with replaceState, like the other Analytics tabs. Back does not step through pages.

  • If feat(db): PostgreSQL as an alternative database backend #2396 (Postgres) merges first, its parity test pg_store_queries_test.go must stop reading degreeSnapshot.total/sortedDesc, which this PR removed as dead. That's a one-line change, already done on our integration branch.

  • Merging with the other overnight PR: whichever lands second needs a one-line rebase in .github/workflows/deploy.yml (both add a suite line next to test-node-reach-e2e.js).

🤖 Generated with Claude Code

@zfouts
zfouts force-pushed the feat/neighbor-rank-2100 branch from 868f9e5 to 85b4b58 Compare November 23, 2026 15:27
"My node is Rank #X on its Reach page — who is #1?" New Analytics tab
`neighbor-rank` lists every ranked node with its placement, name, role and
all-time neighbour count, with search, role filter, paging and deep links
(#/analytics?tab=neighbor-rank&q=&role=&page=&focus=).

- GET /api/nodes/neighbor-rank?q=&role=&offset=&limit=&focus= (typed
  NeighborRankResponse). focus=<pubkey> returns the page that holds that
  node, so links work inside wide tie groups.
- One rank view shared by the endpoint and the Reach page's Rank card, so the
  two always agree: ties share a placement (1, 1, 3), filters never renumber,
  only valid 64-hex pubkeys with a nodes row are ranked, and only edges whose
  both ends are valid pubkeys count. The population follows the /api/nodes
  visibility rule (blacklist, hidden name prefixes, geo_filter), so hidden
  nodes are never listed. The view is rebuilt when the degree snapshot, the
  visibility rules or the node cache change; the reach cache key now includes
  the visibility generation.
- Reach card: "Not ranked" instead of "#0 / N", and a "View leaderboard" link
  that opens the list at the node's row.

Perf: building the view for 10,000 ranked nodes 5.6 ms (once per 60 s
snapshot); serving a cached page with q and role filters 0.15 ms.

Inspired by dborup's Reach leaderboard (dborup#69).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zfouts
zfouts force-pushed the feat/neighbor-rank-2100 branch from 85b4b58 to 1adb680 Compare November 23, 2026 15:46
@zfouts
zfouts marked this pull request as ready for review November 23, 2026 19:55
@n30nex

n30nex commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

I verified two cases on 1adb680bb. All 15 neighbor-rank API tests passed locally.

  1. Typing Waterloo and immediately opening Observers changed #/observers to #/observers?q=Waterloo and sent a ranking request after leaving the tab. Could the delayed search verify its original input is still mounted before updating the URL and fetching?
  2. The search box accepts 64 characters. A 59-character French query occupied 68 UTF-8 bytes and returned HTTP 400. Counting characters consistently in the API and UI would keep accented names searchable up to the advertised limit.

@efiten

efiten commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Review of 1adb680b. Both points from the comment above reproduce, and the first one has a second path:

  1. The search debounce outlives the tab (public/neighbor-rank.js:208-212, change() at :203-207). The 250 ms timer is never cleared and change() does not check that the tab is still mounted. Typing Waterloo and switching to another Analytics tab gives #/analytics?tab=rf-health&q=Waterloo and sends the request. There el is the shared #analyticsContent (analytics.js:392), so the el.isConnected guards at :158 and :195 stay true. The late response then reaches $('nrPagerText') at :186, throws, and showError throws again at :145, leaving an unhandled rejection. A request already in flight when the user switches tabs takes the same path without any typing. Checking rows.isConnected in change() and at the top of .then/.catch, and clearing the timer, covers both.

  2. The 64-character limit counts bytes (cmd/server/neighbor_rank.go:130). len(q) is bytes, while the error text, openapi.go, docs/api-spec.md and the input's maxlength="64" all say characters. A query of 33 x é (66 bytes) returns 400, 32 x é returns 200. utf8.RuneCountInString(q) plus a multi-byte case at 64 characters would fix it.

Neither has a regression test yet; an E2E step for leaving the tab during the debounce and a Go case for the multi-byte query would pin both.

The rest checks out. The ranking does no DB work per cached request: on 10k nodes a rebuild takes 11 ms and a cached filtered page 0.164 ms. The response types are named structs. The cmd/server suite and tests/unit/test-neighbor-rank.js pass locally.

Smaller notes, none blocking:

  • neighbor_rank_bench_test.go:60 is a wall-clock 5 ms threshold in the normal run (measured 0.164 ms).
  • neighbor_rank.go:171 allocates matches at len(view.rows) per request (40 KB at 10k nodes).
  • "Empty when the node has no nodes row" in neighbor_rank_types.go:24-25 and openapi.go cannot occur.
  • The Reach card's nodes_with_edges now means the ranked population; worth a line in the release notes.

Not checked: the E2E and axe suites, and a browser run.

…eans characters

Review feedback on Kpa-clawbot#2457:

- The 250 ms search debounce and a request in flight both outlived the
  tab. The guards checked el.isConnected, but el is the shared
  #analyticsContent, connected on every other tab, so a late search
  rewrote the other tab's URL and fetched, and a late answer threw in
  showError. Guard on this render's own #nrRows instead, in change() and
  in both promise handlers.
- The server's 64-character cap counted UTF-8 bytes; it now counts
  characters (utf8.RuneCountInString), as the docs, the error text and
  the input say. The client cap counts code points too, so it no longer
  cuts an emoji in two (which made buildQuery throw URIError).

Tests: a Go case at 64/65 multi-byte characters; unit cases for the
client cap; E2E step 7 leaves the tab during the debounce and with a
held request, and fails on the old code on each path. Steps 3 and 7 now
wait for the startup theme-refresh re-render before typing: step 3 only
passed before because the replaced render's handler still ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (commit 5e372f47). Thanks to both of you; each point reproduced as described.

  1. The search outlives the tab. live() (public/neighbor-rank.js:132) checks that this render's own #nrRows is still in the document. change() (public/neighbor-rank.js:206) and both promise handlers (public/neighbor-rank.js:164, public/neighbor-rank.js:198) now use it instead of el.isConnected. A debounced search that fires after the user leaves changes neither the URL nor the network, and a late answer, or a late failure, draws nothing. I did not clear the timer in change(): that would drop a pending search edit when a role chip is clicked within 250 ms (clear the box, click a chip), and the existing paging step caught it.
  2. 64 means characters. handleNeighborRank counts runes (cmd/server/neighbor_rank.go:128). The client cap in normState (public/neighbor-rank.js:23) now counts code points too. Before, a deep link with an emoji at the 64-unit boundary left a lone surrogate, and buildQuery threw URIError.

Tests, each failing on 1adb680b:

  • Go TestNeighborRankQueryLimitCountsCharacters: 64 é (128 bytes) and 64 CJK characters (192 bytes) pass, 65 é gets a 400.
  • Unit (tests/unit/test-neighbor-rank.js): 70 é cap at 64, and an emoji run caps at 64 characters without splitting one.
  • E2E step 7 (tests/e2e/test-neighbor-rank-e2e.js), on a fresh page. Path one: type, then switch tabs within the debounce; no q= in the URL and no ranking request after leaving. Path two: hold the ranking response with page.route, switch tabs, then release it; no page error. On the old code the first path fails with #/analytics?q=…, and the second with Cannot set properties of null (setting 'textContent') at showError.

One more thing turned up. On a page load, Analytics renders the tab twice: once from init, then again on the first theme-refresh. Step 3 typed into the first render's input, which the second render replaces. It only passed before because that orphaned handler still rewrote the URL. Steps 3 and 7 now wait for the theme-refresh, as test-health-status-e2e.js does. A user who starts typing in the first ~300 ms after a load can still lose those keystrokes to that re-render. That predates this PR, so I've left it alone here.

Re-tested: the cmd/server suite, test-all.sh, eslint (0 errors), and E2E test-neighbor-rank-e2e.js (3/3 runs) and test-node-reach-e2e.js against a local fixture server.

Not changed (the non-blocking notes): the 5 ms bench threshold, the matches preallocation, the "no nodes row" wording, and the nodes_with_edges release note. Happy to do any of them here if you'd like.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@n30nex

n30nex commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Retested 9c1c3a67. The 59-character French query now returns 200. Typing a search and immediately leaving for Observers kept the destination URL intact and sent zero late ranking requests. All 17 ranking API tests passed locally.

One small mismatch remains in the visible input. Pasting 62 ASCII letters followed by 📡 and Z gives 64 code points. The API and deep link accept all 64, but the text box drops the Z because native maxlength=64 counts UTF-16 units. Could the input use the same code-point limit as the URL and API?

Native maxlength counts UTF-16 units, so after an emoji the box dropped
characters that the API and the deep link accept (62 letters + 📡 + Z is
64 code points, 65 units). The box now has no maxlength; the input
handler cuts anything past 64 code points with clampQuery, the same cut
normState applies, and never leaves half a surrogate pair.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@zfouts

zfouts commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

Review feedback addressed (commit eb401aa7). Thanks, it reproduced as described.

  1. Search box limit. The input no longer has a native maxlength, which counted UTF-16 units. The input handler (public/neighbor-rank.js:220) cuts anything past 64 code points with clampQuery (public/neighbor-rank.js:21), the same cut normState applies to the URL state, so the box, the hash and the API agree. The cut never leaves half a surrogate pair, and the caret goes to the end after a cut.
  2. Tests.
    • tests/unit/test-neighbor-rank.js (21 tests, was 14): clampQuery at 64 and 65 code points, at a surrogate pair on the boundary, null and undefined, no maxlength in the markup, and two through the real input handler.
    • tests/e2e/test-neighbor-rank-e2e.js step 4b: 62 letters + 📡 + Z stay whole in the box and in the hash q, and a typed 65th character is cut. It passed twice locally on the e2e fixture.

@efiten
efiten merged commit 95f13c0 into Kpa-clawbot:master Nov 28, 2026
17 checks passed
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 29, 2026
Brings in Kpa-clawbot#2457, Kpa-clawbot#2490, Kpa-clawbot#2488, Kpa-clawbot#2500 and Kpa-clawbot#2455. Conflicts were two
added lines on each side: the eslint globals (frameHex/frameSize and
NeighborRank) and the deploy.yml E2E suite list (the privacy-on suite
and test-neighbor-rank-e2e.js); both kept. The leak test now requests
Kpa-clawbot#2457's /api/nodes/neighbor-rank, which serves no positions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zfouts added a commit to zfouts/CoreScope that referenced this pull request Nov 29, 2026
… Pushover to Postgres

Brings in 37 master commits, including the push relay (Kpa-clawbot#2447), Pushover
(Kpa-clawbot#2455), plain SMTP (Kpa-clawbot#2466), neighbour rank (Kpa-clawbot#2457), the observers rebuild
fix (Kpa-clawbot#2445) and Kpa-clawbot#2486.

Conflicts: config.example.json, docs/api-spec.md and auth_service.go keep
both sides (as n30nex's merge notes say); dbschema's observers check keeps
the Postgres branch in front of Kpa-clawbot#2445's rowid-alias check; the
release-routing test keeps musl-test; CHANGELOG keeps only unreleased
entries; notify_service.go keeps master's destinations plus the cluster
lock on evaluation, and the email claim moves to notifyChanges.claim.

users.db schema: master's v11 (push relay) and v12 (Pushover) come first,
this branch's rate_limits becomes v13, and v14 adds push_relay_state,
push_relay_pending and notification_pushover_subscriptions.

Push relay and Pushover on Postgres with several server replicas:
- Postgres migrations v11-v14 with the five SQLite triggers as plpgsql;
  instr -> strpos, typed VALUES, a qualified ON CONFLICT WHERE, integer
  booleans. The parity test also compares trigger names.
- Relay enrollment, delivery phase and the pending enrollment (with the
  Ed25519 proof seed) move from <users.db>.push-relay*.json and process
  memory into the accounts store. Writes are compare-and-set on a
  revision; replicas reload it per tick, per dispatch pass and per job.
  Old files are imported once, except an enrollment under a manual relay
  or for another public origin, which is left on disk and never prunes.
- Credentials and the seed are sealed with userManagement.encryptionKey
  (CORESCOPE_ACCOUNTS_KEY), required on Postgres; on SQLite without a key
  they are stored as before, inside users.db. Leftover plain values are
  re-sealed at startup once a key is set. users.db is set to 0600, and
  user backups blank the relay secrets.
- Queue rows are claimed with a 5-minute lease (SKIP LOCKED on Postgres);
  each queue drains under a cluster lock; advisory locks use their own
  connection pool, so lock holders cannot starve the accounts store.
  Device links and the Pushover per-user limit lock the user.
- The enrollment proof and the Pushover connect token work on any
  replica; the proof endpoint validates before any database read and is
  limited per IP; device link/unlink are limited per user.

Also fixed while integrating:
- node_reach used IS NOT 'tx', which Postgres rejects (from Kpa-clawbot#2486).
- docker/server-exec.sh did not pass five variables the server reads
  (CORESCOPE_ACCOUNTS_KEY, CORESCOPE_PUSHOVER_TOKEN,
  CORESCOPE_PUSH_RELAY_CREDENTIAL, CORESCOPE_SMTP_PASSWORD, CORESCOPE_URL);
  tests/unit/test-server-exec-env.js now checks the list.
- corescope-migrate copy-users/verify-users failed on
  notification_pushover_sent (no key); it gets a rowid on Postgres, like
  mail_events, and verify redacts credential and seed columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants