diff --git a/public/config.example.json b/public/config.example.json index b7f16c3..6ec5ee5 100644 --- a/public/config.example.json +++ b/public/config.example.json @@ -6,5 +6,11 @@ "fullRfLog": true, "rfSampler": true, "regionDiscovery": true, - "verifyAdverts": false + "verifyAdverts": false, + + "_beta": "REGION_BETA builds only (rx.on8ar.eu/beta). Ignored by a production build.", + "betaAskGapSec": 2, + "betaTargetGapSec": 15, + "betaMaxAsks": 6, + "betaForgetMin": 5 } diff --git a/src/app.js b/src/app.js index 2f75411..129a323 100644 --- a/src/app.js +++ b/src/app.js @@ -33,7 +33,8 @@ import { heardKeyAfterVerify } from './advertsig.js'; import { buildStatsRequest, parseStats, mergeSample, nextSampleDelay, STATS_CORE, STATS_RADIO, STATS_PACKETS } from './rfstats.js'; import { buildRegionsRequest, parseRegionsResponse, parseSentAck, applyRegionsReply, heardAskDecision, pendingExpired, PENDING_TIMEOUT_MS, recordCandidate, commitAsk, undoAsk, SKIP_IN_FLIGHT, SKIP_BUDGET, SKIP_ANSWERED } from './regionreq.js'; import { - enqueue, dueToSend, takeNext, registerOutstanding, matchOutstanding, pruneOutstanding, markAnswered, + enqueue, dueToSend, takeNext, registerOutstanding, matchOutstanding, pruneOutstanding, + markAnswered, markAsked, } from './regionsprint.js'; import { regionsRows } from './regionsview.js'; import { uplinkState, uplinkWarning, pushOutcome, regionInertReason, buildLogHeader, REGION_DISCOVERY_MIN_FW } from './uplink.js'; @@ -95,9 +96,12 @@ const state = { // takes a repeater out of rotation. The counters exist because the 200-line ring // buffer rolls the per-ask lines out long before a drive ends. beta: { - queue: [], answered: new Set(), outstanding: new Map(), + // targets: pubkey -> { attempts, lastAskedAt, lastHeardAt } for the CURRENT + // encounter. attempts is what the per-encounter cap counts and what a long enough + // silence resets; answered is separate because it outlives every encounter. + queue: [], answered: new Set(), outstanding: new Map(), targets: new Map(), lastSentAt: null, busy: false, overrideRaw: null, - queued: 0, asks: 0, replies: 0, flooded: 0, unmatched: 0, dropped: 0, + queued: 0, heard: 0, asks: 0, replies: 0, flooded: 0, unmatched: 0, dropped: 0, capped: 0, }, // pathResolve: path-hash prefix -> whether it ever resolved to a full pubkey. // A Map, not two counters, because resolvePubkey is called on EVERY reception from @@ -323,8 +327,16 @@ const BETA_OVERRIDE_HOLD_MS = 20000; function betaEnqueue(target) { if (!state.transport) return; const b = state.beta; - if (!featureEnabled(getConfig(), 'regionDiscovery') || !state.regions.supported) { noteRegionInert(); return; } - if (enqueue(b.queue, target, b.answered)) b.queued++; + const cfg = getConfig(); + if (!featureEnabled(cfg, 'regionDiscovery') || !state.regions.supported) { noteRegionInert(); return; } + b.heard++; + const verdict = enqueue(b.queue, target, b.answered, b.targets, Date.now(), { + targetGapMs: cfg.betaTargetGapSec * 1000, + maxAsks: cfg.betaMaxAsks, + forgetMs: cfg.betaForgetMin * 60000, + }); + if (verdict === 'queued-now') b.queued++; + else if (verdict === 'capped') b.capped++; } // betaTick drains the queue. Called from the one-second monitor tick rather than its @@ -333,7 +345,7 @@ function betaEnqueue(target) { function betaTick(now) { const b = state.beta; b.dropped += pruneOutstanding(b.outstanding, now); - if (!dueToSend(b.queue, now, b.lastSentAt, b.busy)) return; + if (!dueToSend(b.queue, now, b.lastSentAt, b.busy, getConfig().betaAskGapSec * 1000)) return; const target = takeNext(b.queue, b.answered); if (!target) return; betaAsk(target); @@ -367,6 +379,9 @@ async function betaAsk(target) { const b = state.beta; b.busy = true; b.lastSentAt = Date.now(); + // Stamped here, at the transmission, not when the target was queued: a target that + // waited its turn behind others must still get its full gap from THIS ask onward. + markAsked(b.targets, target, b.lastSentAt); let overrode = false; try { const frame = buildRegionsRequest(target); @@ -389,8 +404,9 @@ async function betaAsk(target) { } else { b.asks++; registerOutstanding(b.outstanding, ack.tag, target, Date.now()); - dbg('beta → asked ' + target.slice(0, 12) + '… (queue ' + b.queue.length - + ', outstanding ' + b.outstanding.size + ')', 'tx'); + dbg('beta → asked ' + target.slice(0, 12) + '… (attempt ' + + b.targets.get(target).attempts + ' of ' + getConfig().betaMaxAsks + + ' this encounter, queue ' + b.queue.length + ', outstanding ' + b.outstanding.size + ')', 'tx'); } if (overrode) { await new Promise((r) => setTimeout(r, BETA_OVERRIDE_HOLD_MS)); @@ -1476,10 +1492,11 @@ window.addEventListener('DOMContentLoaded', async () => { resolved: Array.from(state.pathResolve.values()).filter(Boolean).length, }, beta: REGION_BETA ? { - queued: state.beta.queued, asks: state.beta.asks, replies: state.beta.replies, + heard: state.beta.heard, queued: state.beta.queued, + asks: state.beta.asks, replies: state.beta.replies, answered: state.beta.answered.size, queue: state.beta.queue.length, outstanding: state.beta.outstanding.size, flooded: state.beta.flooded, - unmatched: state.beta.unmatched, dropped: state.beta.dropped, + unmatched: state.beta.unmatched, dropped: state.beta.dropped, capped: state.beta.capped, } : null, lineCount: lines.length, lineCap: LOG_LINE_CAP, diff --git a/src/config.js b/src/config.js index 5f09753..7cdf70a 100644 --- a/src/config.js +++ b/src/config.js @@ -44,6 +44,15 @@ let inFlight = null; // in-flight loadConfig promise, so concurrent retries shar // normalizeConfig validates + normalizes a parsed config.json object. Throws on // a missing required field (mqttUrl). resolveUrl is optional (empty = node-name // resolution disabled). +// positiveSeconds reads a tuning value that must be a real number of seconds. A +// missing key takes the default; anything unusable (a string, a negative, NaN) also +// takes it rather than disabling the throttle it configures — a typo in config.json +// must never turn into "no limit at all" on a transmitting path. +function positiveSeconds(value, fallback) { + const n = Number(value); + return Number.isFinite(n) && n >= 0 ? n : fallback; +} + export function normalizeConfig(raw) { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('config.json: expected a JSON object'); const c = { @@ -56,6 +65,30 @@ export function normalizeConfig(raw) { fullRfLog: featureEnabled(raw, 'fullRfLog'), rfSampler: featureEnabled(raw, 'rfSampler'), regionDiscovery: featureEnabled(raw, 'regionDiscovery'), + // Two separate throttles for the beta experiment (src/regionsprint.js), both + // seconds, both tunable on the server without a rebuild — that is the point of a + // measurement rig. They answer different questions and must not be conflated: + // + // betaAskGapSec minimum gap between ANY two transmitted asks. Keeps two + // rounds from overlapping and bounds total airtime. + // betaTargetGapSec minimum gap between two asks to the SAME repeater. A node + // held in range is heard many times a minute; this is what + // decides how often each reception is allowed to become an + // ask, and simple_repeater drops anon requests past 4 per + // 180s, so asking one node faster than that cannot help. + // + // Ignored entirely by a production build, where neither throttle exists. + betaAskGapSec: positiveSeconds(raw.betaAskGapSec, 2), + betaTargetGapSec: positiveSeconds(raw.betaTargetGapSec, 15), + // And the two that END the asking. Without them the only exit is a reply, so a + // repeater held in range that never answers is asked every betaTargetGapSec for + // the rest of the session. + // + // betaMaxAsks unanswered asks one repeater gets per encounter + // betaForgetMin silence after which the next reception is a NEW encounter and + // the count starts over + betaMaxAsks: positiveSeconds(raw.betaMaxAsks, 6), + betaForgetMin: positiveSeconds(raw.betaForgetMin, 5), }; if (!c.mqttUrl) throw new Error('config.json: "mqttUrl" is required'); return c; diff --git a/src/regionsprint.js b/src/regionsprint.js index 238544a..13779a1 100644 --- a/src/regionsprint.js +++ b/src/regionsprint.js @@ -16,25 +16,90 @@ // // Everything here is pure: no DOM, no transport, no timers. app.js does the wiring. -export const ASK_SPACING_MS = 2000; // minimum gap between two transmitted asks export const OUTSTANDING_TTL_MS = 120000; // how long an unanswered tag stays matchable -// enqueue adds one target to the back of the queue. A target already queued is not -// added twice: it would be asked twice in a row with nothing heard in between, which -// measures the queue rather than the mesh. A target that has answered is never queued -// again this session — that is the one rule this beta keeps. -export function enqueue(queue, target, answered) { - if (answered.has(target) || queue.includes(target)) return false; - queue.push(target); - return true; +// Two throttles, and they answer different questions. Both come from config.json +// (betaAskGapSec / betaTargetGapSec) so the rig can be retuned on the server between +// drives without a rebuild. +// +// askGapMs between ANY two transmitted asks. Stops two rounds overlapping and +// bounds total airtime. Small by design: a burst of five different +// repeaters heard at once should all get asked while they are in range. +// targetGapMs between two asks to the SAME repeater. This is the one that matters +// for a node parked in range, which is heard many times a minute: +// simple_repeater drops anon requests past 4 per 180s shared across all +// requesters, so asking one node faster than that cannot help and may +// exhaust its limiter for everyone. +export const DEFAULT_ASK_GAP_MS = 2000; +export const DEFAULT_TARGET_GAP_MS = 15000; + +// And two rules that end the asking, because "until it answers" on its own never ends: +// a repeater you keep hearing and that never replies would be asked every targetGap for +// the rest of the session. +// +// maxAsks how many unanswered asks one repeater gets per ENCOUNTER. Past this it +// is dropped, answered or not. simple_repeater allows 4 anon requests per +// 180s across all requesters, so a run much longer than that is spending +// airtime on a limiter that is already refusing. +// forgetMs how long a repeater must be out of earshot before the next reception +// counts as a NEW encounter and gives it a fresh run of maxAsks. This is +// what keeps a node met again 40 km later from being written off by a run +// of failed asks in a spot where it was barely audible. +export const DEFAULT_MAX_ASKS = 6; +export const DEFAULT_FORGET_MS = 5 * 60000; + +// noteHeard updates one target's record and reports it. A gap of forgetMs since the +// last reception starts a NEW encounter: the attempt count and the per-target clock are +// cleared, because the next reception is a different meeting with that repeater — +// different place, different distance — and the failures of the last one say nothing +// about this one. +export function noteHeard(targets, target, now, forgetMs) { + const rec = targets.get(target); + if (!rec) { + const fresh = { attempts: 0, lastAskedAt: null, lastHeardAt: now }; + targets.set(target, fresh); + return fresh; + } + if (now - rec.lastHeardAt >= forgetMs) { rec.attempts = 0; rec.lastAskedAt = null; } + rec.lastHeardAt = now; + return rec; } -// dueToSend gates the worker: one ask at a time, at most one per ASK_SPACING_MS. -// `busy` covers the whole round including the contact-path override hold, so a -// round that has to restore a contact's path cannot be overtaken by the next ask. -export function dueToSend(queue, now, lastSentAt, busy, opts = {}) { +// enqueue records that this repeater was heard again, and is the only thing that ever +// creates an ask. Four reasons it says no, and the reason is returned rather than a +// bare false so the log can say which: +// 'answered' it declared its list: done for this session, no encounter reopens it +// 'queued' already waiting; queueing each reception would ask it twice in a row +// with nothing heard in between, which measures the queue not the mesh +// 'capped' this encounter has used its maxAsks +// 'too-soon' asked less than targetGapMs ago +export function enqueue(queue, target, answered, targets, now, opts) { + const rec = noteHeard(targets, target, now, opts.forgetMs); + if (answered.has(target)) return 'answered'; + if (queue.includes(target)) return 'queued'; + if (rec.attempts >= opts.maxAsks) return 'capped'; + if (rec.lastAskedAt != null && now - rec.lastAskedAt < opts.targetGapMs) return 'too-soon'; + queue.push(target); + return 'queued-now'; +} + +// markAsked counts the attempt and stamps the per-target clock. Called when an ask is +// actually transmitted, never when one is merely queued, so a target that sat in the +// queue behind others is held off from the moment it went out rather than from the +// moment it was heard. +export function markAsked(targets, target, now) { + const rec = targets.get(target) ?? { attempts: 0, lastAskedAt: null, lastHeardAt: now }; + rec.attempts++; + rec.lastAskedAt = now; + targets.set(target, rec); +} + +// dueToSend gates the worker: one round at a time, at most one ask per askGapMs. +// `busy` covers the whole round including the contact-path override hold, so a round +// that has to restore a contact's path cannot be overtaken by the next ask. +export function dueToSend(queue, now, lastSentAt, busy, askGapMs) { if (busy || !queue.length) return false; - return lastSentAt == null || now - lastSentAt >= (opts.spacingMs ?? ASK_SPACING_MS); + return lastSentAt == null || now - lastSentAt >= askGapMs; } // takeNext pops the next target that has not answered in the meantime. A target can diff --git a/src/uplink.js b/src/uplink.js index b148f27..4cfa120 100644 --- a/src/uplink.js +++ b/src/uplink.js @@ -159,9 +159,10 @@ export function buildLogHeader(info) { // repeaters answered at all, and how many asks that took. if (beta) { lines.push(row('beta', beta.answered + ' of ' + beta.queued + ' repeaters answered, ' - + beta.asks + ' asks sent (' + beta.replies + ' answered)')); + + beta.asks + ' asks sent (' + beta.replies + ' answered) from ' + beta.heard + ' receptions')); lines.push(row('beta q', beta.queue + ' queued, ' + beta.outstanding + ' awaiting a reply, ' + beta.dropped + ' timed out, ' + beta.unmatched + ' unmatched replies, ' + beta.flooded + ' sent as FLOOD')); + lines.push(row('beta cap', beta.capped + ' receptions ignored — that repeater had used its asks for this encounter')); } if (companionPubkey) { diff --git a/test/regionsprint.test.mjs b/test/regionsprint.test.mjs index 5026f96..4f172e6 100644 --- a/test/regionsprint.test.mjs +++ b/test/regionsprint.test.mjs @@ -2,15 +2,20 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { enqueue, dueToSend, takeNext, registerOutstanding, matchOutstanding, - pruneOutstanding, markAnswered, ASK_SPACING_MS, OUTSTANDING_TTL_MS, + pruneOutstanding, markAnswered, markAsked, noteHeard, DEFAULT_ASK_GAP_MS, + DEFAULT_TARGET_GAP_MS, DEFAULT_MAX_ASKS, DEFAULT_FORGET_MS, OUTSTANDING_TTL_MS, } from '../src/regionsprint.js'; +const GAP = DEFAULT_TARGET_GAP_MS; +const OPTS = { targetGapMs: GAP, maxAsks: DEFAULT_MAX_ASKS, forgetMs: DEFAULT_FORGET_MS }; +const never = () => new Map(); + const A = 'aa'.repeat(32), B = 'bb'.repeat(32); const reply = (tag) => ({ tag, regions: ['be'], truncated: false, repeaterClock: 100 }); test('enqueue takes a repeater the first time it is heard', () => { const q = []; - assert.equal(enqueue(q, A, new Set()), true); + assert.equal(enqueue(q, A, new Set(), never(), 1_000_000, OPTS), 'queued-now'); assert.deepEqual(q, [A]); }); @@ -19,23 +24,104 @@ test('enqueue does not queue the same target twice while it is still waiting', ( // ask it twice in a row with nothing heard in between, which measures the queue // rather than the mesh. It is re-queued by the NEXT reception after it is asked. const q = [A]; - assert.equal(enqueue(q, A, new Set()), false); + assert.equal(enqueue(q, A, new Set(), never(), 1_000_000, OPTS), 'queued'); assert.deepEqual(q, [A]); }); test('enqueue never re-queues a repeater that already declared its list', () => { const q = []; - assert.equal(enqueue(q, A, new Set([A])), false); + assert.equal(enqueue(q, A, new Set([A]), never(), 1_000_000, OPTS), 'answered'); assert.deepEqual(q, []); }); -test('dueToSend holds the 2s spacing and refuses while a round is running', () => { +test('enqueue holds the same repeater off for targetGapMs after it was asked', () => { + // A repeater parked in range is heard many times a minute, and simple_repeater drops + // anon requests past 4 per 180s shared across all requesters — asking it on every + // single reception cannot help and can exhaust its limiter for everyone. + const targets = new Map([[A, { attempts: 1, lastAskedAt: 1_000_000, lastHeardAt: 1_000_000 }]]); + const justTooSoon = []; + assert.equal(enqueue(justTooSoon, A, new Set(), targets, 1_000_000 + GAP - 1, OPTS), 'too-soon'); + assert.deepEqual(justTooSoon, []); + + const dueAgain = []; + assert.equal(enqueue(dueAgain, A, new Set(), targets, 1_000_000 + GAP, OPTS), 'queued-now'); + assert.deepEqual(dueAgain, [A]); +}); + +test('an unanswered repeater is dropped after maxAsks, however often it is heard', () => { + // Without this the only exit is an answer, so a repeater held in range that never + // replies is asked every targetGap for the rest of the session. + const targets = new Map(); + const q = []; + let now = 1_000_000; + for (let i = 0; i < DEFAULT_MAX_ASKS; i++) { + assert.equal(enqueue(q, A, new Set(), targets, now, OPTS), 'queued-now', 'ask ' + (i + 1)); + q.length = 0; + markAsked(targets, A, now); + now += GAP; + } + assert.equal(enqueue(q, A, new Set(), targets, now, OPTS), 'capped'); + assert.equal(enqueue(q, A, new Set(), targets, now + GAP * 10, OPTS), 'capped', + 'still capped while we keep hearing it'); + assert.deepEqual(q, []); +}); + +test('a repeater met again after forgetMs gets a fresh run — a new encounter is new evidence', () => { + // The same node 40 km later is a different distance and a different antenna aspect. + // Writing it off for the session because it was inaudible once loses exactly the + // repeaters a drive exists to reach. + const targets = new Map(); + const q = []; + let now = 1_000_000; + for (let i = 0; i < DEFAULT_MAX_ASKS; i++) { + enqueue(q, A, new Set(), targets, now, OPTS); + q.length = 0; + markAsked(targets, A, now); + now += GAP; + } + assert.equal(enqueue(q, A, new Set(), targets, now, OPTS), 'capped'); + const later = now + DEFAULT_FORGET_MS; + assert.equal(enqueue(q, A, new Set(), targets, later, OPTS), 'queued-now'); + assert.equal(targets.get(A).attempts, 0, 'the new encounter starts clean'); +}); + +test('an answered repeater is never reopened, not even by a new encounter', () => { + const targets = new Map([[A, { attempts: 0, lastAskedAt: null, lastHeardAt: 1_000_000 }]]); + const answered = new Set([A]); + assert.equal(enqueue([], A, answered, targets, 1_000_000 + DEFAULT_FORGET_MS * 3, OPTS), 'answered'); +}); + +test('noteHeard keeps one encounter alive as long as receptions keep arriving', () => { + // The encounter must be ended by SILENCE, not by elapsed time: a node heard steadily + // for ten minutes is one meeting, and must not be handed a fresh run of asks halfway. + const targets = new Map(); + let now = 1_000_000; + noteHeard(targets, A, now, DEFAULT_FORGET_MS); + markAsked(targets, A, now); + for (let i = 0; i < 20; i++) { + now += DEFAULT_FORGET_MS - 1000; // just inside the window, every time + noteHeard(targets, A, now, DEFAULT_FORGET_MS); + } + assert.equal(targets.get(A).attempts, 1, 'still the same encounter'); +}); + +test('the per-target clock starts when the ask goes out, not when it was queued', () => { + // A target can sit in the queue behind others. Holding it off from the moment it was + // HEARD would let a busy queue shorten the gap between two transmissions to it. + const targets = new Map(); + markAsked(targets, A, 1_000_000); + assert.equal(targets.get(A).lastAskedAt, 1_000_000); + assert.equal(enqueue([], A, new Set(), targets, 1_000_000 + 1000, OPTS), 'too-soon'); +}); + +test('dueToSend holds the ask gap and refuses while a round is running', () => { const q = [A]; - assert.equal(dueToSend(q, 1_000_000, null, false), true, 'nothing sent yet'); - assert.equal(dueToSend(q, 1_000_000, 1_000_000 - 1999, false), false, 'inside the spacing'); - assert.equal(dueToSend(q, 1_000_000, 1_000_000 - ASK_SPACING_MS, false), true); - assert.equal(dueToSend(q, 1_000_000, null, true), false, 'a round is still running'); - assert.equal(dueToSend([], 1_000_000, null, false), false, 'nothing queued'); + const gap = DEFAULT_ASK_GAP_MS; + assert.equal(dueToSend(q, 1_000_000, null, false, gap), true, 'nothing sent yet'); + assert.equal(dueToSend(q, 1_000_000, 1_000_000 - (gap - 1), false, gap), false, 'inside the gap'); + assert.equal(dueToSend(q, 1_000_000, 1_000_000 - gap, false, gap), true); + assert.equal(dueToSend(q, 1_000_000, null, true, gap), false, 'a round is still running'); + assert.equal(dueToSend([], 1_000_000, null, false, gap), false, 'nothing queued'); }); test('takeNext skips a target that answered while it sat in the queue', () => { diff --git a/test/uplink.test.mjs b/test/uplink.test.mjs index 28ae467..896bcf9 100644 --- a/test/uplink.test.mjs +++ b/test/uplink.test.mjs @@ -262,12 +262,13 @@ test('buildLogHeader reports the beta counters when the experiment is running', version: '1.14.0-beta-sprint', nowISO: 'now', config: null, fwVer: 13, regionsSupported: true, uplink: 'ok', pending: 0, lineCount: 1, lineCap: 200, beta: { - queued: 22, asks: 61, replies: 7, answered: 7, queue: 3, - outstanding: 5, flooded: 1, unmatched: 2, dropped: 12, + heard: 340, queued: 22, asks: 61, replies: 7, answered: 7, queue: 3, + outstanding: 5, flooded: 1, unmatched: 2, dropped: 12, capped: 96, }, }); - assert.match(h, /beta {7}7 of 22 repeaters answered, 61 asks sent \(7 answered\)/); + assert.match(h, /beta {7}7 of 22 repeaters answered, 61 asks sent \(7 answered\) from 340 receptions/); assert.match(h, /beta q {5}3 queued, 5 awaiting a reply, 12 timed out, 2 unmatched replies, 1 sent as FLOOD/); + assert.match(h, /beta cap {3}96 receptions ignored/); }); test('buildLogHeader leaves the beta rows out of a production build', () => {