fix: one silent repeater killed every later region ask for the session

state.regions.pending is the single in-flight slot, and it was released in only
three places: a FLOOD send-ack, an accepted reply, and disconnect. None of those
is the ordinary outcome for a moving receiver — a request sent DIRECT to a
repeater we have already driven past is simply never answered, and that left the
slot occupied for the rest of the session.

heardAskEligible gates on that slot, so the first unanswered ask disabled the
event-driven path entirely. What remained was the 60s timer picking a candidate
from the whole session pool — exactly the clock-chosen, minute-late ask the
module header says cannot work at speed. A 23-minute commute log shows ~19
repeaters heard, every ask landing on the timer cadence, not one
"heard ... directly" line, and a single reply.

A pending request now carries sentAt and expires after PENDING_TIMEOUT_MS,
swept by the one-second tick rather than a setTimeout — this app is routinely
backgrounded mid-drive, where a timer fires late or not at all. A pending
without a sentAt counts as expired: a wedged slot costs a whole session, an
early expiry costs one ask that the airtime budget already bounds.

Two invariants the timer path documented but never enforced, unnoticed only
because the wedged slot meant the heard path never ran:

- The shared 60s airtime budget is now stamped in commitAndAsk, the one site
  that transmits, so it counts asks from both paths. It was stamped only in
  maybeAskHeardTarget, so timer asks spent airtime for free.
- The timer no longer asks over a live request. Doing so overwrote pending.tag
  and applyRegionsReply then rejected the real reply as a tag mismatch, so the
  fallback path was destroying the answers this feature exists to collect.

OVERRIDE_ROUND_TIMEOUT_MS now derives from the same constant: once the contact
path override is torn down no reply can arrive, so pending must not outlive it.

Also fixes the log line that hid this. "every repeater heard so far has already
answered" was printed whenever the pool came up empty, including when every
candidate was merely waiting out its retry backoff — it read as a finished job
while one repeater of nineteen had answered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erwin FitenandClaude Opus 5 committed 2026-09-11 09:30:13 +02:00
1 parent 00ae520eec
commit 52b7ff534f
3 files changed
+165 -14

No files matched your search

