Skip to content

feat(generic/routing/random): add random routing - #12

Merged
uniqueg merged 10 commits into
devfrom
feat/random-routing
Oct 28, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/random-routing

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the plugin generic.routing.random (distribution foca-plugin-generic-routing-random), the successor of proTES's random task distribution:

  • route returns all candidate backends shuffled with random.SystemRandom. It never drops or adds candidates and never raises NotApplicable.
  • Annotations: candidates (count) and seeded.
  • Optional params.seed (strict integer), for reproducible orders in tests. It is refused when pipelines are resolved unless the admin sets config.allow_seed (default off), because seeded orders are predictable.
  • The README covers configuration, a seeded test setup and proTES's old default pipeline (distance routing, falling back to random).
  • The root and group READMEs list the plugin.
  • A CHANGELOG entry.

Stacked on #11: this branch contains the commits of #11 (FOCA 0.18.0 from PyPI). The PR targets dev so that CI runs. Merge #11 first; after that, this PR's diff shrinks to the plugin commits.

Closes #7

Verification

  • pytest plugins/generic/routing/random: 24 passed. Coverage of the plugin is 100% (line and branch).
  • pytest tests: 74 passed.
  • pre-commit run --all-files: all hooks pass (ruff, ruff format, mypy, ast-grep, semgrep and the repo's checks).
  • python -m scripts.packages mypy plugins/generic/routing/random: clean.
  • mkdocs build --strict: builds.
  • Contract checks: check_plugin_contract passes, both unseeded and seeded. PluginHarness and a PluginHost load the plugin through its installed entry point.
  • Review: adversarial and quality reviewers, two rounds. Round 1 had a medium (a stale namespace comment) and lows, all fixed. Round 2 found no high or medium findings; its lows (changelog wrapping) are fixed.
  • Sourcery: 2 threads (a permutation test that accepted tuples; a probabilistic test), both fixed in 8c76cdf, replied to and resolved; Sourcery approved.
  • CI: all checks pass on 8c76cdf (Lint, Docs, Test scripts, Test matrix for both plugins on Python 3.11, 3.13 and 3.15 with FOCA 0.18.0 and dev, CodeQL, Codecov, CI passed).

Declined review findings

  • An extra engine test for a seed in an inline client pipeline while allow_seed is off. FOCA itself enforces this (resolve_steps runs check_params for client pipelines). The plugin's check_params is tested directly and through host construction.
  • Documenting that random.Random seeds with the absolute value of the integer (seed: -1 and seed: 1 give the same order). The docs only promise that the order is a function of the seed.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Add a generic random-routing plugin that preserves every candidate while providing secure default shuffling and opt-in predictable ordering for tests.

New Features:

  • Add the experimental generic.routing.random plugin, which routes all candidate backends in random order and supports optional reproducible seeded orders for testing.

Enhancements:

  • Record routing annotations indicating the candidate count and whether seeded ordering was used.
  • Document plugin configuration, installation, testing, and migration from proTES's random task distribution.

Build:

  • Add packaging metadata, dependencies, entry-point registration, licensing, and lockfile updates for the new plugin distribution.

Documentation:

  • List the new routing plugin in repository and generic plugin documentation and add its changelog.

Tests:

  • Add comprehensive unit, contract, engine, entry-point, validation, and seeded/unseeded routing tests.

Chores:

  • Update repository contribution links and references.

uniqueg and others added 7 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]>
@sourcery-ai

sourcery-ai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a packaged random-routing plugin with secure unseeded behavior, explicitly authorized deterministic test seeding, comprehensive FOCA contract and integration coverage, and repository-wide adoption of the released FOCA 0.18 plugin API and compatibility matrix.

Sequence diagram for random backend routing

sequenceDiagram
    participant Gateway
    participant Random
    participant SystemRandom
    participant Backends
    Gateway->>Random: on_route(candidates, ctx)
    Random->>SystemRandom: shuffle(candidates)
    SystemRandom-->>Random: shuffled candidates
    Random->>Random: record(candidates, seeded)
    Random-->>Gateway: all candidates in random order
Loading

Sequence diagram for authorized seeded routing

sequenceDiagram
    participant Pipeline
    participant Random
    participant RandomParams
    participant SeededRandom
    Pipeline->>RandomParams: validate seed
    Pipeline->>Random: check_params(params)
    alt seed set and allow_seed is false
        Random-->>Pipeline: InvalidParams
    else seed allowed or absent
        Pipeline->>Random: on_route(candidates, ctx)
        Random->>SeededRandom: shuffle(candidates)
        SeededRandom-->>Random: reproducible order
        Random-->>Pipeline: all candidates in shuffled order
    end
Loading

File-Level Changes

Change Details Files
Add the generic.routing.random plugin and package it as foca-plugin-generic-routing-random.
  • Shuffle all route candidates with SystemRandom when unseeded and Random when a test seed is provided.
  • Preserve every candidate, return a new list, and record candidates and seeded annotations.
  • Validate strict integer seeds and reject seeded pipeline parameters unless admin allow_seed is enabled.
  • Register the plugin entry point and include package metadata, typed package data, license, README, and changelog.
