diff --git a/.changeset/wot-bound-graph-rebuilds.md b/.changeset/wot-bound-graph-rebuilds.md new file mode 100644 index 000000000..f1498081c --- /dev/null +++ b/.changeset/wot-bound-graph-rebuilds.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(wot): bound a trust graph rebuild and space out the rebuilds contact lists trigger + +A Web of Trust rebuild read follow lists one at a time with no limit on accounts, lists or follows, and every contact list (kind 3) from an account in the graph started or queued another full rebuild. A rebuild now stops at `wot.maxPubkeys`, `wot.maxFollowListReads` or `wot.maxEdges` (defaults 500000, 10000 and 2000000), logs which limit it hit, and keeps the graph built so far, which can only trust fewer accounts, never more. Follow lists are read 100 at a time, and a `p` value that is not a 64-character hex key is no longer looked up as an author prefix. Rebuilds triggered by contact lists wait `wot.minRebuildIntervalSeconds` (default 60) after the previous one ended. A deliberate limit: a follow-list change can take up to that interval longer to reach the graph. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index c7966d2a5..39800a8dc 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -311,8 +311,12 @@ The settings below are listed in alphabetical order by name. Please keep this ta | workers.count | Number of workers to spin up to handle incoming connections. Spin workers as many CPUs are available when set to zero. Defaults to zero. | | wot.enabled | Enables the Web of Trust graph, rooted at `wot.seedPubkey`, built from NIP-02 contact lists. Defaults to false. | | wot.maxDepth | How many hops out from `wot.seedPubkey` the trust graph extends. Direct follows are distance 1. Defaults to 2. | +| wot.maxEdges | Most follows one graph rebuild counts, each account a contact list names counted once per list. Defaults to 2000000. A rebuild that reaches this, `wot.maxFollowListReads` or `wot.maxPubkeys` stops, logs a warning naming the limit, and keeps the graph built up to that point: every account in it has its full-graph distance, and some accounts the full graph would trust are left out, so they get no proof-of-work discount (`limits.event.pow.wotThresholds`) and their NIP-56 reports no WoT weight until a rebuild with higher limits. Each worker builds its own graph. | +| wot.maxFollowListReads | Most follow lists one graph rebuild reads (one for the seed, one for each trusted account it expands). Defaults to 10000. Reaching it stops the rebuild as described for `wot.maxEdges`. | +| wot.maxPubkeys | Most distinct pubkeys one graph rebuild counts followers for, which bounds the memory it uses. Defaults to 500000. Reaching it stops the rebuild as described for `wot.maxEdges`. | | wot.minimumFollowers | Minimum number of already-trusted accounts that must follow a pubkey before it enters the graph at 2+ hops. Direct follows are always trusted. Defaults to 1. | -| wot.refreshIntervalHours | Reserved for a future periodic full rebuild; not yet read by any code (real-time kind-3 ingestion already keeps the graph current). Defaults to 24. | +| wot.minRebuildIntervalSeconds | Seconds a graph rebuild triggered by a contact list (kind 3) from an account in the graph waits after the previous rebuild ended; every contact list that arrives meanwhile is applied by that one rebuild, so a follow-list change can reach the graph up to this many seconds later than with `0`, which rebuilds at once. The first build, and the rebuild after a change to `wot.enabled`, `wot.seedPubkey`, `wot.maxDepth`, `wot.minimumFollowers`, `wot.maxPubkeys`, `wot.maxFollowListReads` or `wot.maxEdges`, do not wait. Defaults to 60. | +| wot.refreshIntervalHours | Reserved for a future periodic full rebuild; not yet read by any code (kind-3 ingestion already triggers rebuilds, see `wot.minRebuildIntervalSeconds`). Defaults to 24. | | wot.seedPubkey | The relay owner's pubkey in hex. Root of the trust graph. Required when `wot.enabled` is true. | ## Peering advertisement (NIP-11) diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 5eb07fa15..fad4a2223 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -140,8 +140,8 @@ nip66: historyRetentionHours: 0 wot: # Web of Trust graph. When enabled, the relay builds a trust graph rooted - # at seedPubkey from NIP-02 contact lists, updated in real time as kind-3 - # events arrive. + # at seedPubkey from NIP-02 contact lists, and rebuilds it as kind-3 + # events from accounts in the graph arrive. enabled: false # The relay owner's pubkey in hex. This is the root of the trust graph. # Required when enabled is true. @@ -151,6 +151,17 @@ wot: minimumFollowers: 1 # How many hops out from seedPubkey the trust graph extends. maxDepth: 2 + # Limits on one rebuild. A rebuild that reaches one stops, logs which one, + # and keeps the graph built so far, so it can only trust fewer accounts. + # Most distinct pubkeys a rebuild counts followers for. + maxPubkeys: 500000 + # Most follow lists a rebuild reads. + maxFollowListReads: 10000 + # Most follows a rebuild counts (each account a list names, once). + maxEdges: 2000000 + # Seconds a rebuild triggered by a contact list waits after the previous + # rebuild ended. Updates in the meantime share one rebuild. 0 rebuilds at once. + minRebuildIntervalSeconds: 60 # Reserved for a future periodic rebuild; not yet read by any code. refreshIntervalHours: 24 nip56: diff --git a/src/@types/services.ts b/src/@types/services.ts index 734701268..07aa7f2dd 100644 --- a/src/@types/services.ts +++ b/src/@types/services.ts @@ -19,7 +19,11 @@ export interface IWotGraphService { */ getDistance(pubkey: Pubkey): Promise isTrusted(pubkey: Pubkey): Promise - /** Applies a pubkey's current NIP-02 follow list to the graph. */ + /** + * Stores a pubkey's current NIP-02 follow list. When it can change the + * graph, a rebuild follows, at least `wot.minRebuildIntervalSeconds` after + * the previous one ended. + */ updateFollowList(pubkey: Pubkey, follows: Pubkey[]): Promise /** * Fire-and-forget: kicks off the initial graph build without waiting on it, diff --git a/src/@types/settings.ts b/src/@types/settings.ts index 54b770b6d..5f8cc0cf1 100644 --- a/src/@types/settings.ts +++ b/src/@types/settings.ts @@ -476,9 +476,24 @@ export interface WoTSettings { * Defaults to 2. */ maxDepth: number + /** + * Most distinct pubkeys one rebuild counts followers for. A rebuild that + * reaches a limit stops, logs which one, and keeps the graph built so far. + * Defaults to 500000. + */ + maxPubkeys: number + /** Most follow lists one rebuild reads. Defaults to 10000. */ + maxFollowListReads: number + /** Most follows one rebuild counts, each listed account once per list. Defaults to 2000000. */ + maxEdges: number + /** + * Seconds a rebuild asked for by a contact-list update waits after the + * previous rebuild ended. 0 rebuilds at once. Defaults to 60. + */ + minRebuildIntervalSeconds: number /** * Reserved for a future periodic full consistency rebuild, on top of the - * real-time updates already applied as kind-3 events are ingested. Not + * rebuilds already triggered as kind-3 events are ingested. Not * yet consumed by any code — no background worker reads this field. * Defaults to 24. */ diff --git a/src/services/wot-graph-service.ts b/src/services/wot-graph-service.ts index 40675f127..1aed4a40d 100644 --- a/src/services/wot-graph-service.ts +++ b/src/services/wot-graph-service.ts @@ -9,17 +9,52 @@ import { toNostrEvent } from '../utils/event' const logger = createLogger('wot-graph-service') -const SEED_PUBKEY_PATTERN = /^[0-9a-f]{64}$/i +const HEX_PUBKEY_PATTERN = /^[0-9a-f]{64}$/i + +export const DEFAULT_WOT_MAX_PUBKEYS = 500_000 +export const DEFAULT_WOT_MAX_FOLLOW_LIST_READS = 10_000 +export const DEFAULT_WOT_MAX_EDGES = 2_000_000 +export const DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS = 60 +export const WOT_FOLLOW_LIST_BATCH_SIZE = 100 + +// The longest delay a Node.js timer accepts; a longer wait is re-armed. +const MAX_TIMER_DELAY_MS = 2 ** 31 - 1 const followSetKey = (pubkey: Pubkey): string => `wot:follows:${pubkey}` -// The settings a built graph depends on. A graph built for one key must not -// answer for another: a hot-reloaded seed, depth or follower threshold would -// otherwise keep granting distances computed under the old values. type WotSettings = NonNullable -const graphKey = (wot: WotSettings | undefined): string => - JSON.stringify([Boolean(wot?.enabled), wot?.seedPubkey ?? null, wot?.maxDepth ?? 2, wot?.minimumFollowers ?? 1]) +const positiveIntegerOr = (value: unknown, fallback: number): number => + typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : fallback + +const rebuildLimits = (wot: WotSettings | undefined) => ({ + maxPubkeys: positiveIntegerOr(wot?.maxPubkeys, DEFAULT_WOT_MAX_PUBKEYS), + maxFollowListReads: positiveIntegerOr(wot?.maxFollowListReads, DEFAULT_WOT_MAX_FOLLOW_LIST_READS), + maxEdges: positiveIntegerOr(wot?.maxEdges, DEFAULT_WOT_MAX_EDGES), +}) + +const minRebuildIntervalMs = (wot: WotSettings | undefined): number => { + const seconds = wot?.minRebuildIntervalSeconds + const valid = typeof seconds === 'number' && Number.isSafeInteger(seconds) && seconds >= 0 + return (valid ? seconds : DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS) * 1000 +} + +// The settings a built graph depends on. A graph built for one key must not +// answer for another: a hot-reloaded seed, depth or follower threshold would +// otherwise keep granting distances computed under the old values, and a +// changed rebuild limit applies at once. +const graphKey = (wot: WotSettings | undefined): string => { + const { maxPubkeys, maxFollowListReads, maxEdges } = rebuildLimits(wot) + return JSON.stringify([ + Boolean(wot?.enabled), + wot?.seedPubkey ?? null, + wot?.maxDepth ?? 2, + wot?.minimumFollowers ?? 1, + maxPubkeys, + maxFollowListReads, + maxEdges, + ]) +} const extractFollowedPubkeys = (tags: Tag[]): Pubkey[] => tags @@ -37,6 +72,12 @@ export class WotGraphService implements IWotGraphService { private rebuildQueued = false + private rebuildRequested = false + + private rebuildTimer: NodeJS.Timeout | undefined + + private lastRebuildEndedAt: number | undefined + public constructor( private readonly cache: ICacheAdapter, private readonly eventRepository: IEventRepository, @@ -98,11 +139,10 @@ export class WotGraphService implements IWotGraphService { // A pubkey outside the current trust graph publishing a new follow list // can't change anyone's distance from the seed, so only rebuild when the - // change could actually matter. Fire-and-forget: the event path must not - // block on a full graph rebuild, and scheduleRebuild() coalesces any - // other triggers that land while one is already in flight. + // change could actually matter. The event path never waits for the + // rebuild, and requestRebuild() spaces these rebuilds out. if (pubkey === wot.seedPubkey || this.distances.has(pubkey)) { - void this.scheduleRebuild() + this.requestRebuild() } } @@ -122,32 +162,75 @@ export class WotGraphService implements IWotGraphService { // Ensures at most one rebuild runs at a time. A trigger that lands while a // rebuild is already in flight doesn't start a second one -- it just marks - // that another rebuild should run once the current one finishes, so a - // burst of kind-3 events collapses into at most one extra rebuild rather - // than one per event. Failures are caught here (not left to the caller) so - // `this.building` always clears -- otherwise every future call would keep - // awaiting the same rejected promise until a restart. + // that another rebuild should run once the current one finishes. Failures + // are caught here (not left to the caller) so `this.building` always + // clears -- otherwise every future call would keep awaiting the same + // rejected promise until a restart. private scheduleRebuild(): Promise { if (this.building) { this.rebuildQueued = true return this.building } + // A rebuild that starts now reads every follow list stored before it, so + // it answers any request still waiting. + this.rebuildRequested = false + clearTimeout(this.rebuildTimer) + this.rebuildTimer = undefined + this.building = this.rebuild() .catch((error) => { logger.error('wot graph rebuild failed: %o', error) }) .finally(() => { this.building = undefined + this.lastRebuildEndedAt = performance.now() if (this.rebuildQueued) { this.rebuildQueued = false void this.scheduleRebuild() + } else { + this.startRequestedRebuild() } }) return this.building } + // Rebuilds asked for by contact-list updates wait until + // wot.minRebuildIntervalSeconds after the previous rebuild ended, and every + // request made in the meantime is served by that one rebuild. Each request + // re-arms the timer, so a changed interval applies from the next one. + private requestRebuild(): void { + this.rebuildRequested = true + this.startRequestedRebuild() + } + + private startRequestedRebuild(): void { + if (!this.rebuildRequested || this.building) { + return + } + + clearTimeout(this.rebuildTimer) + this.rebuildTimer = undefined + const wait = + this.lastRebuildEndedAt === undefined + ? 0 + : this.lastRebuildEndedAt + minRebuildIntervalMs(this.settings().wot) - performance.now() + if (wait <= 0) { + void this.scheduleRebuild() + return + } + + this.rebuildTimer = setTimeout( + () => { + this.rebuildTimer = undefined + this.startRequestedRebuild() + }, + Math.min(Math.ceil(wait), MAX_TIMER_DELAY_MS), + ) + this.rebuildTimer.unref() + } + private async rebuild(): Promise { const wot = this.settings().wot const key = graphKey(wot) @@ -158,7 +241,7 @@ export class WotGraphService implements IWotGraphService { return } - if (!SEED_PUBKEY_PATTERN.test(wot.seedPubkey)) { + if (!HEX_PUBKEY_PATTERN.test(wot.seedPubkey)) { logger.error('wot.seedPubkey %o is not a 64-character hex pubkey; trust graph will be empty', wot.seedPubkey) this.distances = new Map() this.builtKey = key @@ -168,6 +251,7 @@ export class WotGraphService implements IWotGraphService { const maxDepth = wot.maxDepth ?? 2 const minimumFollowers = wot.minimumFollowers ?? 1 + const limits = rebuildLimits(wot) const distances = new Map() // Persists across depth levels (not reset per level) so a candidate's @@ -176,20 +260,51 @@ export class WotGraphService implements IWotGraphService { // documented meaning at any maxDepth, not only maxDepth=2. const followerCounts = new Map() let frontier = [wot.seedPubkey] - - for (let depth = 1; depth <= maxDepth && frontier.length; depth++) { + let reads = 0 + let edges = 0 + // Set when a limit stops the rebuild. Every layer before the current one + // is complete and the current one only misses votes, so the graph kept is + // part of the full graph, with the same distances. + let stoppedAt: string | undefined + + for (let depth = 1; depth <= maxDepth && frontier.length && !stoppedAt; depth++) { const layerCandidates = new Set() - for (const pubkey of frontier) { - const follows = await this.getFollows(pubkey) - // One account is one vote: a contact list that repeats a `p` tag must - // not count more than once towards minimumFollowers. - for (const followed of new Set(follows)) { - if (followed === wot.seedPubkey || distances.has(followed)) { - continue + let start = 0 + while (start < frontier.length && !stoppedAt) { + if (reads === limits.maxFollowListReads) { + stoppedAt = 'wot.maxFollowListReads' + break + } + const batch = frontier.slice( + start, + start + Math.min(WOT_FOLLOW_LIST_BATCH_SIZE, limits.maxFollowListReads - reads), + ) + start += batch.length + reads += batch.length + + for (const follows of await this.getFollowLists(batch)) { + // One account is one vote: a contact list that repeats a `p` tag must + // not count more than once towards minimumFollowers. + for (const followed of new Set(follows)) { + if (edges === limits.maxEdges) { + stoppedAt = 'wot.maxEdges' + break + } + if (followed !== wot.seedPubkey && !distances.has(followed)) { + const followers = followerCounts.get(followed) + if (followers === undefined && followerCounts.size === limits.maxPubkeys) { + stoppedAt = 'wot.maxPubkeys' + break + } + followerCounts.set(followed, (followers ?? 0) + 1) + layerCandidates.add(followed) + } + edges++ + } + if (stoppedAt) { + break } - followerCounts.set(followed, (followerCounts.get(followed) ?? 0) + 1) - layerCandidates.add(followed) } } @@ -210,32 +325,63 @@ export class WotGraphService implements IWotGraphService { this.distances = distances this.builtKey = key this.ready = true - logger('rebuilt wot graph: %d pubkeys within %d hops of %s', distances.size, maxDepth, wot.seedPubkey) + if (stoppedAt) { + logger.warn( + 'wot graph rebuild stopped at %s after %d follow list reads and %d follows; kept %d pubkeys within %d hops of %s', + stoppedAt, + reads, + edges, + distances.size, + maxDepth, + wot.seedPubkey, + ) + } else { + logger('rebuilt wot graph: %d pubkeys within %d hops of %s', distances.size, maxDepth, wot.seedPubkey) + } } - private async getFollows(pubkey: Pubkey): Promise { - // Redis is the fast path once a pubkey's follow list has gone through - // updateFollowList(); a pubkey that genuinely follows no one is - // indistinguishable from an uncached one here and falls back to the DB - // on every rebuild -- acceptable for a first pass, since that's the rare - // case in a real follow graph. - const cached = await this.cache.getSetMembers(followSetKey(pubkey)) - if (cached.length) { - return cached + // Redis is the fast path once a pubkey's follow list has gone through + // updateFollowList(); a pubkey that genuinely follows no one is + // indistinguishable from an uncached one here and falls back to the DB on + // every rebuild -- acceptable for a first pass, since that's the rare case + // in a real follow graph. The pubkeys Redis has no list for share one query. + private async getFollowLists(pubkeys: Pubkey[]): Promise { + const lists = await Promise.all(pubkeys.map((pubkey) => this.cache.getSetMembers(followSetKey(pubkey)))) + + // A `p` value that is not a 64-character hex key would be read as an + // author prefix and match other authors' contact lists. + const misses = [ + ...new Set( + pubkeys + .filter((pubkey, index) => !lists[index].length && HEX_PUBKEY_PATTERN.test(pubkey)) + .map((pubkey) => pubkey.toLowerCase()), + ), + ] + if (!misses.length) { + return lists } - const [event] = await this.eventRepository.findByFilters([ - { kinds: [EventKinds.CONTACT_LIST], authors: [pubkey], limit: 1 }, + const stored = new Map() + const rows = await this.eventRepository.findByFilters([ + { kinds: [EventKinds.CONTACT_LIST], authors: misses, limit: misses.length }, ]) - - if (!event) { - return [] + for (const row of rows) { + const event = toNostrEvent(row) + if (!stored.has(event.pubkey)) { + stored.set(event.pubkey, extractFollowedPubkeys(event.tags)) + } } - const follows = extractFollowedPubkeys(toNostrEvent(event).tags) - if (follows.length) { - await this.cache.addToSet(followSetKey(pubkey), follows) - } - return follows + await Promise.all( + pubkeys.map(async (pubkey, index) => { + const follows = lists[index].length ? undefined : stored.get(pubkey.toLowerCase()) + if (follows?.length) { + lists[index] = follows + await this.cache.addToSet(followSetKey(pubkey), follows) + } + }), + ) + + return lists } } diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 263ee38f0..10e12ceec 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -1454,6 +1454,24 @@ export const validateSettings = (settings: Settings): ValidationIssue[] => { } } + const wot = settings.wot + for (const key of ['maxPubkeys', 'maxFollowListReads', 'maxEdges'] as const) { + const value = wot?.[key] + if (typeof value === 'number' && !(Number.isSafeInteger(value) && value > 0)) { + issues.push({ path: `wot.${key}`, message: `${key} must be a positive integer` }) + } + } + const minRebuildIntervalSeconds = wot?.minRebuildIntervalSeconds + if ( + typeof minRebuildIntervalSeconds === 'number' && + !(Number.isSafeInteger(minRebuildIntervalSeconds) && minRebuildIntervalSeconds >= 0) + ) { + issues.push({ + path: 'wot.minRebuildIntervalSeconds', + message: 'minRebuildIntervalSeconds must be 0 or a positive integer', + }) + } + validateSubscriptionPlans(settings.payments?.subscriptionPlans, issues) validatePeering(settings, issues) diff --git a/test/unit/services/wot-graph-service.spec.ts b/test/unit/services/wot-graph-service.spec.ts index 778256750..2fa927b48 100644 --- a/test/unit/services/wot-graph-service.spec.ts +++ b/test/unit/services/wot-graph-service.spec.ts @@ -8,12 +8,15 @@ chai.use(chaiAsPromised) const { expect } = chai +import pino from 'pino' + import { ICacheAdapter } from '../../../src/@types/adapters' import { Tag } from '../../../src/@types/base' import { DBEvent } from '../../../src/@types/event' import { IEventRepository } from '../../../src/@types/repositories' import { Settings } from '../../../src/@types/settings' -import { WotGraphService } from '../../../src/services/wot-graph-service' +import { logger as baseLogger } from '../../../src/logger' +import { WOT_FOLLOW_LIST_BATCH_SIZE, WotGraphService } from '../../../src/services/wot-graph-service' describe('WotGraphService', () => { const seedPubkey = 'a'.repeat(64) @@ -31,11 +34,11 @@ describe('WotGraphService', () => { let originalConsoleError: typeof console.error - const dbEventWithFollows = (tags: Tag[]): DBEvent => + const dbEventWithFollows = (tags: Tag[], author = seedPubkey): DBEvent => ({ id: 'row-id', event_id: Buffer.from('00', 'hex'), - event_pubkey: Buffer.from('00', 'hex'), + event_pubkey: Buffer.from(author, 'hex'), event_kind: 3, event_created_at: 0, event_content: '', @@ -88,6 +91,7 @@ describe('WotGraphService', () => { seedPubkey, minimumFollowers: 1, maxDepth: 2, + minRebuildIntervalSeconds: 0, refreshIntervalHours: 24, }, } as any @@ -216,6 +220,13 @@ describe('WotGraphService', () => { expect(await service().getDistance('x')).to.equal(3) }) + it('keeps the shortest distance of an account followed again deeper in the graph', async () => { + followsOf[seedPubkey] = ['a', 'b'] + followsOf.a = ['b', seedPubkey] + + expect(await service().getDistance('b')).to.equal(1) + }) + it('counts a follow list that repeats a p tag as one vote', async () => { settings.wot!.minimumFollowers = 2 followsOf[seedPubkey] = ['a'] @@ -226,14 +237,18 @@ describe('WotGraphService', () => { it('counts a repeated p tag once when the follow list comes from the database', async () => { settings.wot!.minimumFollowers = 2 - followsOf[seedPubkey] = ['a'] + const follower = 'b'.repeat(64) + followsOf[seedPubkey] = [follower] findByFiltersStub.callsFake(async (filters: any[]) => - filters[0].authors[0] === 'a' + filters[0].authors[0] === follower ? [ - dbEventWithFollows([ - ['p', 'x'], - ['p', 'x'], - ]), + dbEventWithFollows( + [ + ['p', 'x'], + ['p', 'x'], + ], + follower, + ), ] : [], ) @@ -406,4 +421,283 @@ describe('WotGraphService', () => { expect(wot.isReady()).to.equal(true) }) }) + + describe('rebuild limits', () => { + let logLines: Sinon.SinonStub + + const warnings = (): string[] => + logLines.args + .map(([line]) => JSON.parse(String(line))) + .filter((entry) => entry.level === pino.levels.values.warn && entry.scope?.endsWith(':wot-graph-service')) + .map((entry) => entry.msg) + + // Every account follows three new ones, so the graph only ends where a limit or maxDepth ends it. + const endlessGraph = () => { + getSetMembersStub.callsFake(async (key: string) => { + const pubkey = key.replace('wot:follows:', '') + const name = pubkey === seedPubkey ? 'seed' : pubkey + return [0, 1, 2].map((index) => `${name}/${index}`) + }) + } + + beforeEach(() => { + logLines = sandbox.stub((baseLogger as any)[pino.symbols.streamSym], 'write') + settings.wot!.maxDepth = 8 + }) + + it('stops at wot.maxFollowListReads, keeping the graph read up to it, and reports the limit', async () => { + endlessGraph() + settings.wot!.maxFollowListReads = 3 + const wot = service() + + expect(await wot.getDistance('seed/2')).to.equal(1) + expect(await wot.getDistance('seed/1/2')).to.equal(2) + expect(await wot.getDistance('seed/2/0')).to.be.undefined + expect(await wot.getDistance('seed/0/0/0')).to.be.undefined + expect(getSetMembersStub).to.have.callCount(3) + expect(warnings()).to.have.lengthOf(1) + expect(warnings()[0]).to.match(/^wot graph rebuild stopped at wot\.maxFollowListReads after 3 follow list reads/) + }) + + it('reports a list left unread in the last layer', async () => { + endlessGraph() + settings.wot!.maxDepth = 2 + settings.wot!.maxFollowListReads = 3 + + expect(await service().getDistance('seed/2/0')).to.be.undefined + expect(warnings()).to.have.lengthOf(1) + expect(warnings()[0]).to.match(/stopped at wot\.maxFollowListReads/) + }) + + it('does not report a limit the rebuild did not need to pass', async () => { + endlessGraph() + settings.wot!.maxDepth = 2 + settings.wot!.maxFollowListReads = 4 + + expect(await service().getDistance('seed/2/0')).to.equal(2) + expect(warnings()).to.deep.equal([]) + }) + + it('stops at wot.maxEdges', async () => { + endlessGraph() + settings.wot!.maxEdges = 5 + const wot = service() + + expect(await wot.getDistance('seed/0/1')).to.equal(2) + expect(await wot.getDistance('seed/0/2')).to.be.undefined + expect(await wot.getDistance('seed/1/0')).to.be.undefined + expect(warnings()).to.have.lengthOf(1) + expect(warnings()[0]).to.match(/stopped at wot\.maxEdges after 4 follow list reads and 5 follows/) + }) + + it('stops at wot.maxPubkeys', async () => { + endlessGraph() + settings.wot!.maxPubkeys = 4 + const wot = service() + + expect(await wot.getDistance('seed/0/0')).to.equal(2) + expect(await wot.getDistance('seed/0/1')).to.be.undefined + expect(warnings()).to.have.lengthOf(1) + expect(warnings()[0]).to.match(/stopped at wot\.maxPubkeys after 4 follow list reads and 4 follows/) + }) + + it('only ever trusts fewer accounts when it stops early: votes it did not read are missing', async () => { + settings.wot!.maxDepth = 2 + settings.wot!.minimumFollowers = 2 + settings.wot!.maxFollowListReads = 2 + followsOf[seedPubkey] = ['a', 'b'] + followsOf.a = ['x'] + followsOf.b = ['x'] + + expect(await service().getDistance('x')).to.be.undefined + }) + + it('rebuilds when a limit changes', async () => { + endlessGraph() + settings.wot!.maxDepth = 2 + settings.wot!.maxFollowListReads = 1 + const wot = service() + expect(await wot.getDistance('seed/0/0')).to.be.undefined + + settings.wot!.maxFollowListReads = 10 + expect(await wot.getDistance('seed/0/0')).to.equal(2) + }) + + it('uses the default for a limit that is not a positive integer', async () => { + endlessGraph() + settings.wot!.maxDepth = 2 + settings.wot!.maxEdges = 0 + settings.wot!.maxPubkeys = -1 + settings.wot!.maxFollowListReads = 1.5 + + expect(await service().getDistance('seed/2/2')).to.equal(2) + expect(warnings()).to.deep.equal([]) + }) + }) + + describe('reading follow lists', () => { + const hexKey = (index: number) => index.toString(16).padStart(64, '0') + + it('reads a layer in batches, with one database query per batch for the lists Redis does not have', async () => { + const follows = Array.from({ length: WOT_FOLLOW_LIST_BATCH_SIZE + 50 }, (_, index) => hexKey(index)) + followsOf[seedPubkey] = follows + let inFlight = 0 + let mostInFlight = 0 + getSetMembersStub.callsFake(async (key: string) => { + inFlight++ + mostInFlight = Math.max(mostInFlight, inFlight) + await new Promise((resolve) => setImmediate(resolve)) + inFlight-- + return followsOf[key.replace('wot:follows:', '')] ?? [] + }) + + await service().getDistance('someone') + + expect(mostInFlight).to.equal(WOT_FOLLOW_LIST_BATCH_SIZE) + expect(findByFiltersStub.args.map(([filters]) => filters)).to.deep.equal([ + [{ kinds: [3], authors: follows.slice(0, WOT_FOLLOW_LIST_BATCH_SIZE), limit: WOT_FOLLOW_LIST_BATCH_SIZE }], + [{ kinds: [3], authors: follows.slice(WOT_FOLLOW_LIST_BATCH_SIZE), limit: 50 }], + ]) + }) + + it('gives each author its own stored contact list, the newest one, and caches it under that author', async () => { + const [alice, bob] = [hexKey(1), hexKey(2)] + followsOf[seedPubkey] = [alice, bob] + findByFiltersStub.resolves([ + dbEventWithFollows([['p', 'x']], bob), + dbEventWithFollows([['p', 'y']], alice), + dbEventWithFollows([['p', 'z']], alice), + ]) + const wot = service() + + expect(await wot.getDistance('x')).to.equal(2) + expect(await wot.getDistance('y')).to.equal(2) + expect(await wot.getDistance('z')).to.be.undefined + expect(addToSetStub).to.have.been.calledWithExactly(`wot:follows:${alice}`, ['y']) + expect(addToSetStub).to.have.been.calledWithExactly(`wot:follows:${bob}`, ['x']) + }) + + it('asks the database only for 64-character hex keys, so a short p value is never read as a prefix', async () => { + const upper = 'B'.repeat(64) + followsOf[seedPubkey] = ['b', 'not-a-pubkey', upper] + findByFiltersStub.resolves([dbEventWithFollows([['p', 'x']], upper.toLowerCase())]) + + expect(await service().getDistance('x')).to.equal(2) + expect(findByFiltersStub).to.have.been.calledOnceWithExactly([ + { kinds: [3], authors: [upper.toLowerCase()], limit: 1 }, + ]) + }) + }) + + describe('rebuilds triggered by contact lists', () => { + const day = 24 * 60 * 60 * 1000 + let clock: Sinon.SinonFakeTimers + + const seedReads = () => + getSetMembersStub.getCalls().filter((call) => call.args[0] === `wot:follows:${seedPubkey}`).length + + beforeEach(() => { + clock = sandbox.useFakeTimers() + settings.wot!.minRebuildIntervalSeconds = 60 + followsOf[seedPubkey] = ['a'] + }) + + it('starts at most one rebuild per interval however many contact lists arrive', async () => { + const wot = service() + await wot.getDistance('a') + + for (let second = 0; second < 300; second++) { + await wot.updateFollowList('a', [`f${second}`]) + await clock.tickAsync(1000) + } + + expect(seedReads()).to.equal(1 + 300 / 60) + expect(await wot.getDistance('f299')).to.equal(2) + }) + + it('applies a contact list that lands during a rebuild one interval after that rebuild ends', async () => { + followsOf[seedPubkey] = ['a', 'd'] + const wot = service() + await wot.getDistance('a') + await clock.tickAsync(60_000) + + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + getSetMembersStub.callsFake(async (key: string) => { + const pubkey = key.replace('wot:follows:', '') + if (pubkey === 'd') { + await gate + } + return followsOf[pubkey] ?? [] + }) + + await wot.updateFollowList('a', ['b']) + await clock.tickAsync(0) + await wot.updateFollowList('a', ['c']) + release() + await clock.tickAsync(0) + + expect(await wot.getDistance('b')).to.equal(2) + expect(await wot.getDistance('c')).to.be.undefined + + await clock.tickAsync(59_999) + expect(await wot.getDistance('c')).to.be.undefined + await clock.tickAsync(1) + expect(await wot.getDistance('c')).to.equal(2) + }) + + it('lets a rebuild started for another reason serve a contact list that was waiting', async () => { + const wot = service() + await wot.getDistance('a') + await wot.updateFollowList('a', ['b']) + + settings.wot!.maxDepth = 3 + expect(await wot.getDistance('b')).to.equal(2) + expect(seedReads()).to.equal(2) + + await clock.tickAsync(60_000) + expect(seedReads()).to.equal(2) + }) + + it('applies a changed interval from the next contact list', async () => { + settings.wot!.minRebuildIntervalSeconds = 3600 + const wot = service() + await wot.getDistance('a') + await wot.updateFollowList('a', ['b']) + + settings.wot!.minRebuildIntervalSeconds = 60 + await clock.tickAsync(30_000) + await wot.updateFollowList('a', ['c']) + await clock.tickAsync(29_999) + expect(seedReads()).to.equal(1) + await clock.tickAsync(1) + expect(seedReads()).to.equal(2) + }) + + it('waits out an interval longer than one timer can', async () => { + settings.wot!.minRebuildIntervalSeconds = (30 * day) / 1000 + const wot = service() + await wot.getDistance('a') + await wot.updateFollowList('a', ['b']) + + await clock.tickAsync(30 * day - 1) + expect(seedReads()).to.equal(1) + await clock.tickAsync(1) + expect(seedReads()).to.equal(2) + }) + + it('uses the default interval for a value that is not a non-negative integer', async () => { + settings.wot!.minRebuildIntervalSeconds = -1 + const wot = service() + await wot.getDistance('a') + await wot.updateFollowList('a', ['b']) + + await clock.tickAsync(59_999) + expect(seedReads()).to.equal(1) + await clock.tickAsync(1) + expect(seedReads()).to.equal(2) + }) + }) }) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 39634a2b0..54add0355 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -26,6 +26,12 @@ import { withSettingsWriteLock, } from '../../../src/utils/settings-config' import { getSettingsFilePath, getSettingsWriteLockPath } from '../../../src/utils/settings-paths' +import { + DEFAULT_WOT_MAX_EDGES, + DEFAULT_WOT_MAX_FOLLOW_LIST_READS, + DEFAULT_WOT_MAX_PUBKEYS, + DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS, +} from '../../../src/services/wot-graph-service' import { toBech32 } from '../../../src/utils/transform' import { getGuidedSettingCategory, @@ -858,6 +864,49 @@ describe('settings-config', () => { }) }) + describe('wot rebuild settings', () => { + const wotIssues = (wot: any) => + validateSettings({ info: { relay_url: 'wss://test.relay', name: 'test' }, network: {}, wot } as any).filter( + (issue) => issue.path.startsWith('wot'), + ) + + it('accepts the shipped defaults', () => { + expect( + wotIssues({ + enabled: true, + seedPubkey: 'a'.repeat(64), + minimumFollowers: 1, + maxDepth: 2, + maxPubkeys: DEFAULT_WOT_MAX_PUBKEYS, + maxFollowListReads: DEFAULT_WOT_MAX_FOLLOW_LIST_READS, + maxEdges: DEFAULT_WOT_MAX_EDGES, + minRebuildIntervalSeconds: DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS, + refreshIntervalHours: 24, + }), + ).to.deep.equal([]) + }) + + for (const key of ['maxPubkeys', 'maxFollowListReads', 'maxEdges']) { + for (const bad of [0, -1, 1.5, '10', Number.NaN, Number.MAX_SAFE_INTEGER + 2]) { + it(`rejects ${key} = ${String(bad)}`, () => { + expect(wotIssues({ [key]: bad }).map((issue) => issue.path)).to.deep.equal([`wot.${key}`]) + }) + } + } + + it('accepts 0 for minRebuildIntervalSeconds', () => { + expect(wotIssues({ minRebuildIntervalSeconds: 0 })).to.deep.equal([]) + }) + + for (const bad of [-1, 1.5, '10', Number.NaN]) { + it(`rejects minRebuildIntervalSeconds = ${String(bad)}`, () => { + expect(wotIssues({ minRebuildIntervalSeconds: bad }).map((issue) => issue.path)).to.deep.equal([ + 'wot.minRebuildIntervalSeconds', + ]) + }) + } + }) + describe('subscription plan settings', () => { const settingsWith = (subscriptionPlans: any) => ({ diff --git a/test/unit/utils/settings.spec.ts b/test/unit/utils/settings.spec.ts index d786d5c04..082591d11 100644 --- a/test/unit/utils/settings.spec.ts +++ b/test/unit/utils/settings.spec.ts @@ -5,6 +5,12 @@ import { tmpdir } from 'os' import Sinon from 'sinon' import { mergeDeepRight } from 'ramda' import { Settings } from '../../../src/@types/settings' +import { + DEFAULT_WOT_MAX_EDGES, + DEFAULT_WOT_MAX_FOLLOW_LIST_READS, + DEFAULT_WOT_MAX_PUBKEYS, + DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS, +} from '../../../src/services/wot-graph-service' import { SettingsFileTypes, SettingsStatic } from '../../../src/utils/settings' import * as settingsConfig from '../../../src/utils/settings-config' @@ -386,6 +392,13 @@ describe('SettingsStatic', () => { expect(defaults).to.have.nested.property('wot.seedPubkey', '') expect(defaults).to.have.nested.property('wot.minimumFollowers', 1) expect(defaults).to.have.nested.property('wot.refreshIntervalHours', 24) + expect(defaults).to.have.nested.property('wot.maxPubkeys', DEFAULT_WOT_MAX_PUBKEYS) + expect(defaults).to.have.nested.property('wot.maxFollowListReads', DEFAULT_WOT_MAX_FOLLOW_LIST_READS) + expect(defaults).to.have.nested.property('wot.maxEdges', DEFAULT_WOT_MAX_EDGES) + expect(defaults).to.have.nested.property( + 'wot.minRebuildIntervalSeconds', + DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS, + ) }) it('user config wot block overrides defaults', () => {