# How `ordered_backends` Manages User Overrides in Agent Reach

> Discover how Agent Reach's ordered_backends method manages user overrides by prioritizing specified backends and ignoring invalid ones for robust configurations.

- Repository: [Pnant/Agent-Reach](https://github.com/Panniantong/Agent-Reach)
- Tags: internals
- Published: 2026-08-04

---

**The `ordered_backends` method in Agent Reach moves a user-specified backend to the front of the probe list by matching the `<channel>_backend` config key or `<CHANNEL>_BACKEND` environment variable, while ignoring invalid overrides to prevent broken configurations.**

Agent Reach is an open-source Python framework for automating social channel interactions through pluggable backends. The `ordered_backends` method, defined in the abstract `Channel` base class, enables users to override backend priority without modifying source code. This article explains exactly how the override mechanism works, with reference to the implementation in `Panniantong/Agent-Reach`.

## Where `ordered_backends` Is Defined

The method lives in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py) at lines 45–60 inside the abstract `Channel` class:

```python
def ordered_backends(self, config=None) -> List[str]:
    """Candidate backends in probe order, honoring the user override.

    The config key `<channel>_backend` (env `<CHANNEL>_BACKEND`) moves the
    named backend to the front of the list; unknown values are ignored so
    a stale override can never hide working backends.
    """
    candidates = list(self.backends)
    override = config.get(f"{self.name}_backend") if config else None
    if override:
        for i, b in enumerate(candidates):
            if b == override or b.startswith(override):
                candidates.insert(0, candidates.pop(i))
                break
    return candidates

```

Concrete channels like `TwitterChannel` inherit this behavior and call `ordered_backends` during their `check()` method to determine probe order.

## How User Overrides Work in `ordered_backends`

The override system follows a four-stage pipeline:

### 1. Baseline Ordering from Class Attribute

Each concrete channel defines `backends` as a class-level ordered list. For example, in [`agent_reach/channels/twitter.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/twitter.py):

```python
class TwitterChannel(Channel):
    name = "twitter"
    backends = ["twitter-cli", "OpenCLI", "bird CLI (legacy)"]

```

The first element is the default preferred backend.

### 2. Override Detection via Config or Environment

Users specify priority through:
- **Config key**: `"<channel>_backend"` (e.g., `"twitter_backend"`)
- **Environment variable**: `<CHANNEL>_BACKEND` (e.g., `TWITTER_BACKEND`)

The `agent_reach.config` module merges environment variables into the config dictionary before `ordered_backends` receives it.

### 3. Prefix-Aware Reordering

The method performs an **in-place promotion** when it finds a match:

- Exact match: `b == override`
- Prefix match: `b.startswith(override)`

The matched backend is **removed from its current position** and **inserted at index 0**. The loop breaks after the first match, ensuring only one backend is promoted.

### 4. Safety Guard for Invalid Overrides

If no backend matches the override string, the method returns the original `candidates` list unchanged. This prevents stale or misspelled overrides from rendering the channel non-functional.

## Practical `ordered_backends` Examples

```python
from agent_reach.channels.twitter import TwitterChannel

# Default probe order without override

chan = TwitterChannel()
print(chan.ordered_backends())

```

Output:

```python
['twitter-cli', 'OpenCLI', 'bird CLI (legacy)']

```

### Example: Short-Form Override

```python

# "bird" matches "bird CLI (legacy)" via startswith()

cfg = {"twitter_backend": "bird"}
print(chan.ordered_backends(cfg))

```

Output:

```python
['bird CLI (legacy)', 'twitter-cli', 'OpenCLI']

```

### Example: Full-Name Override

```python
cfg = {"twitter_backend": "bird CLI (legacy)"}
print(chan.ordered_backends(cfg))

```

Output:

```python
['bird CLI (legacy)', 'twitter-cli', 'OpenCLI']

```

### Example: Invalid Override Is Ignored

```python
cfg = {"twitter_backend": "nonexistent"}
print(chan.ordered_backends(cfg))

```

Output:

```python
['twitter-cli', 'OpenCLI', 'bird CLI (legacy)']

```

## Integration with Channel Health Checks

Downstream code consumes `ordered_backends` during capability detection. In `TwitterChannel.check()` and similar methods:

```python
def check(self, config=None):
    for backend in self.ordered_backends(config):
        if self._probe_backend(backend):
            return backend
    raise BackendUnavailable(f"No working backend for {self.name}")

```

The user-override backend is always tried first, with automatic fallback to remaining candidates if unavailable.

## Key Files in Agent Reach

| File | Purpose |
|------|---------|
| [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py) | Defines `Channel` abstract base class and `ordered_backends` implementation |
| [`agent_reach/channels/twitter.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/twitter.py) | Concrete channel demonstrating `backends` class attribute |
| [`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py) | Merges environment variables into config dictionary |
| [`tests/test_channel_contracts.py`](https://github.com/Panniantong/Agent-Reach/blob/main/tests/test_channel_contracts.py) | Unit tests verifying override behavior and backend preservation |

## Summary

- **`ordered_backends`** is defined in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py) (lines 45–60) inside the `Channel` class
- Users override via `<channel>_backend` config key or `<CHANNEL>_BACKEND` environment variable
- The method supports **exact or prefix matching** to identify the target backend
- Invalid overrides are **silently ignored**, preserving safe fallback behavior
- The promoted backend is moved to **index 0** via `insert(0, pop(i))` with `O(n)` complexity

## Frequently Asked Questions

### What happens if I specify a backend that doesn't exist?

The override is ignored and the original ordering is returned. This safety mechanism prevents configuration errors from breaking channel functionality.

### Can I use partial names to specify a backend?

Yes. The `startswith()` check allows short forms like `"bird"` to match `"bird CLI (legacy)"`, making overrides more convenient to type.

### Does `ordered_backends` modify the original `backends` list?

No. The method creates `candidates = list(self.backends)` to operate on a copy, leaving the class attribute unchanged.

### How do environment variables get converted to config keys?

The `agent_reach.config` module normalizes environment variables like `TWITTER_BACKEND=bird` into `{"twitter_backend": "bird"}` before passing to `ordered_backends`.