Skip to content

fix(relay): never cache a region hint from a one-region catalog - #19322

Closed
Jinwoo-H wants to merge 8 commits into
mainfrom
relay/region-probe-full-catalog
Closed

Jinwoo-H wants to merge 8 commits into
mainfrom
relay/region-probe-full-catalog

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​297 $\color{#cf222e}{\Huge{\mathbf{−}}}$​7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​290
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​153 $\color{#cf222e}{\Huge{\mathbf{−}}}$​65 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​88

Follow-up to #19233 from the post-merge adversarial review. Three findings on the desktop region probe, all reproduced against main.

Why

  • HIGH: a one-region catalog cached a 24 h hint. The director lists only regions that have a general, ready, heartbeating cell (assignment-store.ts regionCatalog), so a roll wave or heartbeat stall shortens the catalog. The resolver only required every listed region to be measured, so a lone healthy region won against nothing and was written as a day-long hint. Two existing tests pinned that behaviour. An Asia desktop refreshing while the Asia cells drained would publish us-central1 for a day; a US desktop refreshing while US cells were absent would publish asia-east2, the exact incident fix(relay): stop rejecting the near region on a cold first probe #19233 was written to end.
  • MEDIUM: the warm-up shared the 1.5 s sample budget. The warm-up exists because the first request pays DNS, TCP, and TLS. A warm-up timeout drops the region as unreachable, which withholds the hint for an hour and places the desktop at the director default. On a lossy far link that is the region the desktop most needs measured.
  • LOW: the self-heal probe skipped the director-ownership check. Catalog probe origins must be under the director's hostname; the assigned-cell probe had no such fence, so a director could point an unauthenticated GET carrying the desktop's address at any https host.

What

  • refresh() withholds the hint (1 h no-hint TTL) when reports.length < RELAY_REGIONS.length, logged with the new reason catalog-incomplete.
  • WARMUP_TIMEOUT_MS = 3 × PROBE_TIMEOUT_MS; RelayProbe takes an optional 'warmup' | 'sample' phase and createProbe picks the budget from it. An explicit requestTimeoutMs option still overrides both, as before.
  • invalidateIfAssignedCellIsFar returns early unless the cell origin passes isProbeOriginForDirector, now exported from relay-region-catalog-fetch.ts.
  • measuredRegions / bestMeasurement / selectRegionMeasurement and the switch margins moved to relay-region-selection.ts to keep the resolver under the line budget. No behaviour change.

Tests

  • New: lone-region catalog → no hint, 1 h TTL, catalog-incomplete reason (fails without the fix).
  • New: warm-up requests get 4 500 ms and samples 1 500 ms, counted through AbortSignal.timeout.
  • New: a cell origin outside the director's domain is never probed and the cache is untouched.
  • The two tests that asserted a lone-region hint now use a two-region catalog; their intent (corrupt cache recovery, expiry bound) is preserved.
  • pnpm vitest run src/main/runtime/relay 159/159, pnpm tc:node, oxlint clean.

Also

Review round 3 (Opus sweep)

  • The catalog request now gets the warm-up budget (4.5 s): it is the coldest request in the sequence and a timeout withheld the hint for an hour.
  • Reason ordering: a lone region that is unreachable or flapping logs all-unreachable / all-rejected; catalog-incomplete is reserved for a lone healthy region, so a support census of client-side breakage is not hidden by a roll wave.
  • Tests pin the exact budget sequence, the requestTimeoutMs override, and the aggregated unreplayable warning text and count.

Cost and compatibility notes

  • Worst-case cold resolve() grows from 7.5 s to 13.5 s (catalog 4.5 s, then warm-up 4.5 s, then three 1.5 s sample rounds, all sequential; regions run in parallel within each phase). The drain grace floor is 60 s, so a drain rotation still fits, and the no-hint case re-enters it hourly rather than daily. The drain-rotation path awaits it serially; if the roll-wave frequency makes that hourly cost visible, a wall-clock deadline around resolvePreferredRegion is the next step.
  • RELAY_REGIONS.length is now load-bearing: a desktop on this build withholds the hint permanently (and re-probes hourly) in any environment that serves fewer regions than the constant lists. Retiring a region needs a desktop release that shrinks the constant first; adding one is safe (the catalog schema caps at the constant, so an unknown region fails the schema as before).

Review round 4 (second Opus pass)

  • An incomplete catalog no longer discards a correct incumbent. A hint earned against a full catalog that still measures is held with the 24 h TTL; a lone survivor that is not the incumbent is still never promoted. Without this, an expiry landing during the other region's roll wave sent a correctly homed desktop to the director default for an hour.
  • An empty catalog (every region draining at once) is classified catalog-incomplete, not all-unreachable.

Review round 5 (Codex)

  • The cache records fullCatalog: true only on a hint that won against every served region. Only a marked hint is held through an incomplete catalog, and the held entry is written without the marker, so one roll wave can extend a proven hint by a day but the next expiry must re-earn it. A legacy cache or a lone survivor is never renewed on partial evidence.
  • The hold is logged as held-previous, not measured.
  • Self-heal rereads the cache before deleting it, so a refresh that landed during its probes is not deleted on a stale verdict (superseded-by-refresh). This race predates the PR.

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The relay region resolver now uses shared selection rules with deterministic tie-breaking and latency thresholds. Warm-up probes use a longer timeout than sample probes. Incomplete catalogs can retain a measured incumbent or withhold a region hint and record catalog-incomplete. Assigned cell probing requires director ownership and rejects malformed URLs. Replay warnings now report unreplayable pending connections in one consolidated message. Tests cover these behaviors.

Merge Risk: 🟡 Moderate · up to 43d31

The change can preserve a relay-region hint from an unverified legacy cache during an incomplete catalog and renew it for 24 hours. Cache eligibility tracking and regression coverage should be added before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: preventing region hints from being cached when the catalog contains only one region.
Description check ✅ Passed The description is detailed and covers the problem, reasons, implementation changes, tests, compatibility, and follow-up findings. It does not use every template heading, but it provides the required …
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 45f195fe-c3f2-464a-83dc-f2cdc03633a3

📥 Commits

Reviewing files that changed from the base of the PR and between 83b1558 and 14ddeb7.

📒 Files selected for processing (6)
  • src/main/runtime/relay/relay-region-catalog-fetch.ts
  • src/main/runtime/relay/relay-region-preference.test.ts
  • src/main/runtime/relay/relay-region-preference.ts
  • src/main/runtime/relay/relay-region-probe-log.ts
  • src/main/runtime/relay/relay-region-probe.ts
  • src/main/runtime/relay/relay-region-selection.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — a focused fix to the desktop relay region probe, addressing the three post-merge adversarial-review findings on #19233.

  • Never cache a one-region hint — refresh() now withholds the hint (1 h NO_HINT_TTL_MS) when the catalog drops a region, logged as catalog-incomplete. This closes the roll-wave / heartbeat-stall case where a lone healthy region won against nothing and pinned the desktop for 24 h.
  • Wider warm-up budget — RelayProbe carries a 'warmup' | 'sample' phase; the discarded first request now gets WARMUP_TIMEOUT_MS = 3 × PROBE_TIMEOUT_MS so a cold TLS path on a lossy link no longer drops the whole region.
  • Fenced self-heal probe — invalidateIfAssignedCellIsFar early-returns unless the assigned cell origin is under the director's hostname (reusing the existing isProbeOriginForDirector ownership rule), preventing an unauthenticated GET /health against an arbitrary host.
  • Mechanical extraction — measuredRegions / bestMeasurement / selectRegionMeasurement move to relay-region-selection.ts with no behavior change, keeping the resolver under the line budget.

The three new tests each pin the fix (and fail on the pre-fix code): the one-region catalog test asserts an exact 1 h expiresAt and the catalog-incomplete reason, the warm-up test counts AbortSignal.timeout arguments (2 × 4500 ms warm-up vs 7 × 1500 ms sample/catalog), and the fence test asserts the attacker origin is never fetched and the cache is untouched.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — two commits landed since the prior pullfrog review; both are clean.

  • Refuse a malformed assigned-cell origin — isProbeOriginForDirector now returns false when new URL(...) throws instead of throwing, so a non-URL cell cannot reject the fire-and-forget self-heal probe. The fence test now also drives 'not a url' through invalidateIfAssignedCellIsFar and confirms no fetch, no probe, and an untouched cache.
  • Aggregate unreplayable-pending-connection logging — replayPendingConnections logs one [relay] warn per ack with an entry count instead of one per unreplayable pending entry, the bundled #19238 follow-up. The dialing path is unchanged; the single-entry test still passes, though no test exercises the multi-entry → one warn case.

Both additions address edge cases without altering the previously reviewed region-probe behavior.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…achability before catalog shape

- the catalog fetch is the coldest request of the sequence (DNS, TCP, TLS to the director) and
  ran on the 1.5 s sample clock; a timeout withheld the hint for an hour
- a lone region that is unreachable or flapping now logs all-unreachable / all-rejected, so a
  census of client-side network breakage is not hidden by a roll wave
- tests pin the budget sequence, the requestTimeoutMs override, and the aggregated warning text

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor observation inline.

Reviewed changes — one commit (27e685a) landed since the prior pullfrog review; the region-probe behavior is otherwise unchanged.

  • Gave the catalog request the warm-up budget — probeCatalog now fetches /v1/regions on WARMUP_TIMEOUT_MS (4.5 s) instead of the sample budget, since it is the coldest request in the sequence and a catalog timeout previously withheld the hint for an hour.
  • Reported reachability before catalog shape — refreshReason now classifies all-unreachable / all-rejected before catalog-incomplete, reserving catalog-incomplete for a lone healthy region so a support census of client-side breakage is not hidden by a roll wave.
  • Pinned the budget sequence and override — tests now assert the exact [4500 × 3, 1500 × 6] timeout sequence, that requestTimeoutMs overrides every budget, and the aggregated one-line unreplayable-connection warning.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — one commit (2c2fa3d) landed since the prior pullfrog review, closing that review's single inline finding.

  • Classified an empty catalog as catalog-incomplete — refreshReason now returns catalog-incomplete when reports.length === 0 before the reachability checks, so a total drain (every region losing its general/ready/heartbeating cell at once, regionCatalog() → []) no longer falls through the vacuously-true [].every(unreachable) and mislabels as all-unreachable. The catalog-incomplete path is now reserved for catalog-shape cases and all-unreachable stays meaningful for the client-side-breakage census.
  • Pinned the empty-catalog classification — a new test drives catalogFetch([]) and asserts the exact { reason: 'catalog-incomplete', regions: [] } event; it fails on the pre-fix code.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…alog

An expiry that lands during the other region's roll wave saw a one-region catalog and
withheld the hint, sending a correctly homed desktop to the director default for an hour.
The incumbent was earned against a full catalog, so it is kept; a lone survivor that is
not the incumbent is still never promoted.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: d81e4631-f5e1-4b34-a4fe-6d08ae8cc6b6

📥 Commits

Reviewing files that changed from the base of the PR and between 2c2fa3d and 43d31d4.

📒 Files selected for processing (2)
  • src/main/runtime/relay/relay-region-preference.test.ts
  • src/main/runtime/relay/relay-region-preference.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — one commit (43d31d4b) landed since the prior pullfrog review, and it is a clean refinement of the round-3 reordering.

  • Held a still-measured incumbent through an incomplete catalog — refresh() now derives complete = measurements.length === reports.length && reports.length === RELAY_REGIONS.length and, when incomplete, selects incumbent ?? null (the previous region if still listed and measured) instead of always withholding. An expiry that lands during the other region's roll wave now keeps a correctly homed desktop on its incumbent with the 24 h CACHE_TTL_MS rather than bouncing it to the director default for an hour.
  • Still refused to promote a lone survivor — a lone region that is not the incumbent remains withheld (region: null), so the core "never cache a one-region hint" property is preserved; only the incumbent, earned against a full catalog, is exempt.
  • Added two regression tests — holds a still-measured incumbent through an incomplete catalog drives an expired asia-east2 cache through a one-region catalog and asserts the 24 h re-cache plus the logged chosenRegion; does not promote a lone survivor that is not the incumbent pins the non-incumbent-withhold invariant. Both exercise refresh (the helper's expiresAt default is 999 against now: 1_000), so neither is a vacuous cache-hit.

The change is client-side only (no wire or shared-type impact) and the prior inline finding is already retired.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

… the cache proves it won a full one

The cache now records fullCatalog: true on a hint earned against every served region. A
cache without the marker (older build, or a lone survivor) is re-earned, not renewed.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one minor suggestion on test coverage inline.

Reviewed changes — one commit (7835c05) landed since the prior pullfrog review, refining the incumbent-hold exception that review approved.

  • Gated the incumbent-hold on a fullCatalog marker — the cache schema gains an optional fullCatalog: z.literal(true), and refresh() now holds a still-measured incumbent through an incomplete catalog only when previous?.fullCatalog proves that hint was earned against a full catalog. A cache written by an older build (which may hold a lone survivor) is treated as unverified and re-earned, closing the gap where the incumbent exception could have resurrected the one-region-hint bug for pre-existing caches.
  • Marked full-catalog wins and held incumbents, never no-hint entries — writeCache writes fullCatalog: true on the selected-region branch (both a fresh full-catalog win and a held incumbent) and never on the region: null branch. The invariant chains by induction: fullCatalog: true ⟺ won against a full catalog, or held from a region that did.
  • Added two regression tests — does not hold an incumbent an older build cached without the full-catalog marker (fails on pre-fix code) and marks a hint earned against a full catalog, and never a no-hint entry.

The change is client-side only (no wire or shared-type impact); production logic is sound.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment on lines +452 to +459
const lone = sampledProbe({ [ASIA]: [90, 30, 32, 34] })
await new RelayRegionPreferenceResolver({
directorUrl: DIRECTOR,
userDataPath: userDataPath(),
fetch: catalogFetch([{ region: 'asia-east2', probeOrigins: [ASIA] }]),
probe: lone.probe,
now: () => 1_000
}).resolve()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second half of this test resolves a lone-region catalog against a fresh userDataPath() and never reads the resulting cache, so the "never a no-hint entry" promise in the test name is unasserted: it would still pass if writeCache ever leaked fullCatalog: true onto the region: null branch. Capture the second path and assert the no-hint cache omits fullCatalog.

Suggested change
const lone = sampledProbe({ [ASIA]: [90, 30, 32, 34] })
await new RelayRegionPreferenceResolver({
directorUrl: DIRECTOR,
userDataPath: userDataPath(),
fetch: catalogFetch([{ region: 'asia-east2', probeOrigins: [ASIA] }]),
probe: lone.probe,
now: () => 1_000
}).resolve()
const lonePath = userDataPath()
const lone = sampledProbe({ [ASIA]: [90, 30, 32, 34] })
await new RelayRegionPreferenceResolver({
directorUrl: DIRECTOR,
userDataPath: lonePath,
fetch: catalogFetch([{ region: 'asia-east2', probeOrigins: [ASIA] }]),
probe: lone.probe,
now: () => 1_000
}).resolve()
expect(JSON.parse(readFileSync(cachePath(lonePath), 'utf8'))).toEqual({
v: 1,
directorUrl: DIRECTOR,
region: null,
expiresAt: 3_601_000
})

…read before a self-heal delete

- a held incumbent is written without the fullCatalog marker, so the next expiry must
  re-earn it against a full catalog; holds cannot chain on partial evidence
- the hold is logged as held-previous, not measured
- self-heal rereads the cache before rmSync so a refresh that landed during its probes
  is not deleted on a stale verdict (new reason superseded-by-refresh)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta — one minor test-coverage item from the prior review remains open.

Reviewed changes — one commit (258705c) landed since the prior pullfrog review, tightening the incumbent-hold exception it approved.

  • One hold per proven hint — a held incumbent is now written without the fullCatalog marker, so a roll wave can extend a proven hint by a day, but the next expiry re-enters selectRegionMeasurement against a full catalog instead of chaining holds on partial evidence. The cannot chain holds test pins the no-marker re-earn path.
  • held-previous logging for held incumbents — relayRegionRefreshEvent takes a held flag and reports held-previous when the incumbent is kept through an incomplete catalog, preserving measured for a win against a live rival.
  • Self-heal reread before delete — invalidateIfAssignedCellIsFar re-reads the cache before rmSync and keeps it (logging superseded-by-refresh) when a concurrent refresh wrote a different region during the probes, closing a pre-existing race.

The production logic is sound and the new tests fail without their fix. The one prior inline finding — the marks a hint earned against a full catalog, and never a no-hint entry test resolves a lone-region catalog against a discarded userDataPath() and never reads the written cache, so the "never a no-hint entry" half of its name is unasserted — is unchanged by this commit and remains open.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H

Jinwoo-H commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #19349, which keeps only the one-region rule. The rest of this PR was heuristics stacked on heuristics across six review rounds; each fix invited the next. Dropped rather than merged.

@Jinwoo-H Jinwoo-H closed this Sep 7, 2026
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.

1 participant