Skip to content

feat(tes/routing/distance): add distance routing - #13

Merged
uniqueg merged 16 commits into
devfrom
feat/distance-routing
Oct 28, 2026
Merged

uniqueg merged 16 commits into
devfrom
feat/distance-routing

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the plugin tes.routing.distance (distribution foca-plugin-tes-routing-distance), the successor of proTES's distance-based task distribution (elixir-cloud-aai/protes#130).

How it routes:

  • It ranks the candidate backends by the summed great-circle distance to the locations of a task's input URLs, closest first.
  • Ties keep their order. Backends without a location follow, in their order.
  • It raises NotApplicable (so the step's next alternative, e.g. generic.routing.random, routes) if:
    • the task has no input URLs,
    • none of its inputs can be located, or
    • none of the candidates can be located.

Where locations come from:

  • The backend list (Backend.location), when configured.
  • Otherwise, the first public address of a host. Private and in-cluster addresses are never looked up. Providers:
    • offline (default): a local GeoIP database in MaxMind DB format. DB-IP's "IP to City Lite" (CC BY 4.0) is recommended, with attribution in the README and the module docstring. The README describes a derived-image download step. No database file is committed; the path is configurable.
    • dbip (an explicit opt-in): DB-IP's free API, then Nominatim, through ctx.http.
      • Both declared in data_transfers.
      • Places and coordinates cached; Nominatim at 1 request per second, without waiting beyond the deadline.
      • Back-off after DB-IP refuses lookups; a budget of lookups per call.

Bounds and caches:

  • Name resolution: all names of a call are resolved in parallel, within resolve_timeout (2 s). Thread pools per process are bounded, with separate pools for inputs and backends, and a per-call share of the input pool. Results are cached, failures included.
  • Lookups are cached per process with TTLs (locations, misses, failures). FOCA 0.18 gives plugins no database, so a shared cache is a follow-up.
  • Annotations hold counts only.

Other:

  • Capability routing-by-data-locality.
  • Generic defaults (nothing ECP-specific).
  • New dependencies:
    • maxminddb (Apache-2.0), for the plugin;
    • mmdb-writer (MIT) and netaddr (BSD), in the dev group only, to build test fixtures.

Stacked on #11 and #12: this branch contains their commits. The PR targets dev so that CI runs. Merge #11, then #12, then this one; the diff then shrinks to the distance-routing commits.

Closes #8

Verification

  • pytest plugins/tes/routing/distance: 128 passed (several runs, stable). Coverage of the plugin is 100% (line and branch).
  • pytest tests: 74 passed. python -m scripts.checks check: OK.
  • pre-commit run --all-files: all hooks pass (ruff, ruff format, mypy, ast-grep, semgrep and the repo's checks).
  • mkdocs build --strict: builds.
  • The plugin tests pass on Python 3.11 with the locked environment, and with FOCA dev.
  • The wheel contains only foca_plugins/tes/routing/distance/* and py.typed; no namespace __init__.py.
  • The plugin tests use FOCA's test kit: the contract checks, PluginHarness with FakeHttp, and a PluginHost loading the plugin through its entry point.
  • Review: adversarial and quality reviewers, two rounds.
    • Round 1 (high): slow-DNS hosts could tie up FOCA's plugin workers.
    • Round 1 (mediums): uncapped resolver threads; DB-IP quota use; a throttle that slept under its lock; missing plugin-level tests.
    • Round 2 (mediums): turns spent without a Nominatim request; concurrent callers missing a running resolution; input names starving backends; brittle tests.
    • All high and medium findings are fixed, along with most lows.
  • CodeQL flagged a substring check in a test ("incomplete URL substring sanitization", a false positive); the test now compares the recipients exactly (25e3e38).
  • Sourcery: 11 threads. 9 fixed in 13bf1c4: turn booking before DB-IP, with give-back; time split between input and backend names; bucket URLs not located; distances per host; failures don't replace concurrent locations; waiters woken when no thread starts; dbip closed state; dbip miss TTL; float overflow. 2 answered (see below). All resolved; the Sourcery check passes.
  • CI: all checks pass on 13bf1c4 (Lint, Docs, Test scripts, Test matrix for all plugins on Python 3.11, 3.13 and 3.15 with FOCA 0.18.0 and dev, CodeQL, Codecov, CI passed).

Declined review findings

  • Coalescing concurrent provider lookups of the same address at cold start. The caches, the per-call budgets and the back-off bound the cost; coalescing adds complexity for a short window.
  • A per-principal rate limit for dbip lookups. A user who submits many tasks with fresh public addresses can still use up DB-IP's free quota. The README documents this as a limit of the opt-in provider (distance routing then doesn't apply until the quota resets) and recommends offline.
  • Sourcery: serializing Nominatim requests under the lock. Turns are booked an interval apart; only scheduling jitter (milliseconds) can bring two requests closer. Holding the lock during the wait or the request blocked all other lookups.
  • Sourcery: stopping the resolver threads of an earlier setup(). FOCA 0.18 runs setup() once per instance, and getaddrinfo can't be interrupted; the threads are daemon threads, bounded by their resolver.
  • Computing url_host() once per URL instead of twice. It is cheap, and the duplication is local.

Follow-ups (not in this PR)

  • FOCA's docs have no capability vocabulary yet; routing-by-data-locality should be listed there (as decided, the vocabulary lives in FOCA's docs).
  • A cache shared between processes needs plugin storage in FOCA.
  • proTES#130 can be closed with a pointer to this plugin once it is released.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Add distance-based TES routing that orders candidate backends by geographic proximity to task input data.

New Features:

  • Add the tes.routing.distance plugin to route TES tasks toward backends closest to their input data.
  • Support offline GeoIP resolution by default and opt-in DB-IP/Nominatim location lookups with transfer disclosures and configurable limits.

Enhancements:

  • Bound hostname resolution and provider work with deadlines, thread limits, caching, rate limiting, and fallback behavior for unavailable locations.
  • Expose data-locality routing metadata, installation configuration, changelog, licensing, and package documentation.

Build:

  • Add the standalone foca-plugin-tes-routing-distance package and its GeoIP and test-fixture dependencies.

Documentation:

  • Document routing behavior, privacy and data transfers, provider configuration, GeoIP database setup, and operational limits.

Tests:

  • Add comprehensive unit, integration, contract, provider, resolver, cache, and entry-point coverage for the distance-routing plugin.

uniqueg and others added 13 commits October 27, 2026 11:31
FOCA 0.18.0, with the plugin engine and its test kit, is on PyPI.
Remove the Git source of FOCA, require foca>=0.18.0,<0.19 in the
example plugin and the meta distribution, and re-lock. CI tests
FOCA 0.18.0 and dev; Dependabot updates FOCA again. The template's
tests use FOCA's test kit (contract checks, harness), so new
plugins inherit them. Docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Template tests build a new task per use instead of sharing a
mutable dict. The Codecov upload follows a coverage flag of the
matrix entry instead of a hard-coded FOCA version. Comments and
docs say how contract checks run, that both CI entries replace
the locked FOCA, and which sample inputs plugins should pass;
a stale note on the Git source of FOCA is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The template's tests build their candidate backends per use, like
their tasks, so that hooks that change their input in place can't
make comparisons pass. Rewrap a comment in release.yml; say in the
CI matrix comment which entry reports coverage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tests that check that the template's hooks keep their input pass
values of their own (a task name, backend identifiers), so that a
hook returning the builders' defaults can't pass them. The template's
comment on namespace packages no longer names its own subgroup, which
copies kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the plugin generic.routing.random, the successor of proTES's
random task distribution: its route step returns all candidate
backends shuffled with random.SystemRandom. A seed gives
reproducible orders for tests, refused unless the admin setting
allow_seed is on. Records the number of candidates and whether a
seed was used; the order itself is in FOCA's route provenance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Accept only integer seeds, name the Python version in the promise of
reproducible orders, add a seeded example, fix the namespace comment
and list the plugin in the READMEs. Tests use their own candidates
and assert exact exception types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check that the hook returns a new list, and replace the probabilistic
check of unseeded orders with one on a fixed entropy stream (review
by Sourcery).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the plugin tes.routing.distance, the successor of proTES's
distance-based task distribution: its route step ranks the candidate
backends by their summed great-circle distance to the locations of
the task's inputs; unlocated backends follow, none is dropped. It
does not apply without inputs or backends that can be located.

Backend locations come from the backend list first. Host addresses
are looked up offline in a local GeoIP database by default (DB-IP
Lite recommended, CC BY 4.0, with attribution in the README), or via
DB-IP's free API and Nominatim as an explicit opt-in, through
ctx.http and throttled per Nominatim's policy. Lookups and misses are
cached per process with TTLs (proTES#130). Annotations hold counts
only. No database is committed; tests write their own fixture with
mmdb-writer (dev dependency).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bound name resolution: resolve all host names of a call in parallel
under one budget (resolve_timeout, now 2 s), at most resolve_threads
names at a time and each name once per process, start nothing after
the deadline, and cache resolutions (also failures) for
resolve_cache_ttl. Slow or hostile name servers can no longer tie up
FOCA's plugin workers.

Protect DB-IP's quota: cache places and coordinates, book Nominatim's
turn before asking DB-IP (and wait outside the lock), back off after a
refusal (error answer or HTTP 429), cap uncached lookups per call
(dbip_max_lookups) and cache failed lookups briefly
(cache_failure_ttl).

Also validate the user agent as a header value, keep the provider after
close() and fail its lookups, replace the assert in setup(), move the
TTL cache to its own module, add plugin-level tests (privacy, caches,
deadlines, threads), and update the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let concurrent calls wait for a running resolution of a name instead of
getting nothing, resolve backend names in threads of their own, and let
one call start at most a quarter of the input threads, so that names
chosen by clients can't hold up backends or other calls.

Book Nominatim turns only for requests to Nominatim (DB-IP is asked if
a turn is free before the deadline), mark failures for lack of time as
transient and don't cache them, and give inputs and backends a budget
of dbip_max_lookups each.

Tests: deterministic lock test, shared resolutions, per-call limits,
backend threads, turns, transient failures; TTL offsets come from the
settings. Docs: limits of the dbip provider, cache sizes, docstrings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces the TES distance-routing plugin with offline GeoIP as the default and bounded, cached optional online geolocation, adds the generic random-routing fallback, and updates packaging, documentation, tests, and CI for FOCA 0.18 compatibility.

Sequence diagram for TES distance-based routing

sequenceDiagram
    participant Gateway
    participant Distance
    participant Resolver
    participant Provider
    participant BackendList

    Gateway->>Distance: on_route(candidates, ctx)
    Distance->>Distance: input_urls(ctx.original)
    Distance->>Resolver: resolve(input and backend hosts, deadline)
    Resolver-->>Distance: public addresses
    Distance->>Provider: locate(public address, ctx)
    Provider-->>Distance: input and backend locations
    Distance->>BackendList: read Backend.location
    BackendList-->>Distance: configured locations
    Distance->>Distance: distance_km and stable sort
    Distance-->>Gateway: ranked candidates

    alt no input URLs or no located inputs or no located backends
        Distance-->>Gateway: NotApplicable
        Gateway->>Gateway: try next alternative
    end
Loading

Flow diagram for distance routing fallback

flowchart TD
    Start[Route TES task] --> Inputs{Input URLs available?}
    Inputs -- No --> NA[Raise NotApplicable]
    Inputs -- Yes --> LocateInputs[Locate input hosts]
    LocateInputs --> InputLocations{Any inputs located?}
    InputLocations -- No --> NA
    InputLocations -- Yes --> LocateBackends[Use Backend.location or locate backend hosts]
    LocateBackends --> BackendLocations{Any candidates located?}
    BackendLocations -- No --> NA
    BackendLocations -- Yes --> Sort[Stable sort by summed great-circle distance]
    Sort --> Result[Return located candidates first\nthen unlocated candidates]
    NA --> Fallback[Next route alternative\nfor example generic.routing.random]
Loading

File-Level Changes

Change Details Files
Add the tes.routing.distance plugin and package it as a standalone FOCA TES routing distribution.
  • Register the plugin entry point and expose typed package metadata.
  • Declare FOCA, MaxMind DB, and development fixture dependencies with Python 3.11+ support.
  • Document installation, configuration, capabilities, data-transfer behavior, licensing attribution, and changelog information.
plugins/tes/routing/distance/pyproject.toml
plugins/tes/routing/distance/README.md
plugins/tes/routing/distance/CHANGELOG.md
plugins/tes/routing/distance/LICENSE
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/py.typed
plugins/tes/README.md
pyproject.toml
uv.lock
Implement distance-based routing using input and backend geographic locations, with stable fallback behavior.
  • Extract and deduplicate TES input URLs, resolve hostnames, ignore private or in-cluster addresses, and select public addresses.
  • Prefer configured backend locations, otherwise locate backend hosts through the configured provider.
  • Rank located candidates by summed great-circle distance while preserving tie and unlocated-backend order.
  • Raise NotApplicable when input URLs or usable input/backend locations are unavailable, allowing pipeline alternatives to run.
  • Record aggregate routing annotations without exposing addresses or places.
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/geo.py
Add offline and opt-in online location providers with validation, guarded transfers, rate limits, and failure handling.
  • Read MaxMind DB/GeoIP2-style coordinates from a locally configured database by default.
  • Support DB-IP followed by Nominatim through ctx.http when explicitly enabled, including HTTPS validation, user-agent handling, provider data-transfer metadata, and coordinate validation.
  • Enforce lookup budgets, Nominatim throttling, DB-IP back-off, deadline checks, and transient versus cacheable failures.
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py
Bound resolver and lookup resource usage and add process-local caching for concurrent routing calls.
  • Use separate bounded resolver pools for input and backend names with per-call input sharing and coalesced in-flight resolutions.
  • Cache successful resolutions, misses, failures, and provider results with configurable TTLs and LRU size limits.
  • Ensure provider setup and shutdown are idempotent and safely handle lookups after closure.
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/geo.py
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/cache.py
plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py
Add the generic random routing successor and use it as the documented routing fallback.
  • Shuffle all candidate backends using system randomness, with optional admin-gated deterministic seeds for tests.
  • Preserve all candidates, record only candidate-count and seed-use annotations, and expose route metadata through FOCA provenance.
  • Add package documentation, changelog, entry point, typed package data, and comprehensive contract, harness, and pipeline tests.
plugins/generic/routing/random/pyproject.toml
plugins/generic/routing/random/README.md
plugins/generic/routing/random/CHANGELOG.md
plugins/generic/routing/random/LICENSE
plugins/generic/routing/random/src/foca_plugins/generic/routing/random/__init__.py
plugins/generic/routing/random/src/foca_plugins/generic/routing/random/py.typed
plugins/generic/routing/random/tests/test_random.py
plugins/generic/README.md
Update the repository and CI to target released FOCA 0.18 and validate plugins across supported FOCA and Python versions.
  • Remove the temporary FOCA Git source and update plugin/meta dependency bounds and documentation.
  • Test affected packages against FOCA 0.18.0 and dev, with coverage reported only by the designated matrix entry.
  • Adopt FOCA plugin contract checks and test-kit guidance in CI and contributor documentation.
  • Add the distance fixture tooling to the development environment and update maintenance guidance.
.github/dependabot.yml
.github/workflows/ci.yml
.github/workflows/release.yml
MAINTAINERS.md
README.md
docs/contributing.md
docs/writing-plugins.md
meta/pyproject.toml
plugins/generic/example/noop/README.md
plugins/generic/example/noop/pyproject.toml
plugins/generic/example/noop/tests/test_noop.py
pyproject.toml
uv.lock

Assessment against linked issues

Issue Objective Addressed Explanation
#8 Provide an opt-in TES distance-routing plugin that ranks all candidate backends by summed great-circle distance to task input locations, preserves order for ties and unlocated candidates, and declines applicability when inputs or candidates cannot be located. ✅
#8 Support backend-configured locations and public-host resolution with an offline GeoIP provider by default, with explicit online DB-IP/Nominatim lookup, bounded network and resolution behavior, and per-process caches. ✅
#8 Meet the issue's privacy, metadata, documentation, and verification requirements, including count-only annotations, declared data transfers and locality capability, offline tests, mocked online tests, cache/applicability coverage, and complete coverage. ✅

Possibly linked issues

  • feat(tes/routing/distance): add distance routing #8: The PR implements the issue’s distance-routing plugin, including offline-by-default geolocation, opt-in online lookups, caching, and fallback behavior.
  • #unknown: The stacked PR includes the random router implementation matching this issue; its distance-routing work is separate.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (bd81028) to head (3f715a2).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev       #13    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files            2         6     +4     
  Lines           66       551   +485     
  Branches         6        71    +65     
==========================================
+ Hits            66       551   +485     
Flag Coverage Δ
foca-plugin-generic-example-noop 100.00% <ø> (ø)
foca-plugin-generic-routing-random 100.00% <ø> (ø)
foca-plugin-tes-routing-distance 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Compare the recipients of the data transfers instead of searching
substrings, which CodeQL flags as incomplete URL sanitization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 27, 2026 20:42

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 11 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py" line_range="258" />
<code_context>
+        if not cached:
+            if self._clock() < self._blocked_until:
+                raise LookupFailed("DB-IP refused lookups recently; backing off")
+            self._check_turn(ctx)
+            place = self._place(http, address)
+            self._places.put(address, place, self.cache_ttl)
</code_context>
<issue_to_address>
**DB-IP quota is spent on failed lookups**

When concurrent uncached lookups need more Nominatim turns than fit within their deadlines, `_check_turn` only observes `_next`, so `DbipProvider.locate` calls `_place` and spends DB-IP quota before `_book` reserves a Nominatim turn; calls whose turns miss their deadlines then fail without locating an address.

Reserve and validate each Nominatim turn before calling `_place`.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:270`, `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:386-389`.
</issue_to_address>

### Comment 2
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py" line_range="373" />
<code_context>
+            ),
+        )
+        hosts = list(dict.fromkeys(host for url in urls if (host := url_host(url))))
+        locator.locate(hosts[: settings.max_hosts], self.input_resolver)
+        inputs = [
+            location
</code_context>
<issue_to_address>
**Backend DNS lookups lose their deadline**

When input hostname resolution is slow and candidate backends need DNS resolution, `on_route` waits for input resolution using the shared deadline before calling `backend_resolver.resolve`; `Resolver.resolve` then skips backend hostname lookups, so routing falls through despite having located inputs.

Ensure input and backend resolution share the available time without letting input resolution consume the entire backend resolution budget.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:367`, `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:385`, `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:392`.
</issue_to_address>

### Comment 3
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py" line_range="270" />
<code_context>
+        for query in queries:
+            cached, location = self._searches.get(query)
+            if not cached:
+                self._wait(self._book(ctx))
+                location = self._search(http, query)
+                self._searches.put(query, location, self.cache_ttl)
</code_context>
<issue_to_address>
**Nominatim requests violate the interval**

When a caller is delayed after booking a turn while another concurrent lookup reaches its turn, `_book` schedules turns, but `_wait` releases that ordering before the HTTP request; the later caller can send first and the delayed caller can send immediately after, violating the configured Nominatim interval.

Serialize turn waiting and request dispatch so requests are sent in booked order at the configured interval.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:391-421`.
</issue_to_address>

### Comment 4
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py" line_range="100" />
<code_context>
+        if isinstance(value, bool) or not isinstance(value, int | float | str):
+            return None
+        try:
+            number = float(value)
+        except ValueError:
+            return None
</code_context>
<issue_to_address>
**Large coordinates fail the route**

When a provider returns an integer coordinate too large to convert to a float, `coordinates` calls `float(value)` and catches only `ValueError`; the resulting `OverflowError` escapes the provider and routing hook, failing the route instead of treating the location as invalid and allowing fallback.

Catch `OverflowError` alongside `ValueError` in `coordinates`.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:101`.
</issue_to_address>

### Comment 5
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py" line_range="243-251" />
<code_context>
+        self.batch_lookups += 1
+        try:
+            location = self.provider.locate(address, self.ctx)
+        except LookupFailed as exc:
+            self.failed_lookups += 1
+            self.ctx.log.warning("Lookup failed: %s", exc)
+            if not exc.transient:
+                self.cache.put(address, None, self.settings.cache_failure_ttl)
+            return None
+        settings = self.settings
+        ttl = settings.cache_miss_ttl if location is None else settings.cache_ttl
+        self.cache.put(address, location, ttl)
+        return location
+
</code_context>
<issue_to_address>
**Failed lookup erases location**

When two cold lookups for the same address overlap, one succeeds first, and the other later gets a non-transient provider error, `_Locator._lookup` writes `None` with `cache_failure_ttl` over the successful location; subsequent requests treat that address as unlocated until expiry and fall back instead of distance routing.

Avoid replacing a valid cached location with a later failure result, using an atomic conditional update or coalescing concurrent lookups.
</issue_to_address>

### Comment 6
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/geo.py" line_range="80" />
<code_context>
+        invalid.
+    """
+    try:
+        host = urlsplit(url).hostname
+    except ValueError:
+        return None
</code_context>
<issue_to_address>
**Bucket DNS misroutes storage inputs**

When an input uses an S3-style bucket URI whose bucket name resolves to a public DNS address, `url_host` treats the URI authority as a DNS hostname, and `_Locator` can use the bucket's public address as the input location; routing then ranks backends by the bucket's DNS target rather than the data location.

Do not use bucket URI authorities as DNS locations for input data.
</issue_to_address>

### Comment 7
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py" line_range="398" />
<code_context>
+                if location is None:
+                    unlocated.append(backend)
+                else:
+                    total = sum(distance_km(location, i) for i in inputs)
+                    ranked.append((total, backend))
+        ctx.record("inputs", len(urls))
</code_context>
<issue_to_address>
**Many inputs exhaust routing workers**

When a TES task contains many distinct input URLs, including many URLs on the same host, `input_urls` retains every distinct URL, and `on_route` builds locations and calculates distances for each URL against each located candidate; `max_hosts` only caps host lookups, so routing work and memory grow with the input URLs and candidates.

Bound the input URLs used to build locations and calculate backend distances.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/geo.py:65`.
</issue_to_address>

### Comment 8
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py" line_range="325" />
<code_context>
+                cache_ttl=config.cache_ttl,
+            )
+        self.cache = TtlCache(config.cache_size)
+        self.input_resolver = Resolver(
+            config.resolve_threads,
+            config.resolve_cache_ttl,
</code_context>
<issue_to_address>
**Repeated setup leaks resolver threads**

When the plugin is set up again while DNS lookups from an earlier setup remain blocked, `setup` replaces both resolver instances without stopping their in-flight daemon threads; those threads retain the old resolvers and their per-instance limits, so repeated setup accumulates resolver threads beyond the configured bounds.

Stop or otherwise clean up the existing resolver instances before replacing them in `setup`.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:331-333`.
</issue_to_address>

### Comment 9
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/geo.py" line_range="241-242" />
<code_context>
+                target=self._run, args=(job,), name="distance-resolve", daemon=True
+            ).start()
+        except RuntimeError:  # no more threads
+            self._release(host)
+            return None, False
+        return job, True
+
</code_context>
<issue_to_address>
**Resolver waiters never wake**

When `Thread.start()` raises `RuntimeError` while another caller has already retrieved the published job, the startup caller removes the job after `Thread.start()` raises, but never sets `job.done`; callers that already obtained that job keep waiting until their deadlines, then proceed without its resolution even if a later retry resolves the host.

Set the failed job's event before releasing it so all callers waiting on that job wake immediately.
</issue_to_address>

### Comment 10
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py" line_range="278" />
<code_context>
+        return None
+
+    def close(self) -> None:
+        """Release resources (none)."""
+
+    def _place(self, http: GuardedClient, address: str) -> Place | None:
</code_context>
<issue_to_address>
**Online lookups continue after close**

When the plugin uses `provider: dbip` and a route hook performs an uncached lookup after close, `DbipProvider.close()` does nothing, and `locate()` has no closed-state guard; an uncached route lookup after `Distance.close()` can still send requests to DB-IP and Nominatim instead of failing as `Distance.close()` promises.

Track the online provider's closed state and reject lookups after close.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:336`.
</issue_to_address>

### Comment 11
<location path="plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py" line_range="260" />
<code_context>
+                raise LookupFailed("DB-IP refused lookups recently; backing off")
+            self._check_turn(ctx)
+            place = self._place(http, address)
+            self._places.put(address, place, self.cache_ttl)
+        if place is None:
+            return None
</code_context>
<issue_to_address>
**Configured miss TTL is bypassed**

When `provider: dbip` returns `None` and `cache_miss_ttl` is shorter than `cache_ttl`, when the online provider returns no place or coordinates, `DbipProvider` caches `None` for `cache_ttl` (default one day), so an expired outer miss still gets the cached negative result instead of retrying the lookup. Callers see misses persist longer than the configured `cache_miss_ttl`.

Use the miss TTL for negative entries in the provider caches, or avoid retaining negative results there beyond the address miss TTL.

Also at `plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:272`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 11 findings to address first, and when an administrator opts into the DB-IP provider, the plugin sends public IP addresses derived from task input hosts to DB-IP and their inferred places to Nominatim; reverting stops future lookups but cannot retract data already disclosed. The default provider is offline, but the new runtime dependency is maxminddb.

Blocking findings: plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:258, plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:373, plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:270, plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/providers.py:100, plugins/tes/routing/distance/src/foca_plugins/tes/routing/distance/__init__.py:251, and 6 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

uniqueg and others added 2 commits October 27, 2026 21:52
- Book Nominatim's turn before asking DB-IP and give it back if unused,
  so that DB-IP's quota isn't spent on lookups that then run out of time.
- Give names of inputs half of resolve_timeout and backends the rest.
- Locate only hosts of http(s), ftp(s) and sftp URLs, not bucket names.
- Weigh distances per input host instead of per URL.
- Keep a location found by a concurrent call when a lookup fails.
- Wake callers that share a resolution whose thread didn't start.
- Fail dbip lookups after close(), and keep dbip misses for the miss TTL.
- Treat coordinates too large for a float as invalid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 319b7a1 into dev Oct 28, 2026
35 checks passed
@uniqueg
uniqueg deleted the feat/distance-routing branch October 28, 2026 00:38
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.

feat(tes/routing/distance): add distance routing

2 participants