+63 -11
View File
@@ -31,7 +31,7 @@ import { loadConfig, getConfig, featureEnabled } from './config.js';
import { buildRfLogRecord } from './capture.js';
import { heardKeyAfterVerify } from './advertsig.js';
import { buildStatsRequest, parseStats, mergeSample, nextSampleDelay, STATS_CORE, STATS_RADIO, STATS_PACKETS } from './rfstats.js';
import { buildRegionsRequest, parseRegionsResponse, selectNextTarget, parseSentAck, applyRegionsReply, heardAskEligible } from './regionreq.js';
import { buildRegionsRequest, parseRegionsResponse, selectNextTarget, parseSentAck, applyRegionsReply, heardAskEligible, pendingExpired, PENDING_TIMEOUT_MS } from './regionreq.js';
import { regionsRows } from './regionsview.js';
import { uplinkState, uplinkWarning, pushOutcome, regionInertReason, buildLogHeader, REGION_DISCOVERY_MIN_FW } from './uplink.js';
import {
@@ -206,6 +206,23 @@ function fireDiscover(now) {
// backoff, so which path fires never changes the airtime spent — only the timing.
const REGION_SENT_ACK_TIMEOUT_MS = 4000;
// expireStalePendingAsk frees the single pending slot once its round is over. Driven
// by the one-second tick rather than a setTimeout on purpose: this app is routinely
// backgrounded on a phone mid-drive, where a timer fires late or not at all, and the
// slot is exactly what must not be held hostage by a suspended page.
function expireStalePendingAsk(now) {
const r = state.regions;
if (!pendingExpired(r.pending, now)) return;
const target = r.pending.target;
r.pending = null;
// A silent repeater is not a repeater that declared nothing, so it stays demoted
// and keeps its attempts count — the retry backoff, not this, decides when it is
// asked again. All this releases is the in-flight slot.
dbg('regions: no reply from ' + target.slice(0, 12) + '… within '
+ Math.round(PENDING_TIMEOUT_MS / 1000) + 's — slot freed for the next repeater heard', 'st');
finishOverrideRound(target); // no-op unless this round overrode the contact's path
}
function maybeQueryRegions() {
if (!state.transport) return;
const r = state.regions;
@@ -224,16 +241,35 @@ function maybeQueryRegions() {
// noteRegionInert says which gate is holding this, exactly once — the four
// reasons were previously indistinguishable from an empty candidate pool.
if (!featureEnabled(cfg, 'regionDiscovery') || !r.supported) { noteRegionInert(); return; }
// This path is the FALLBACK for a candidate heard once and never heard again, so it
// is bound by the same two invariants as the heard path — it just never enforced
// them, which went unnoticed only because a wedged pending slot meant the heard
// path never ran at all:
// 1. one request in flight. Asking over a live one overwrites pending.tag, and
// applyRegionsReply then rejects the real reply as a tag mismatch — the timer
// was destroying the very answers this feature exists to collect.
// 2. one ask per 60s of AIRTIME. simple_repeater rate-limits anon requests to 4
// per 180s shared across all types and requesters, so two paths each asking
// on their own clock makes a reply less likely, not more.
const nowMs = Date.now();
if (r.pending && !pendingExpired(r.pending, nowMs)) return;
if (!regionDiscoverDue(nowMs, r.lastAskAt)) return;
const candidates = Array.from(r.candidates, ([pubkey, advertTs]) => ({ pubkey, advertTs }));
const target = selectNextTarget({
candidates, answered: r.answered, demoted: r.demoted, cursor: r.cursor,
attempts: r.attempts, lastAskedAt: r.lastAskedAt, now: Date.now(),
attempts: r.attempts, lastAskedAt: r.lastAskedAt, now: nowMs,
});
if (!target) {
// Silence here has two very different causes and they must not read alike.
// Silence here has three very different causes and they must not read alike.
// "already answered" used to be printed for all of them, which reads as a
// finished job — the field log that exposed the wedged-pending bug showed this
// line while exactly one of nineteen repeaters had ever answered.
const answeredCount = Array.from(r.candidates.keys()).filter((k) => r.answered.has(k)).length;
const why = r.candidates.size === 0
? 'no repeater heard yet'
: 'every repeater heard so far has already answered';
: answeredCount === r.candidates.size
? 'every repeater heard so far has already answered'
: answeredCount + ' of ' + r.candidates.size + ' answered; the rest are waiting out their retry backoff';
dbg('regions: nothing to ask — ' + why, 'st');
return; // do not transmit
}
@@ -254,10 +290,8 @@ function maybeAskHeardTarget(target, advertTs) {
if (!featureEnabled(cfg, 'regionDiscovery') || !r.supported) return;
const now = Date.now();
if (!heardAskEligible(target, advertTs, r, now)) return;
// Consume the shared budget here, same as the timer path — both paths stamp the
// SAME clock (r.lastAskAt) so the one-ask-per-60s ceiling holds no matter which
// path actually fires.
r.lastAskAt = now;
// The shared budget is consumed by commitAndAsk, the one site that transmits, so
// the one-ask-per-60s ceiling holds no matter which path fires.
dbg('regions: heard ' + target.slice(0, 12) + '… directly — asking now', 'st');
commitAndAsk(target, advertTs);
}
@@ -275,13 +309,25 @@ function commitAndAsk(target, advertTs) {
const frame = buildRegionsRequest(target);
r.cursor++;
r.attempts.set(target, (r.attempts.get(target) ?? 0) + 1);
r.lastAskedAt.set(target, Date.now());
r.demoted.add(target); // demoted until it answers — silence must never look like "declared nothing"
const sentAt = Date.now();
r.lastAskedAt.set(target, sentAt);
// The shared one-ask-per-60s airtime budget is stamped HERE, at the one site that
// actually transmits, so it counts transmissions from BOTH paths. Stamping it only
// in maybeAskHeardTarget meant timer-path asks spent airtime without consuming the
// budget, so "which path fires never changes the airtime spent" was not true.
r.lastAskAt = sentAt;
// tag starts null: the reply-matcher (applyRegionsReply) treats a null tag as
// "not yet confirmed" and refuses to accept ANY reply until the RESP_CODE_SENT
// ack (captured below) fills it in — a reply must never be attributed on the
// sole evidence that a request happens to be pending.
r.pending = { target, advertTs, tag: null };
//
// sentAt bounds how long this occupies the single pending slot (pendingExpired in
// src/regionreq.js). Without it a request sent DIRECT and never answered — the
// ordinary outcome once we have driven past the repeater — held the slot for the
// whole session and, through heardAskEligible's pending gate, silently disabled
// every later event-driven ask.
r.pending = { target, advertTs, tag: null, sentAt };
prepareAndAskRegions(target, frame);
}
@@ -298,7 +344,10 @@ const CONTACT_WRITE_TIMEOUT_MS = 4000;
// est_timeout (returned in the send-ack but otherwise unused here) is normally
// shorter, but nothing tells us a reply is NEVER coming — this is the backstop that
// guarantees restoreContact still runs even if the round never resolves any other way.
const OVERRIDE_ROUND_TIMEOUT_MS = 20000;
// Shares PENDING_TIMEOUT_MS by construction: once this restore runs the contact is
// back on its stale path and no reply can arrive, so the pending slot must not
// outlive the override that made the ask answerable in the first place.
const OVERRIDE_ROUND_TIMEOUT_MS = PENDING_TIMEOUT_MS;
// getContact reads one contact by pubkey. Resolves parseContactReply's result, or
// null on a timeout/send failure — callers treat null the same as "not a contact":
@@ -632,6 +681,9 @@ function monitorTick() {
else renderDiscoverStatus(dec);
// Region discovery runs on its own clock and is NOT gated on dec.fire, so the
// stationary pause cannot silence it — see regionDiscoverDue in monitor.js.
// Free a timed-out ask BEFORE the region paths run, so the slot is available to
// the very next repeater heard instead of one tick later.
expireStalePendingAsk(now);
if (regionDiscoverDue(now, state.regions.lastEvalAt)) maybeQueryRegions();
// A session that started without config must be able to heal without a restart:
// retry once a minute (not per tick) for as long as it is missing.
+30 -1
View File
@@ -109,11 +109,40 @@ export function selectNextTarget(state) {
// budget. Layering demotion on top would be a second fairness mechanism solving a
// problem this event ordering already solves.
export function heardAskEligible(target, advertTs, r, now) {
if (r.pending) return false;
if (r.pending && !pendingExpired(r.pending, now)) return false;
if (!regionDiscoverDue(now, r.lastAskAt)) return false;
return isTargetDue(target, advertTs, r.answered, r.attempts, r.lastAskedAt, now);
}
// PENDING_TIMEOUT_MS: how long one outstanding request may hold the single pending
// slot. This app deliberately keeps only ONE ask in flight, so that slot is also the
// gate on the event-driven path (heardAskEligible above) — which means an ask that is
// never released takes every LATER ask down with it.
//
// That is exactly what happened in the field (2026-09-11 commute): pending was
// cleared on a FLOOD send-ack, on an accepted reply, and on disconnect — but the
// ordinary outcome for a moving receiver is none of those. A request sent DIRECT to a
// repeater we have already driven past is simply never answered, and that left the
// slot occupied for the rest of the session: 23 minutes, ~19 repeaters heard, one
// reply, and not a single event-driven ask after the first silent one.
//
// The value is the same horizon as the contact-path override backstop in app.js, and
// that is not a coincidence worth letting drift: once the override is torn down the
// contact is back on its stale path and the reply can no longer arrive, so a pending
// request must never outlive its own override.
export const PENDING_TIMEOUT_MS = 20000;
// pendingExpired reports whether the outstanding request has been waiting long enough
// that the round is over. A missing sentAt counts as EXPIRED, not as in-flight — the
// asymmetry is deliberate: a wedged slot silently disables the heard path for a whole
// session, while an early expiry costs at most one extra ask and the shared 60s
// airtime budget (regionDiscoverDue) bounds even that. Fail toward expiry.
export function pendingExpired(pending, now, opts = {}) {
if (!pending) return false;
if (pending.sentAt == null) return true;
return now - pending.sentAt >= (opts.timeoutMs ?? PENDING_TIMEOUT_MS);
}
export function parseRegionsResponse(bytes) {
if (!bytes || bytes.length < 10 || bytes[0] !== PUSH_CODE_BINARY_RESPONSE) return null;
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+72 -2
View File
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import {
buildRegionsRequest, parseRegionsResponse, selectNextTarget, CMD_SEND_ANON_REQ,
parseSentAck, RESP_CODE_SENT, applyRegionsReply, TRUNCATION_WARN_BYTES, retryBackoffFor,
isTargetDue, heardAskEligible,
isTargetDue, heardAskEligible, pendingExpired, PENDING_TIMEOUT_MS,
} from '../src/regionreq.js';
import { REGION_INTERVAL_MS } from '../src/monitor.js';
@@ -292,7 +292,10 @@ test('heardAskEligible: an already-answered repeater is NOT eligible', () => {
});
test('heardAskEligible: an ask already pending blocks a heard target regardless of budget/backoff', () => {
const r = { pending: { target: B, advertTs: 1, tag: null }, lastAskAt: null, answered: new Map(), attempts: new Map(), lastAskedAt: new Map() };
// sentAt is what makes this pending genuinely in-flight rather than expired (see
// pendingExpired). The one-ask-at-a-time rule this asserts is unchanged; it is now
// bounded in time, which the expiry tests below cover.
const r = { pending: { target: B, advertTs: 1, tag: null, sentAt: 1_000_000 }, lastAskAt: null, answered: new Map(), attempts: new Map(), lastAskedAt: new Map() };
assert.equal(heardAskEligible(A, 1, r, 1_000_000), false);
});
@@ -341,3 +344,70 @@ test('a reply that is only padding yields no regions, not one empty name', () =>
const padded = new Uint8Array([0x8c, 0, ...le32(1), ...le32(2), 0, 0, 0, 0, 0, 0, 0, 0]);
assert.deepEqual(parseRegionsResponse(padded).regions, []);
});
// --- Pending-request expiry ---------------------------------------------------
// Field regression (2026-09-11 commute log): 23 minutes, ~19 repeaters heard, one
// single reply. Every ask in the log landed exactly on the 60s timer cadence and
// not one "heard … directly — asking now" line appeared, even though repeaters
// were being heard continuously. Cause: state.regions.pending was cleared in only
// three places — a FLOOD send-ack, an accepted reply, and disconnect — so the
// ordinary outcome on a moving receiver (sent DIRECT, never answered) left it set
// forever. heardAskEligible's pending gate then disabled the event-driven path for
// the rest of the session, leaving only the clock-picked ask that the module header
// says cannot work while moving. A pending request must expire.
test('pendingExpired: a request still inside its window has not expired', () => {
const p = { target: A, advertTs: null, tag: 1, sentAt: 1_000_000 };
assert.equal(pendingExpired(p, 1_000_000 + PENDING_TIMEOUT_MS - 1), false);
});
test('pendingExpired: a request outstanding past its window has expired', () => {
const p = { target: A, advertTs: null, tag: 1, sentAt: 1_000_000 };
assert.equal(pendingExpired(p, 1_000_000 + PENDING_TIMEOUT_MS), true);
});
test('pendingExpired: no pending request is not an expired one', () => {
assert.equal(pendingExpired(null, 1_000_000), false);
});
test('pendingExpired: a pending without a sentAt is treated as expired, never as a permanent block', () => {
// Asymmetric on purpose. A pending that wedges forever silently kills the whole
// event-driven path for a session; one that expires early costs at most one extra
// ask, and the shared 60s airtime budget bounds even that. Fail toward expiry.
assert.equal(pendingExpired({ target: A, advertTs: null, tag: null }, 1_000_000), true);
});
test('heardAskEligible: an EXPIRED pending no longer blocks a heard repeater', () => {
// The exact field scenario: an unanswered ask must not cost us every later one.
const r = {
pending: { target: B, advertTs: null, tag: 7, sentAt: 1_000_000 },
lastAskAt: null, answered: new Map(), attempts: new Map(), lastAskedAt: new Map(),
};
const stillInFlight = 1_000_000 + PENDING_TIMEOUT_MS - 1;
assert.equal(heardAskEligible(A, null, r, stillInFlight), false,
'one request at a time still holds while the reply could plausibly arrive');
const afterExpiry = 1_000_000 + PENDING_TIMEOUT_MS;
assert.equal(heardAskEligible(A, null, r, afterExpiry), true,
'but a silent request must not disable the heard path for the rest of the session');
});
test('a silent repeater does not wedge the heard path for every later repeater', () => {
// Regression at the level the field log showed it: ask B, hear nothing back, then
// drive into range of A. Before the fix this returned false forever.
const t0 = 1_000_000;
const r = {
pending: null, lastAskAt: null,
answered: new Map(), attempts: new Map(), lastAskedAt: new Map(),
};
// B is heard and asked.
assert.equal(heardAskEligible(B, null, r, t0), true);
r.lastAskAt = t0;
r.attempts.set(B, 1);
r.lastAskedAt.set(B, t0);
r.pending = { target: B, advertTs: null, tag: 7, sentAt: t0 };
// B never answers. A minute later we are past a different repeater.
const later = t0 + REGION_INTERVAL_MS;
assert.equal(heardAskEligible(A, null, r, later), true,
'A is due, the budget has elapsed, and B\'s silence is not A\'s problem');
});