plugins/generic/routing/random/pyproject.toml
plugins/generic/routing/random/src/foca_plugins/generic/routing/random/__init__.py
plugins/generic/routing/random/LICENSE
plugins/generic/routing/random/README.md
plugins/generic/routing/random/CHANGELOG.md
Expand plugin verification using FOCA 0.18's plugin testing APIs.
  • Add unit coverage for permutation behavior, randomness source, reproducibility, annotations, validation, and edge cases.
  • Add contract, harness, installed entry-point, and pipeline tests, including seed authorization.
  • Migrate the example plugin tests to FOCA's contract checks and PluginHarness utilities.
plugins/generic/routing/random/tests/test_random.py
plugins/generic/example/noop/tests/test_noop.py
Adopt the released FOCA 0.18 plugin API and update compatibility and dependency management.
  • Replace the FOCA development Git source with foca>=0.18.0,<0.19 dependencies and update the lockfile.
  • Update maintainer, contributing, plugin-writing, and example-plugin guidance for released FOCA 0.18 and future minor releases.
  • Remove obsolete pre-release dependency notes and Dependabot exclusions.
pyproject.toml
uv.lock
meta/pyproject.toml
plugins/generic/example/noop/pyproject.toml
MAINTAINERS.md
.github/dependabot.yml
docs/contributing.md
docs/writing-plugins.md
README.md
plugins/generic/example/noop/README.md
Extend CI and release configuration for stable and development FOCA compatibility.
  • Test affected plugins on FOCA 0.18.0 and dev across the supported Python matrix.
  • Limit coverage upload to the designated stable matrix entry and rely on plugin tests for contract checks.
  • Update release comments and workflow metadata for the published FOCA dependency.
.github/workflows/ci.yml
.github/workflows/release.yml
Document and expose the new routing plugin throughout the repository.
  • List the plugin in root and generic group documentation.
  • Document configuration, seeded test usage, security rationale, installation, and the former proTES fallback pipeline.
  • Add an unreleased feature changelog entry.
README.md
plugins/generic/README.md
plugins/generic/routing/random/README.md
plugins/generic/routing/random/CHANGELOG.md

Assessment against linked issues

Issue Objective Addressed Explanation
#7 Add a generic.routing.random FOCA plugin that supports all APIs and only routes candidates, returning every input candidate exactly once in shuffled order using system randomness when unseeded. ✅
#7 Support reproducible seeded routing for tests while rejecting seeds unless the administrator enables allow_seed; validate seed values strictly. ✅
#7 Record routing metadata without duplicating the candidate order, and document the plugin and the pipeline that restores proTES's former distance-first, random-fallback behavior. ✅

Possibly linked issues

  • feat(generic/routing/random): add random routing #7: The PR implements the issue’s random routing plugin and acceptance criteria, including permutation routing, reproducible allowed seeds, contract checks, and documentation.
  • #unknown: The PR explicitly includes the issue's FOCA 0.18.0 migration, PyPI sourcing, CI matrix, Dependabot, contract checks, and documentation updates.

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 (2f79722) to head (3ba8603).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #12   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            1         2    +1     
  Lines           29        66   +37     
  Branches         3         6    +3     
=========================================
+ Hits            29        66   +37     
Flag Coverage Δ
foca-plugin-generic-example-noop 100.00% <ø> (ø)
foca-plugin-generic-routing-random 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.

@uniqueg
uniqueg marked this pull request as ready for review October 27, 2026 20:04

@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 2 issues

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

## Individual Comments

### Comment 1
<location path="plugins/generic/routing/random/tests/test_random.py" line_range="245" />
<code_context>
+        for _ in range(20)
+    }
+    # 8! orders: 20 equal draws have a probability of about 1e-88
+    assert len(orders) > 1
+
+
</code_context>
<issue_to_address>
**Correct random draws can fail**

When all 20 unseeded draws happen to produce the same permutation, when 20 correct unseeded draws happen to produce the same permutation, `test_on_route_varies_without_seed` fails at line 245 even though the implementation is correct; the test relies on an unmocked random outcome.

Replace the probabilistic assertion with a deterministic check of the unseeded randomness path.
</issue_to_address>

### Comment 2
<location path="plugins/generic/routing/random/tests/test_random.py" line_range="209" />
<code_context>
+    candidates = tuple(BACKENDS)
+    ctx = make_context()
+    result = plugin.on_route(candidates, ctx)
+    assert sorted(result, key=lambda b: b.id) == BACKENDS
+    assert candidates == tuple(BACKENDS)
+    assert ctx.annotations == {"candidates": 8, "seeded": False}
</code_context>
<issue_to_address>
**Tuple results pass permutation check**

When the route hook returns the input tuple unchanged for a multi-candidate tuple input, when `on_route` returns the input tuple unchanged for this multi-candidate input, `test_on_route_returns_permutation` sorts it at line 209 and compares only its contents, so the test passes despite the hook not returning the promised new list.

Assert that the result is a list and, using a mutable input, that it is not the input object.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: plugins/generic/routing/random/tests/test_random.py:209


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

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]>

@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.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit bd81028 into dev Oct 28, 2026
21 checks passed
@uniqueg
uniqueg deleted the feat/random-routing branch October 28, 2026 00:25
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(generic/routing/random): add random routing

1 participant