Repository navigation
feat(tes/routing/distance): add distance routing - #13
Conversation
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces 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 routingsequenceDiagram
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
Flow diagram for distance routing fallbackflowchart 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]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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]>
There was a problem hiding this comment.
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
- 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]>
# Conflicts: # README.md # uv.lock
Summary
Adds the plugin
tes.routing.distance(distributionfoca-plugin-tes-routing-distance), the successor of proTES's distance-based task distribution (elixir-cloud-aai/protes#130).How it routes:
NotApplicable(so the step's next alternative, e.g.generic.routing.random, routes) if:Where locations come from:
Backend.location), when configured.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, throughctx.http.data_transfers.Bounds and caches:
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.Other:
routing-by-data-locality.maxminddb(Apache-2.0), for the plugin;mmdb-writer(MIT) andnetaddr(BSD), in the dev group only, to build test fixtures.Stacked on #11 and #12: this branch contains their commits. The PR targets
devso 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.dev.foca_plugins/tes/routing/distance/*andpy.typed; no namespace__init__.py.PluginHarnesswithFakeHttp, and aPluginHostloading the plugin through its entry point.Declined review findings
dbiplookups. 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 recommendsoffline.setup(). FOCA 0.18 runssetup()once per instance, andgetaddrinfocan't be interrupted; the threads are daemon threads, bounded by their resolver.url_host()once per URL instead of twice. It is cheap, and the duplication is local.Follow-ups (not in this PR)
routing-by-data-localityshould be listed there (as decided, the vocabulary lives in FOCA's docs).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:
tes.routing.distanceplugin to route TES tasks toward backends closest to their input data.Enhancements:
Build:
foca-plugin-tes-routing-distancepackage and its GeoIP and test-fixture dependencies.Documentation:
Tests: