From 38a535500eb706c989a2467a34126857d99c2d94 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 7 Nov 2026 12:48:19 +0000 Subject: [PATCH 1/3] feat(ai): search the web through SearXNG --- docs/CONFIGURATION.md | 3 +- docs/ENV_VARS.md | 3 +- docs/TELEMETRY.md | 2 +- k8s/README.md | 2 +- k8s/devops/configmap.example.yaml | 5 + .../.openspec.yaml | 2 + .../3927-searxng-search-provider/design.md | 17 + .../3927-searxng-search-provider/proposal.md | 47 +++ .../specs/web-search/spec.md | 76 ++++ .../3927-searxng-search-provider/tasks.md | 29 ++ src/devops_cli/ai/web_search.py | 131 +++++- src/devops_cli/config/defaults.py | 9 +- src/devops_cli/config/settings.py | 10 +- src/devops_cli/roadmap/request_plan.py | 2 +- src/devops_cli/telemetry/instruments.py | 2 +- tests/ai/test_web_search.py | 2 +- tests/ai/test_web_search_searxng.py | 386 ++++++++++++++++++ tests/fixtures/searxng/search_reply.json | 53 +++ tests/roadmap/test_roadmap_dry_runs.py | 17 + 19 files changed, 781 insertions(+), 17 deletions(-) create mode 100644 openspec/changes/3927-searxng-search-provider/.openspec.yaml create mode 100644 openspec/changes/3927-searxng-search-provider/design.md create mode 100644 openspec/changes/3927-searxng-search-provider/proposal.md create mode 100644 openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md create mode 100644 openspec/changes/3927-searxng-search-provider/tasks.md create mode 100644 tests/ai/test_web_search_searxng.py create mode 100644 tests/fixtures/searxng/search_reply.json diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 1cc6d9a056..4ef7afd5e0 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -303,8 +303,9 @@ The providers that web search asks, in order, and the language of the search. | Option | Type | Default | Environment Variable | Description | |---|---|---|---|---| -| `providers` | `list` | `['searxng', 'duckduckgo', 'firecrawl']` | `DEVOPS_CLI_SEARCH_PROVIDERS` | The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped, and `searxng` is skipped until its provider exists (#3927). A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers | +| `providers` | `list` | `['searxng', 'duckduckgo', 'firecrawl']` | `DEVOPS_CLI_SEARCH_PROVIDERS` | The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped: `searxng` without `search.searxng_url`, and `firecrawl` without its key. A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers | | `language` | `str` | `en` | `DEVOPS_CLI_SEARCH_LANGUAGE` | The language of a web search, as the `Accept-Language` of its request | +| `searxng_url` | `Union` | - | `DEVOPS_CLI_SEARCH_SEARXNG_URL` | Address of the SearXNG service for web search, such as `http://searxng.devops.svc.cluster.local:8080` in the cluster, or `http://127.0.0.1:8080` on a workstation after `kubectl port-forward -n devops svc/searxng 8080:8080`. A cluster address needs `ai.allow_private_network`. It has no default, and `searxng` is skipped without it | ## Top-Level Settings diff --git a/docs/ENV_VARS.md b/docs/ENV_VARS.md index 1621234c97..ef3b76630c 100644 --- a/docs/ENV_VARS.md +++ b/docs/ENV_VARS.md @@ -125,7 +125,8 @@ All configuration options for `devops-cli` can be overridden via environment var | `DEVOPS_CLI_RUNS_INDEX_URL` | `runs.index_url` | No | Valkey holding the run index shared by workstations (set by `devops ai runs connect`) | | `DEVOPS_CLI_SANDBOX_EXCLUDE_HOME_DIR` | `sandbox.exclude_home_dir` | No | Exclude user home directory entirely from sandbox access (/home/**/* and ~/**/*) | | `DEVOPS_CLI_SEARCH_LANGUAGE` | `search.language` | No | The language of a web search, as the `Accept-Language` of its request | -| `DEVOPS_CLI_SEARCH_PROVIDERS` | `search.providers` | No | The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped, and `searxng` is skipped until its provider exists (#3927). A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers | +| `DEVOPS_CLI_SEARCH_PROVIDERS` | `search.providers` | No | The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped: `searxng` without `search.searxng_url`, and `firecrawl` without its key. A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers | +| `DEVOPS_CLI_SEARCH_SEARXNG_URL` | `search.searxng_url` | No | Address of the SearXNG service for web search, such as `http://searxng.devops.svc.cluster.local:8080` in the cluster, or `http://127.0.0.1:8080` on a workstation after `kubectl port-forward -n devops svc/searxng 8080:8080`. A cluster address needs `ai.allow_private_network`. It has no default, and `searxng` is skipped without it | | `DEVOPS_CLI_SERVICE_DRAIN_TIMEOUT_SECONDS` | `service.drain_timeout_seconds` | No | Shutdown drain timeout for running service jobs in seconds | | `DEVOPS_CLI_SERVICE_GITHUB_APP_APP_ID` | `service.github_app.app_id` | No | ID of the GitHub App that the roadmap Service and the cluster jobs act as | | `DEVOPS_CLI_SERVICE_GITHUB_APP_INSTALLATION_ID` | `service.github_app.installation_id` | No | ID of the App's installation on the account that owns the managed repositories | diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 6638651513..fe2e062497 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -90,7 +90,7 @@ writes by name. | `devops_cli_github_requests_total` | Counter | `1` | GitHub requests the rate limiter paced, each attempt and retry once, by resource, method, status, repo and row. The resource is the rate limit resource the request spends, such as core, graphql or search. The method is the HTTP method; a GraphQL request is a POST, and a gh command other than gh api is a POST when it writes and a GET when it reads. The status is the HTTP status of the answer, such as 200 or 304. It is none for a gh command or for an attempt that got no answer. The repo is the repository of the roadmap Service worker that sent the request, one of service.repos, and the row is the job row that sent it, such as metrics, intake, refine or alternatives; each is other outside a worker or a row. A gh command and a request of the GitHub session both count. The counter holds every attempt. The request budget of the Service leaves out the attempts with status 304, as GitHub does not count them against its rate limit. | | `devops_cli_github_throttle_wait_seconds` | Histogram | `s` | Time devops-cli waited before it sent a refused GitHub request again, by resource: one observation for each throttle. GitHub refused the request with a rate limit, or the GitHub session got a 5xx for a read. | | `devops_cli_github_graphql_points_total` | Counter | `1` | GraphQL points that GitHub reported each answer cost in its rateLimit field. | -| `devops_cli_web_searches_total` | Counter | `1` | Web search attempts, by the provider that ran (the backend, or none) and the result: ok for a provider that returned hits, empty for one that returned none, the HTTP status of a provider that refused the search, such as 402 when the account has no credits or 429 at its rate limit, degraded for a reply that the provider could not read, error for a provider that did not answer, refused for a query that the guard stopped, and exhausted for a search that no provider answered. The backend of the last two is none. | +| `devops_cli_web_searches_total` | Counter | `1` | Web search attempts, by the provider that ran (the backend, or none) and the result: ok for a provider that returned hits, empty for one that returned none, the HTTP status of a provider that refused the search, such as 402 when the account has no credits or 429 at its rate limit, degraded for a reply that the provider could not read, error for a provider that did not answer, refused for a query that the guard stopped or an address that the egress check refused, and exhausted for a search that no provider answered. The backend of the last two is none. | | `devops_cli_crawl4ai_fetches_total` | Counter | `1` | Page text fetches through the Crawl4AI service, by result: ok, the HTTP status of a fetch that the service refused, such as 401 for a wrong token, 429 at its rate limit or 504 when the page took too long, or error for a fetch that got no answer or a reply that is not page text. A page URL that the client refuses before it sends a request does not count. | | `devops_cli_roadmap_refine_comments_capped_total` | Counter | `1` | Refine comments that the cap on refine's comments on one item in 24 hours stopped: one count for each newest comment on an item that the cap left with no answer. The item waits on a person and takes no place under the round's limit. A later round that finds no newer comment on the item does not count it again. | | `devops_cli_roadmap_alternatives_total` | Counter | `1` | Checks of open items for an open tool that covers them, by verdict: covers, partly, none, not-applicable, rejected or in-use. One count for each check that the alternatives job writes to an item. A check that fails, or that the job skips because a person changed the item, counts nothing. | diff --git a/k8s/README.md b/k8s/README.md index c9fc551b7e..d975a118fb 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -648,7 +648,7 @@ kubectl -n devops logs -f job/ 10. Run one service per set of repos. While it runs, use `devops roadmap run --dry-run` (#981). 11. The Service keeps three files in `/home/devops/.data/roadmap/` on volume `roadmap-service-home`, beside the `schedule.json` of each repository: `service-halt.json` (GitHub refused the identity), `service-budget.json` (the GitHub requests of the last hour) and `service-failures.json` (the jobs that failed rounds in a row). A restart reads them back, so a restart does not clear a halt, the budget or a suspended job. A round that ends because the Service is stopping, for example in a rollout, does not count as a failed round: the count of its job stays as it was. The log line that suspends a job names the class of the error of each of its failed rounds in a row; the file keeps only the count, so a round that an earlier process counted reads as `unknown`. A comment of a person is new input for a job that failed a round (#2754). A person has write access (the association OWNER, MEMBER or COLLABORATOR), is no bot, and is not the account of the Service. A comment on a pull request does not count. So the answer of a person starts a suspended job again, and the job counts its failed rounds from one. A comment from before the last success of the job changes nothing. A poll with no new comment changes nothing. The Service takes no `issue_comment` event ([ADR 0009](../docs/adr/0009-one-webhook-router-delivers-each-event-to-the-consumers-subscribed-to-it.md)). A round that only polls reads the comments instead, when a job that may run failed a round before. It reads the comments of the repository from the oldest last success of those jobs, newest first. It stops at the first comment of a person, and after the newest 100 comments. So each lane that reads sends one request. A comment of a person that 100 newer comments follow does not count. The job then has the input it had before, and runs again once. A round that a webhook starts reads no comment, because the time of that round is already new input. A round with no such job, and a dry run, read no comment. At the default poll interval of 151 seconds, one repository costs at most 72 requests an hour: 3 lanes and about 24 polls. The budget `service.github_requests_per_hour` (500 by default) is for all repositories together, and it is hard, so these requests cannot pass it. They count under `row="other"` in `devops_cli_github_requests_total`, as they run outside a row. A rate limit that one request gets stops the requests of all workers until its wait ends. When GitHub refuses the identity, for example because the App's installation is suspended, the Service halts and logs `GitHub refused the identity`. To clear the halt after you fix the cause, remove the file and restart the Service: `kubectl -n devops exec deploy/roadmap-service -- rm /home/devops/.data/roadmap/service-halt.json`, then `kubectl -n devops delete pod -l app.kubernetes.io/name=roadmap-service`. 12. The Service's `/metrics` shows the budget and the suspended jobs (#2475): `devops_cli_service_budget_limit_requests` (the hourly budget), `devops_cli_service_budget_spent_requests` (the GitHub requests of the last hour, not counting the answers with status 304, which GitHub does not count against its rate limit), `devops_cli_service_budget_holds_total` (one count each time a hold begins), `devops_cli_service_job_suspended` (1 while a job of a repository, by `repo` and `row`, waits for new input after it failed 3 rounds in a row) and `devops_cli_service_implement_failures_total` (one count for each runner Job that left a stop, by the failure `class` and `repo`, when a round reports the Job; #3065; the values of `class` are the classes in [docs/ROADMAP_WORKFLOW.md](../docs/ROADMAP_WORKFLOW.md), The failure classes, and a panel or rule matches no other value, #3476). Each counter of the Service starts its label sets at zero (#3495, [docs/TELEMETRY.md](../docs/TELEMETRY.md)), except `devops_cli_service_identity_refused_total`, whose label set starts with the first refusal. Each GitHub request counts in `devops_cli_github_requests_total` under its `method`, its `status` (the HTTP status of the answer, or `none` for a gh command or an attempt with no answer), the `repo` of the worker that sent it and the job `row` (`metrics`, `intake`, `refine`, `retitle`, `stage`, `implement`, `stage_ready` or `alternatives`); a request outside a worker or a row counts as `other`. To find what spent the budget, run `sum by (repo, row, method) (increase(devops_cli_github_requests_total{job="roadmap-service"}[1h]))` in Grafana Explore. A delivery of the App bot's own write counts as outcome `self` in `devops_cli_service_webhook_deliveries_total`. -13. A refine round writes at most 2 comments on one item in 24 hours. A round that finds 2 refine comments of the last 24 hours on an item leaves the item alone, with no model call and no comment. The item waits on a person and takes no place under the round's limit, so the round refines the next item. For each newest comment on the item that the cap leaves with no answer, the round records the time of that comment in the item's job record (`refine.capped_after`), logs `Refine left # alone and wrote no comment`, and adds 1 to `devops_cli_roadmap_refine_comments_capped_total`. A later round that finds no newer comment does not log or count the item again. A person refines the item at the cap with `devops roadmap refine --item --confirm`. A web search asks the providers of `search.providers` in order (`searxng`, `duckduckgo`, `firecrawl` by default, #3925). A provider that is not configured is skipped: `searxng` until its provider exists (#3927), and `firecrawl` without its key. A provider that fails (a timeout, HTTP 401, 402, 403, 429 or 5xx, or a reply that is not readable) or returns no hit passes the search on at once, with no retry and no wait. The first provider with a hit answers. Each request goes through the HTTP entry point at the public level (the public HTTPS rule of policy `devops-default-perimeter`, no new rule). Each attempt counts in `devops_cli_web_searches_total` by `backend` (a provider name, or `none`) and `result`: `ok`, `empty`, the HTTP status of a refused search, `degraded` for a reply that cannot be read, `error` for no answer, `refused` for a query that the guard stopped, or `exhausted` for a search that no provider answered. A failed attempt logs `A web search failed on ` with the status or the error class, and never the key or the query. The guard refuses an empty query, a query over 400 characters or 50 words, a query that starts with `!` or `:`, and a query that holds a secret, an e-mail address, a private address or an internal host name; it sends no request. DuckDuckGo needs no key, so a round on a public repository has web search with the default providers. Firecrawl stays the last provider for one release cycle. When `crawl4ai.url` is set, the run also has the tool `fetch_page`, which reads the text of one page through the Crawl4AI service. It takes an https URL that a search of the same run returned or that the item text names, and no other URL; it sends no request for any other URL. A run fetches at most 3 pages. The tool frames the text as data from an outside page, never an instruction, and names the source URL and the fetch date so that a comment can cite them. A failed fetch is a tool answer and uses one fetch. Each call counts in `devops_cli_roadmap_page_fetches_total` by `toolset` (`refine` or `alternatives`) and `result` (`ok`, `refused`, `limit` or `error`). The tool is off with no `crawl4ai.url`. The tool needs the Crawl4AI service and its token. It reads pages from the web, which is new egress, so a person sets `crawl4ai.url` in the live ConfigMap to enable it. +13. A refine round writes at most 2 comments on one item in 24 hours. A round that finds 2 refine comments of the last 24 hours on an item leaves the item alone, with no model call and no comment. The item waits on a person and takes no place under the round's limit, so the round refines the next item. For each newest comment on the item that the cap leaves with no answer, the round records the time of that comment in the item's job record (`refine.capped_after`), logs `Refine left # alone and wrote no comment`, and adds 1 to `devops_cli_roadmap_refine_comments_capped_total`. A later round that finds no newer comment does not log or count the item again. A person refines the item at the cap with `devops roadmap refine --item --confirm`. A web search asks the providers of `search.providers` in order (`searxng`, `duckduckgo`, `firecrawl` by default, #3925). A provider that is not configured is skipped: `searxng` without `search.searxng_url`, and `firecrawl` without its key. A provider that fails (a timeout, HTTP 401, 402, 403, 429 or 5xx, or a reply that is not readable) or returns no hit passes the search on at once, with no retry and no wait. The first provider with a hit answers. Each request goes through the HTTP entry point. DuckDuckGo and Firecrawl use the public level (the public HTTPS rule of policy `devops-default-perimeter`, no new rule). SearXNG sends `GET /search` with `format=json` at the configured level: loopback, or private with `ai.allow_private_network`. The client follows no redirect and reads at most 1 MiB, and a reply with no result while an engine did not answer counts as `degraded`. An address that the egress check refuses counts as `refused` and passes the search on. Each attempt counts in `devops_cli_web_searches_total` by `backend` (a provider name, or `none`) and `result`: `ok`, `empty`, the HTTP status of a refused search, `degraded` for a reply that cannot be read, `error` for no answer, `refused` for a query that the guard stopped or an address that the egress check refused, or `exhausted` for a search that no provider answered. A failed attempt logs `A web search failed on ` with the status or the error class, and never the key or the query. The guard refuses an empty query, a query over 400 characters or 50 words, a query that starts with `!` or `:`, and a query that holds a secret, an e-mail address, a private address or an internal host name; it sends no request. DuckDuckGo needs no key, so a round on a public repository has web search with the default providers. Firecrawl stays the last provider for one release cycle. When `crawl4ai.url` is set, the run also has the tool `fetch_page`, which reads the text of one page through the Crawl4AI service. It takes an https URL that a search of the same run returned or that the item text names, and no other URL; it sends no request for any other URL. A run fetches at most 3 pages. The tool frames the text as data from an outside page, never an instruction, and names the source URL and the fetch date so that a comment can cite them. A failed fetch is a tool answer and uses one fetch. Each call counts in `devops_cli_roadmap_page_fetches_total` by `toolset` (`refine` or `alternatives`) and `result` (`ok`, `refused`, `limit` or `error`). The tool is off with no `crawl4ai.url`. The tool needs the Crawl4AI service and its token. It reads pages from the web, which is new egress, so a person sets `crawl4ai.url` in the live ConfigMap to enable it. 14. The row `alternatives` of the model lane runs after `refine`: on a first run, and 719 minutes after its last success. It runs `devops roadmap alternatives --confirm` for the repository. A round checks at most `roadmap.alternatives.first_pass_limit` items (20 by default) while an item has no check, and at most `roadmap.alternatives.limit` items (5 by default) after. The row runs about twice a day, so a first pass of 141 items takes about 4 days. A round takes first the items with no check, then the items whose check is older than `roadmap.alternatives.recheck_days` (30 by default) or whose text changed. A webhook makes the row due at no other time. The row changes no label and closes no issue. It does nothing, and logs `The alternatives check of is off`, for a private repository and when no search provider is configured. If the check of an item fails, the row records the failure in the item's job record (`alternatives.failed_at` and `alternatives.failed_error`, the class of the error), writes the other checks and succeeds. The row fails, and counts toward the suspension after 3 failed rounds, only when it tried items and checked none. A round takes a failed item again after `roadmap.alternatives.retry_days` (3 by default). Each written check adds 1 to `devops_cli_roadmap_alternatives_total` by `verdict`: `covers`, `partly`, `none`, `not-applicable`, `rejected` or `in-use`. Each round also sends two gauges by `repo` at its start, before it checks any item, also when it checks none (#2950): `devops_cli_roadmap_alternatives_unchecked_items` (the items that the check can take and has no check for, an item in the retry delay too) and `devops_cli_roadmap_alternatives_oldest_check_age_seconds` (the age of the oldest check among those items, sent only while one has a check). Each written check observes `devops_cli_roadmap_alternatives_searches` by `verdict`: the searches the check ran, 0 for a skip class. The row Alternatives Check of the dashboard `devops-cli Telemetry` shows the three, and the alert `RoadmapServiceAlternativesNotSearching` warns when the Service made no web search in 3 days while an item has no check. An item of the type `test`, `docs`, `refactor`, `chore`, `ci` or `perf`, and a `fix` with a Python traceback in its body, gets `not-applicable` with no model call; every other item must run a search before the check accepts a verdict, and gets one more turn to search. Once for a round that checks an item of no skip class, the check reads the ADRs of `docs/adr/` that are in force. An ADR that a later ADR supersedes is left out. The model sees the number, the title, the status lines and the `Considered Options` section of each ADR. The model proposes `rejected` with the number of an ADR, and `in-use` when the item names the tool. The job gives either verdict only when the text confirms it. It drops a proposal that it cannot confirm and keeps the verdict of the reply. A cut by the token cap leaves out whole ADRs and logs a warning. A `covers` verdict makes refine ask a person to adopt the tool or to keep the item with a reason. A `rejected` or `in-use` verdict asks nothing. The item waits on a person until a reply answers the question, and Ready items with a new covering tool go back to New. Refine records the tool it asked about in the job record (`refine.alternatives_asked`). `devops roadmap run --dry-run` lists the row when it is due. 15. The row `retitle` follows `refine` on the model lane (#3535). It is due on a first run and every 61 minutes. It shortens the title summary of at most 25 open items, as `devops roadmap retitle --confirm` does, with the model of the `triage` task. It needs no clone, and it reads and writes only the issues of the repository. The row `stage` follows `retitle` on the model lane (#2659), so the stage job reads the new titles in the same round. It runs `devops roadmap stage --confirm` in the model clone: it is due every 37 minutes, on a first run, and in a round where `refine` set an item Ready. It stages the Ready items that `roadmap.stage.filter` names, at most `roadmap.stage.limit` in a round, plans only items with the priority `P0-Critical` or `P1-High` while the count of open Planned items is at `roadmap.stage.planned_limit` (#3487, #3692), and splits a task group over `roadmap.stage.step_tokens`. Each task group has a kind (#3005): a `behavior` group has a failing test, and an `other` group has no test but a command or the steps of a manual check that prove it. The job sends a reply that breaks this rule back to the model once. It leaves out an item whose change folder is on the default branch or in its archive (#2714): a round reads that tree once with `git ls-tree`, so a merged staging pull request never makes a second one. The pull request it opens is a draft with the title `docs(openspec): plan # `. The job does not mark it ready: the row `stage_ready` does (step 18). Before it opens one, it checks each path of the plan (`reads`, `changes`, the code spans of the tasks and `verify`) against the tracked files of the commit it plans, read with one `git ls-files` for the round (#3010). A path that is no file there, and that no group up to its own creates, goes back to the model once with the files of the same name. When a later group creates the path, the problem names that group and tells the model to move it before the group that names the path (#3017). A second reply with a missing path stops the item, so no draft opens and the implement Job never meets a wrong path. `k8s/devops/configmap.example.yaml` holds the five settings, and `devops k8s deploy-stack --stack devops` applies them; each also has a variable, `DEVOPS_CLI_ROADMAP_STAGE_FILTER`, `DEVOPS_CLI_ROADMAP_STAGE_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_PLANNED_LIMIT`, `DEVOPS_CLI_ROADMAP_STAGE_STEP_TOKENS` and `DEVOPS_CLI_ROADMAP_STAGE_TOOLSET`. The setting `roadmap.stage.toolset` is `extended` by default (#3238): a plan run then has three tools more than the nine that read the staged commit. `references` counts a text in every file of the commit. `read_issue` and `find_issues` read issues and pull requests of the repository on GitHub, as GET requests with the token of the Service and no other permission. `base` leaves them out. Each item of a round counts once in `devops_cli_roadmap_stage_total` by its `result`: `staged`, `skipped`, `needs_split` or `failed`. A failed item is recorded in its job record with the class of its error and the time (#3493), and the job leaves it out for `roadmap.stage.retry_hours` hours (6 by default) while it takes the other items. The row fails a round only when it tried items and staged, stopped or returned none, or when a failure belongs to no item; three such rounds on the same input suspend the row. The ledger file keeps the class of each error, and a round that the stop of the Service ends counts as `stopped`, not as an error. The image carries the pinned OpenSpec and a Node runtime, so the job validates each change before it pushes: `kubectl -n devops exec deploy/roadmap-service -- openspec --version` prints the locked version. 16. The row `implement` follows `metrics` on the status lane (#2667, #2757). It calls no model, so a model-lane round that has not ended never delays it. It is due every 7 minutes and on a first run, in the clone of the status lane. The Service runs no step: a round only talks to the Kubernetes API, in three moves. It reports each Job that ended, with a comment on the item that holds the state and the last 40 lines of the log of the Job's pod, masked of secrets, and records `implement.job_state` as `succeeded`, `failed` or `gone`. It moves the deadline of each Job that has not ended (#3063, below). It waits while a Job of the repository has not ended. Else it makes one Job from CronJob `devops-cli-runner` for the first Staged or Planned item that the default filter names (a Planned item has its change folder on the default branch and no branch: a person merged the staging pull request, and the job makes the branch and the draft itself), with the args `roadmap implement --repo --item --confirm` and the item's number as the only item text, and records the name of the Job in `implement.job`, and the digest of the runner image that the CronJob template names in `implement.job_digest`. The same write sets the label `owner/service` on the item (#2910), and the report of the Job removes it. The comment that reports the Job names the digest. The Service makes no Job for an item that an agent or a person claimed, and a claim of an agent or a person ends a running Job at its next group boundary, with no push and no pull request. A round also sets the Status label of the items from their record (`status_sync.py`): it reads the plans on the default branch once for the sweep and for the plan, writes `status/planned` once a plan is merged, and writes `status/in-progress` as soon as the record names a Job, and again after it makes one. It writes only an open item that holds Ready or Planned with the label that a job last recorded, so a label that a person set stays. The rows `stage` and `stage_ready` use the same function. The Jobs of a repository carry the label `implement-repo`, whose value is a digest of the repository name, so the API is the lock and a restart of the Service loses nothing. A Job that leaves its item In Progress, or Ready or Planned with no stop, is a stop that the runner could not write, such as a pod that the kernel killed for its memory, unless an agent or a person claimed the item. The round then sets the item Blocked (`status/blocked`) and records `implement.stopped` as `job`. No Job is made for it before a clear rule runs. A stop that the runner writes sets Blocked in the same way, with the step in `implement.stopped`. After the report, the round clears the stop of each item that it set Blocked. It uses one of three rules, and a comment names the rule that ran. Rule `retry`: a comment `implement: retry`, made after the report by the owner, a member or a collaborator, clears the stop at once, whatever the image. Rule `continue` (#3721): three things must hold. The stop is `job`, which the round records for a Job that ended with no result. Examples are a pod that the kernel killed or evicted, a stalled Job that the Service ended, and a Job that no longer exists. The class in `implement.failure` has the action `retry` in `ACTION_BY_CLASS`. The count `implement.continuations` is less than the setting `roadmap.implement.continuations_per_item` (default 2, 0 turns the rule off). Kubernetes never restarts a Failed Job: `activeDeadlineSeconds` takes precedence over `backoffLimit`, and the template sets `backoffLimit: 0` on purpose. So a continuation is a new Job from the Service. The clear adds 1 to `implement.continuations`, a count and no other data, which stays after a clear. A retry of a person does not reset it. The comment says "continuation n of N", and at the limit it adds "No continuation is left". The rule runs before `digest`, reads no template and spends no clear by digest. The new Job takes the branch from `origin`. So it keeps the `wip:` commits that the run pushed for a group with more than one task (#3054). A group of one task that passed, and that no push kept, runs again. A class with another action, such as `oom` (`raise_limit`), waits for a retry, because a second run on the same limit ends the same way. Only a sign in the log gives the class `oom`. The Service reads no pod status, so a kill with no text in the log is continued as `ci_infra` (follow-up #3727). A stop that the runner wrote, with a step in `implement.stopped`, is no continuation. At the limit, a new runner image still clears the stop by the rule `digest`, within its limits. Rule `digest`: the digest in the template of CronJob `devops-cli-runner` is not `implement.job_digest`, so a new runner image has rolled out since the stop, and the class in `implement.failure` has the action `retry` in `ACTION_BY_CLASS` (#3481). A new image cannot fix a plan, a premise, a refused tool or a failed test, so a stop of another class, and a stop with no class on record, wait for a retry. Each clear by digest adds the class, the new digest and the time to `implement.digest_clears`, and the list stays after the clear. The settings `roadmap.implement.digest_clears_per_class` (default 1) and `roadmap.implement.digest_clears_per_item` (default 3) bound the entries; a stop at a limit stays Blocked until a retry, also for `ci_infra`. The comment of a clear by digest shows at most one time in 24 hours for an item (`implement.digest_clear_commented_at`), and the clear is recorded either way. The rule reads no image content: the Service holds digests and no map from a digest to commits. A clear sets Ready or Planned and removes `implement.stopped`, and the same round can make a Job for the item. The new Job overwrites `implement.job_digest`, so a second stop on the same image waits for a retry. A continuation is the exception, and `implement.continuations` bounds it. So the round makes no Job in a loop. A stop with no digest on record is cleared by a retry only, except a stop `job`, which a continuation clears with no digest. Inside one priority, a round takes an item with no digest clear before an item with one, and a retried item of a higher priority still goes before a new item of a lower priority. A Blocked stop that no rule clears costs one request in each round, the listing of its comments (6 an hour of `service.github_requests_per_hour`); the round reads the issue again only when a rule holds, and reads the template at most one time. The round clears no item that a Job holds, that an agent or a person claimed, or that a person labeled Blocked by hand. The failures ledger is unchanged: three failed rounds on the same input still suspend the row. If CronJob `devops-cli-runner` does not exist, the round fails with a message that names it: run `devops k8s deploy-stack --stack devops`, or wait for Argo CD. A Job that cannot pull its image (the package `runner` is not public, or no release published it) has an empty log, so it ends by its stall after 40 minutes, and the next round records the stop. Read the Jobs with `kubectl -n devops get jobs -l implement-repo`. The Job runs the checks that a person runs at a commit and at a push (#3043). Before the first step it runs `pre-commit install-hooks`, with `PRE_COMMIT_HOME` in the cache directory of the data directory, on the home volume. The two remote hook repositories come over public HTTPS (9 s and 51 MB, measured). A failed install stops the item at the step `hooks`, before any model request. Each step then runs the `pre-commit` stage on its staged changes as its last exit check. The child is `uv`, which holds no token. The Job installs no git hook, because git runs a hook with the token of the session, and the agent can edit the hook configuration. For the same reason every hook run gets `--config` with a copy of the configuration of the default branch, so an edit of the agent skips no hook. A hook run that runs out of time stops the step. A failed hook goes to the agent as a repair turn with its output. The setting `roadmap.implement.repair_rounds` (variable `DEVOPS_CLI_ROADMAP_IMPLEMENT_REPAIR_ROUNDS`, default 3) bounds the extra turns of a step for `ruff`, `mypy` and the hooks. Only a used budget stops the step. After the last group, the docs, the archive and the final rebase, and before the push, the Job runs the scoped checks: the `pre-push` stage of the hooks, `devops ci --check --only constructs,docs,openspec`, and `devops ci test` with the test modules that cover the changed Python files of `src/` and `tests/`. Above 30 test modules, which a change to a shared module gives, the tests check runs only the changed test modules, and it does not run when no test covers the change. A failed check starts a fix step, up to `repair_rounds` times for all scoped checks. The Job generates the docs again after each fix. It pushes a finished item only after all of them pass. A stop in this phase (a used budget, a fix step that stops, an error, a command that runs out of time) pushes the commits that passed to the item branch, as any other stop does, and the draft pull request stays a draft (#3645). The comment on the pull request shows the repair rounds of each step, and each run of a scoped check with its seconds. The extra run time of an item is about 10 s of hooks for each step, 9 s for the install, 35 s for the first two scoped checks, and at most about 3.5 minutes for the tests (12 test modules of the roadmap ran in 88 s on 2 CPUs). So it is 2 to 5 minutes in a Job that runs about an hour. The workflow checks `actionlint` and `zizmor` run in the `pre-push` stage only when the push changes a workflow, because the runner image holds no `actionlint`. A failed check of the pull request after the push gets a fix step, a push and a new watch, up to `repair_rounds` times, with a comment on the pull request for each round. diff --git a/k8s/devops/configmap.example.yaml b/k8s/devops/configmap.example.yaml index 112dc7ffe9..b3be3ca266 100644 --- a/k8s/devops/configmap.example.yaml +++ b/k8s/devops/configmap.example.yaml @@ -64,6 +64,11 @@ data: # ConfigMap. crawl4ai: url: http://crawl4ai.devops.svc.cluster.local:11235 + # The SearXNG service in namespace devops, which searches the web with no key. The cluster + # address needs ai.allow_private_network. On a workstation, set the address to + # http://127.0.0.1:8080 after `kubectl port-forward -n devops svc/searxng 8080:8080`. + search: + searxng_url: http://searxng.devops.svc.cluster.local:8080 telemetry: enabled: true endpoint: http://otel-collector-opentelemetry-collector.otel.svc.cluster.local:4318 diff --git a/openspec/changes/3927-searxng-search-provider/.openspec.yaml b/openspec/changes/3927-searxng-search-provider/.openspec.yaml new file mode 100644 index 0000000000..e582ee4a2c --- /dev/null +++ b/openspec/changes/3927-searxng-search-provider/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/3927-searxng-search-provider/design.md b/openspec/changes/3927-searxng-search-provider/design.md new file mode 100644 index 0000000000..4a289525cc --- /dev/null +++ b/openspec/changes/3927-searxng-search-provider/design.md @@ -0,0 +1,17 @@ +# Design + +## Decisions + +- **One class, one setting.**: `SearxngProvider` follows the protocol of the chain, so the chain code changes in one place only (see the next decision). `configured` is true when `search.searxng_url` is set. +- **Add `method` to the protocol.**: The dry run printed `POST` for the first provider. SearXNG searches with `GET`, so each provider names its method, and `url` is a property for the provider whose address comes from the settings. +- **A refused address passes the search on.**: `SSRFBlockedError` is not an `httpx2.HTTPError`. A cluster address with `ai.allow_private_network` off would end the whole search with an exception, and DuckDuckGo would never run. The chain counts it as `refused` with a warning that holds the error class, and goes on. +- **Stream the reply and cap it.**: The same rule as the Crawl4AI client: the body is read in chunks and refused at 1 MiB. A SearXNG reply holds about 20 results, so the cap leaves room. +- **Categories `general,it,science` as a constant.**: The kept engines answer in these categories (see Feasibility). A setting would add a key that no one has a reason to change before the live check shows the real behavior. +- **`degraded` for a silent engine.**: SearXNG reports a suspended engine only in `unresponsive_engines`. An empty list of results with that field set is a failure of the engines, not an answer, so the chain counts `degraded` and goes on. With hits, the hits answer. +- **No redirect, no retry.**: `follow_redirects=False`. HTTP 3xx fails through `raise_for_status`, and its status is the result. + +## Rejected alternatives + +- **A SearXNG client package.**: None read. The call is one `GET` and one JSON object. +- **`allows_keep` on the provider.**: It existed for the Brave terms. The owner dropped Brave on 2026-11-07, and every provider's hits may be kept. +- **A default address for the setting.**: A default would send queries to a host that may not exist (no unconfigured fallback). diff --git a/openspec/changes/3927-searxng-search-provider/proposal.md b/openspec/changes/3927-searxng-search-provider/proposal.md new file mode 100644 index 0000000000..bd03642e20 --- /dev/null +++ b/openspec/changes/3927-searxng-search-provider/proposal.md @@ -0,0 +1,47 @@ +# Proposal + +## Why + +The chain of web search providers (#3925) lists `searxng` and skips it, because no provider class exists. The project runs no search service of its own: Firecrawl answers HTTP 402, and DuckDuckGo has no second path. SearXNG (manifest item #3924) is a keyless search service that the cluster will run. The chain needs a client for it (#3927). + +## What Changes + +- A new class `SearxngProvider` in `src/devops_cli/ai/web_search.py`, with the name `searxng`, listed in `PROVIDERS`. It sends `GET {search.searxng_url}/search` with `q`, `format=json`, `language` (from `search.language`), `categories` and `pageno=1`, through `http_client(level=configured_level(...))`. A loopback address needs no flag; a cluster Service address needs `ai.allow_private_network`. +- The client follows no redirect. SearXNG answers a query that starts with `!` with a redirect, so a redirect is a failure with its status as the result. A reply with another status than 200 is a failure with its status as the result. The client reads at most 1 MiB; a larger reply is `degraded`. +- The provider maps each item of `results` to a `SearchHit` with the provider `searxng`. An empty `results` with a non-empty `unresponsive_engines` is `degraded`; an empty `results` with an empty `unresponsive_engines` is `empty`. +- New setting `search.searxng_url` (variable `DEVOPS_CLI_SEARCH_SEARXNG_URL`) with no default. Without it the provider is not configured and the chain skips it. A direct call raises `ConfigurationError` that names the setting. +- `SearchProvider` gains `method`, and the dry run of `devops roadmap alternatives` lists the method of the first configured provider (`GET` for SearXNG, not always `POST`). +- An address that the egress check refuses (`SSRFBlockedError`) passes the search on and counts as `refused` for the provider, as a failed provider does. Without this, a cluster address with the flag off would stop the whole search before DuckDuckGo. +- `k8s/devops/configmap.example.yaml` names the cluster address, and `k8s/README.md` and the generated settings documents describe the setting. +- The change is observable in a setting, a metric result and a dry run, so it carries a spec delta for `web-search`. +- The change fits one pull request. + +## Capabilities + +### Modified Capabilities + +- `web-search`: The SearXNG provider, its request, its failure rules and the setting `search.searxng_url` + +## Impact + +- Code: `src/devops_cli/ai/web_search.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/roadmap/request_plan.py`, `src/devops_cli/telemetry/instruments.py` +- Tests: `tests/ai/test_web_search_searxng.py` (new), `tests/fixtures/searxng/search_reply.json` (new), `tests/ai/test_web_search.py`, `tests/roadmap/test_roadmap_dry_runs.py` +- Documents: `docs/CONFIGURATION.md`, `docs/ENV_VARS.md`, `docs/TELEMETRY.md` (generated), `k8s/README.md`, `k8s/devops/configmap.example.yaml` +- Dependencies: none + +## Feasibility + +- The API: the SearXNG document `docs/dev/search_api.rst` at commit 629368e40 (the commit of the pinned image `2026.10.23-629368e40`), read on 2026-11-07, says that `GET /search` takes `q`, `categories` (comma separated), `language`, `pageno` and `format`, and that a format that `search.formats` does not list answers HTTP 403. +- The engines that the manifest keeps (`searx/settings.yml` at that commit) sit in the categories `general` (wikipedia, duckduckgo), `it` (stackoverflow, askubuntu, superuser, mdn, docker hub, github, pypi) and `science` (arxiv). The provider asks for `general,it,science`. This is read from the engine files, not from a live pod. +- NOT RUN: a live query. The SearXNG manifests (#3924) are not in `main`, so no pod exists. The reply fixture holds the shape that the API document gives, not a saved reply. The live check (#3929) must replace the fixture with a reply saved from the pinned digest and must check the categories; this change moves that criterion to #3929. +- The redirect: `searx/webapp.py` answers with a redirect when `result_container.redirect_url` is set, which a bang query causes (researcher, 2026-11-07). The test `test_a_redirect_is_a_failure_and_no_second_request_is_sent` holds the client to it. The query guard already refuses a query that starts with `!` or `:`. +- `configured_level` gives loopback, or private with `ai.allow_private_network`. The tests in `tests/ai/test_web_search_searxng.py` show a loopback address works with the flag off and a cluster address needs it. +- The Brave Search API and the `allows_keep` flag are not part of the design (the owner dropped them on 2026-11-07). + +## Existing Tool Considered + +The project's `http_client` and `configured_level`, `service_base_url`, and the SearXNG JSON API. Rejected: a Python SearXNG client package (none read; the call is one request and one JSON object) and the `pydantic-ai` search tools (they take no transport, so they skip the egress check). The written cost is about 25k tokens to build and keep, and 1 hour. + +## Dependencies + +None for the code. The manifest item #3924 deploys the service, and the live check #3929 holds the fixture to a real reply. diff --git a/openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md b/openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md new file mode 100644 index 0000000000..786bb9801c --- /dev/null +++ b/openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md @@ -0,0 +1,76 @@ +## ADDED Requirements + +### Requirement: The SearXNG provider is configured by its address +The provider `searxng` SHALL be configured when `search.searxng_url` is set, and SHALL be skipped without it. A direct call without the setting SHALL raise `ConfigurationError` that names `search.searxng_url`. + +#### Scenario: No address +- **WHEN** `search.searxng_url` is not set +- **THEN** no request reaches SearXNG and the counter has no point with the backend `searxng` + +### Requirement: The SearXNG provider searches with a JSON request +The provider SHALL send `GET
/search` with `q`, `format=json`, `language` (the value of `search.language`), `categories` and `pageno=1`. It SHALL map each item of `results` that has a `url` to a hit with `url`, `title`, `content` as the snippet, and the provider `searxng`. + +#### Scenario: A good reply +- **WHEN** the providers are `searxng` and the service answers with three results +- **THEN** `web_search` returns three hits with the provider `searxng`, and the counter has a point with the backend `searxng` and the result `ok` + +#### Scenario: The request +- **WHEN** a search runs for a query with `search.language` set to `de` +- **THEN** one `GET` reaches `/search` with the parameters `q`, `format=json`, `language=de`, `categories` and `pageno=1` + +### Requirement: The SearXNG client dials by the configured egress level +The provider SHALL send its request through the HTTP entry point at the configured level: loopback, or private when `ai.allow_private_network` is set. + +#### Scenario: A loopback address +- **WHEN** `search.searxng_url` is a loopback address and `ai.allow_private_network` is off +- **THEN** the search reaches the service + +#### Scenario: A cluster address +- **WHEN** `search.searxng_url` is a cluster Service address that resolves to a private address and `ai.allow_private_network` is off +- **THEN** a direct call raises `SSRFBlockedError` and no request is sent, and with the setting on the search reaches the service + +### Requirement: The SearXNG client follows no redirect and reads a capped reply +The provider SHALL follow no redirect and SHALL read at most 1 MiB of a reply. A reply with a status other than 200, a redirect included, SHALL count with the status as the result and SHALL pass the search on. + +#### Scenario: A status other than 200 +- **WHEN** the service answers HTTP 403, 429 or 503 +- **THEN** the counter has a point with the backend `searxng` and that status as the result, and the next provider is asked + +#### Scenario: A redirect +- **WHEN** the service answers HTTP 302 +- **THEN** one request was sent, and the counter has a point with the backend `searxng` and the result `302` + +### Requirement: A SearXNG reply that cannot answer passes the search on +A reply over the byte cap, a reply that is not a JSON object with a `results` list, and a reply with no result and a non-empty `unresponsive_engines` SHALL count as `degraded`. A reply with no result and an empty `unresponsive_engines` SHALL count as `empty`. An address that the egress check refuses SHALL count as `refused`. Each SHALL pass the search on. + +#### Scenario: Engines that did not answer +- **WHEN** the service answers with an empty `results` and a non-empty `unresponsive_engines` +- **THEN** the counter has a point with the backend `searxng` and the result `degraded` + +#### Scenario: No result +- **WHEN** the service answers with an empty `results` and an empty `unresponsive_engines` +- **THEN** the counter has a point with the backend `searxng` and the result `empty` + +#### Scenario: A refused address +- **WHEN** the egress check refuses the address of the service +- **THEN** the counter has a point with the backend `searxng` and the result `refused`, and the next provider is asked + +### Requirement: The dry run lists the method of the first provider +The dry run of `devops roadmap alternatives` SHALL list the method and the URL of the request of the first configured provider. + +#### Scenario: SearXNG is first +- **WHEN** `searxng` is the first configured provider +- **THEN** the dry run lists `GET` with the search endpoint of the service, and no request to DuckDuckGo + +## MODIFIED Requirements + +### Requirement: The settings name the providers and the language +The section `search` of the settings SHALL have `providers`, a list of `searxng`, `duckduckgo` and `firecrawl` with the default `searxng`, `duckduckgo`, `firecrawl`, `language`, with the default `en`, and `searxng_url`, with no default. An unknown provider name SHALL be a validation error. The variables SHALL be `DEVOPS_CLI_SEARCH_PROVIDERS`, `DEVOPS_CLI_SEARCH_LANGUAGE` and `DEVOPS_CLI_SEARCH_SEARXNG_URL`. The text of `providers` SHALL say that `searxng` is skipped without `search.searxng_url`. + +#### Scenario: An unknown provider +- **WHEN** the settings are built with the providers `duckduckgo` and `bing` +- **THEN** the settings raise a validation error that names `providers` + +#### Scenario: The address has no default +- **WHEN** the settings are built with no value for `search.searxng_url` +- **THEN** `search.searxng_url` is not set diff --git a/openspec/changes/3927-searxng-search-provider/tasks.md b/openspec/changes/3927-searxng-search-provider/tasks.md new file mode 100644 index 0000000000..835fe6a165 --- /dev/null +++ b/openspec/changes/3927-searxng-search-provider/tasks.md @@ -0,0 +1,29 @@ +# Tasks + +## 1. Add the SearXNG provider + +Reads: `src/devops_cli/ai/web_search.py`, `src/devops_cli/ai/page_text.py`, `src/devops_cli/http/egress.py`, `src/devops_cli/roadmap/request_plan.py`. Changes: `src/devops_cli/ai/web_search.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/roadmap/request_plan.py`, `src/devops_cli/telemetry/instruments.py`, `tests/ai/test_web_search_searxng.py`, `tests/fixtures/searxng/search_reply.json`, `tests/ai/test_web_search.py`, `tests/roadmap/test_roadmap_dry_runs.py`. + +- [x] 1.1 In `tests/ai/test_web_search_searxng.py` and `tests/fixtures/searxng/search_reply.json`, write the cases of the provider: a good reply, the request parameters, the cap, each status, a redirect, an empty reply with and without an unresponsive engine, a reply that is not readable, the byte cap, no address, a loopback address, a cluster address with the flag off and on, a refused address, and the log line + - Verification: `uv run devops ci test tests/ai/test_web_search_searxng.py` +- [x] 1.2 Add `SearxngProvider`, `method` on the providers, the setting `search.searxng_url`, the constants, and the `refused` count of a refused address in `web_search`; make the dry run use `provider.method` + - Verification: `uv run devops ci test tests/ai/test_web_search.py tests/ai/test_web_search_searxng.py tests/roadmap/test_roadmap_dry_runs.py tests/config` + +## 2. Update the documents + +Reads: `k8s/README.md`, `k8s/devops/configmap.example.yaml`. Changes: `k8s/README.md`, `k8s/devops/configmap.example.yaml`, `docs/CONFIGURATION.md`, `docs/ENV_VARS.md`, `docs/TELEMETRY.md`. + +- [x] 2.1 Name the cluster address in the example ConfigMap and describe the provider in `k8s/README.md`, and regenerate the settings documents + - Verification: `uv run devops docs generate --sync-readme && uv run devops docs generate --check` + +## Criteria + +- Group 1: The provider SHALL send `GET /search` with `format=json` and follow no redirect. +- Group 1: A status other than 200 SHALL count with the status as the result, and an empty result with an unresponsive engine SHALL count as `degraded`. +- Group 1: A loopback address SHALL need no flag, and a cluster address SHALL need `ai.allow_private_network`. +- Group 2: The generated documents SHALL list `search.searxng_url`. + +## Workflow follow-up + +- The SearXNG manifests are the item #3924. The live check of the pinned image is #3929: it replaces the fixture with a saved reply and checks the categories. +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/src/devops_cli/ai/web_search.py b/src/devops_cli/ai/web_search.py index 0de869bae9..3d0d835413 100644 --- a/src/devops_cli/ai/web_search.py +++ b/src/devops_cli/ai/web_search.py @@ -5,13 +5,14 @@ hit, passes the search on at once, with no retry and no wait. Every request goes through the HTTP entry point at the public level, so the egress check of SECURITY.md applies to each provider. -A new provider is a class with the three members of `SearchProvider` and one entry in `PROVIDERS` -and in `SearchProviderName`. +A new provider is a class with the members of `SearchProvider` and one entry in `PROVIDERS` and in +`SearchProviderName`. """ from __future__ import annotations import ipaddress +import json import logging from collections.abc import Iterator from dataclasses import dataclass @@ -38,6 +39,9 @@ DEFAULT_DUCKDUCKGO_TIMEOUT_SECONDS, DEFAULT_FIRECRAWL_SEARCH_URL, DEFAULT_FIRECRAWL_TIMEOUT_SECONDS, + DEFAULT_SEARXNG_CATEGORIES, + DEFAULT_SEARXNG_MAX_REPLY_BYTES, + DEFAULT_SEARXNG_TIMEOUT_SECONDS, DEFAULT_WEB_SEARCH_DEADLINE_SECONDS, DEFAULT_WEB_SEARCH_LIMIT, DEFAULT_WEB_SEARCH_QUERY_MAX_CHARS, @@ -46,8 +50,11 @@ from devops_cli.config.settings import Settings, get_firecrawl_api_key, load_settings from devops_cli.core import clock from devops_cli.exceptions.ai import SearchFailed, SearchQueryRefused -from devops_cli.http.egress import EgressLevel +from devops_cli.exceptions.config import ConfigurationError +from devops_cli.exceptions.security import SSRFBlockedError +from devops_cli.http.egress import EgressLevel, configured_level from devops_cli.http.entry import http_client +from devops_cli.http.urls import service_base_url from devops_cli.security.reference_extractor import ( is_local_or_reserved_domain, is_private_or_local_ip, @@ -59,6 +66,7 @@ _PROSE_EDGES: Final[str] = ".,;:!?\"'`(){}<>" _HTTP_SCHEMES: Final[frozenset[str]] = frozenset({"http", "https"}) +_SEARXNG_SETTING: Final[str] = "search.searxng_url" @dataclass(frozen=True) @@ -79,8 +87,20 @@ class SearchProvider(Protocol): passes the search on. """ - name: str - url: str + @property + def name(self) -> str: + """The name that `search.providers` lists and the metric uses as its backend.""" + ... + + @property + def method(self) -> str: + """The HTTP method of a search request.""" + ... + + @property + def url(self) -> str: + """The URL of a search request.""" + ... def configured(self, settings: Settings) -> bool: """Whether the provider has what it needs to search, such as a key.""" @@ -100,6 +120,7 @@ class DuckDuckGoProvider: """ name = "duckduckgo" + method = "POST" url = DEFAULT_DUCKDUCKGO_SEARCH_URL def configured(self, settings: Settings) -> bool: @@ -141,6 +162,7 @@ class FirecrawlProvider: credit for each result.""" name = "firecrawl" + method = "POST" url = DEFAULT_FIRECRAWL_SEARCH_URL def configured(self, settings: Settings) -> bool: @@ -176,10 +198,99 @@ def search(self, query: str, *, limit: int) -> list[SearchHit]: ] -# The providers that exist, by the name that `search.providers` lists. `searxng` is not here until -# its provider exists (#3927): the chain skips a listed name that has no provider. +class SearxngProvider: + """The SearXNG service of the cluster (#3927). It needs no key, only its address in + `search.searxng_url`, which has no default. + + The request is `GET {address}/search` with `format=json`. A model chooses the query, and + SearXNG reads a query that starts with `!` as an engine selector and answers it with a + redirect, so the client follows no redirect: a redirect is a failure (the query guard refuses + such a query first). The client dials a loopback address, and a private one when + `ai.allow_private_network` is set, so a workstation reaches the service by + `kubectl port-forward` and the Service pod by its cluster address. The client reads at most + `DEFAULT_SEARXNG_MAX_REPLY_BYTES`. The title and the text of a hit are data from the web and + untrusted: a caller must never run them as an instruction. + """ + + name = "searxng" + method = "GET" + + @property + def url(self) -> str: + """The search endpoint of the configured service, or an empty string without an address.""" + address = load_settings().search.searxng_url + return f"{service_base_url(address, _SEARXNG_SETTING)}/search" if address else "" + + def configured(self, settings: Settings) -> bool: + return bool(settings.search.searxng_url) + + def search(self, query: str, *, limit: int) -> list[SearchHit]: + """Raises `ConfigurationError` when `search.searxng_url` is not set, `SSRFBlockedError` when + the egress check refuses the address, `httpx2.HTTPStatusError` for an answer other than + HTTP 200 (a redirect included), and `ValueError` for a reply that is over the byte cap, is + not a JSON object with a `results` list, or has no result while an engine did not + answer.""" + settings = load_settings() + if not settings.search.searxng_url: + raise ConfigurationError( + f"The setting {_SEARXNG_SETTING} is not set", key=_SEARXNG_SETTING + ) + endpoint = f"{service_base_url(settings.search.searxng_url, _SEARXNG_SETTING)}/search" + with ( + http_client( + level=configured_level(settings.ai), + timeout=DEFAULT_SEARXNG_TIMEOUT_SECONDS, + follow_redirects=False, + ) as client, + client.stream( + "GET", + endpoint, + params={ + "q": query, + "format": "json", + "language": settings.search.language, + "categories": DEFAULT_SEARXNG_CATEGORIES, + "pageno": "1", + }, + headers={"Accept": "application/json", **_language_headers()}, + ) as response, + ): + response.raise_for_status() + if response.status_code != httpx2.codes.OK: + raise ValueError(f"SearXNG answered with HTTP {response.status_code}") + body = _read_capped(response) + reply = json.loads(body) + results = reply.get("results") if isinstance(reply, dict) else None + if not isinstance(results, list): + raise ValueError("SearXNG reply has no 'results' list") + if not results and reply.get("unresponsive_engines"): + raise ValueError("SearXNG engines did not answer") + return [ + SearchHit( + url=str(item["url"]), + title=str(item.get("title") or ""), + snippet=str(item.get("content") or ""), + provider=self.name, + ) + for item in results[:limit] + if isinstance(item, dict) and item.get("url") + ] + + +def _read_capped(response: httpx2.Response) -> bytes: + """The body of a streamed reply, refused as soon as it passes the byte cap.""" + body = bytearray() + for chunk in response.iter_bytes(): + body += chunk + if len(body) > DEFAULT_SEARXNG_MAX_REPLY_BYTES: + raise ValueError("SearXNG reply is larger than the byte cap") + return bytes(body) + + +# The providers that exist, by the name that `search.providers` lists. PROVIDERS: Final[dict[str, SearchProvider]] = { - provider.name: provider for provider in (DuckDuckGoProvider(), FirecrawlProvider()) + provider.name: provider + for provider in (SearxngProvider(), DuckDuckGoProvider(), FirecrawlProvider()) } @@ -237,6 +348,9 @@ def web_search(query: str, *, limit: int = DEFAULT_WEB_SEARCH_LIMIT) -> list[Sea except httpx2.HTTPError as exc: _failed(provider.name, CONST_WEB_SEARCH_RESULT_ERROR, type(exc).__name__) continue + except SSRFBlockedError as exc: + _failed(provider.name, CONST_WEB_SEARCH_RESULT_REFUSED, type(exc).__name__) + continue except ValueError as exc: _failed(provider.name, CONST_WEB_SEARCH_RESULT_DEGRADED, type(exc).__name__) continue @@ -359,6 +473,7 @@ def _is_private_address(host: str) -> bool: "FirecrawlProvider", "SearchHit", "SearchProvider", + "SearxngProvider", "configured_providers", "first_configured_provider", "iter_configured_providers", diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 87f1758519..021ab1c599 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -546,7 +546,7 @@ # ── AI Web Search Defaults ────────────────────────────────────────────────────── # The providers that `web_search` can ask (#3925). The default list is the order of the asks: a -# provider that is not configured is skipped, and `searxng` has no provider class yet (#3927). +# provider that is not configured is skipped, and `searxng` is not configured without its address. SearchProviderName = Literal["searxng", "duckduckgo", "firecrawl"] DEFAULT_SEARCH_PROVIDERS: Final[tuple[SearchProviderName, ...]] = ( "searxng", @@ -568,6 +568,13 @@ DEFAULT_DUCKDUCKGO_TIMEOUT_SECONDS: float = 15.0 DEFAULT_DUCKDUCKGO_REGION: str = "us-en" DEFAULT_DUCKDUCKGO_SAFESEARCH: str = "moderate" +# The SearXNG provider (#3927). The categories are those of the engines that the manifest keeps: the +# general engines, the technical ones (`it`) and the scientific ones (`science`). The live check of +# #3929 holds them to the pinned image. The reply holds the text of up to 20 results, so the cap +# leaves room. +DEFAULT_SEARXNG_CATEGORIES: str = "general,it,science" +DEFAULT_SEARXNG_TIMEOUT_SECONDS: float = 30.0 +DEFAULT_SEARXNG_MAX_REPLY_BYTES: int = 1024 * 1024 # 1 MiB # ── AI Page Text Defaults (Crawl4AI service) ──────────────────────────────────── # Seconds that the Crawl4AI service may take to load and convert one page. Its own wall-clock diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index 09d6cd23f7..3dcf3b3c08 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -1321,7 +1321,7 @@ class SearchConfig(BaseModel): model_config = ConfigDict(extra="ignore", validate_assignment=True, hide_input_in_errors=True) providers: Annotated[list[SearchProviderName], Variable()] = Field( - description="The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped, and `searxng` is skipped until its provider exists (#3927). A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers", + description="The providers of web search, in the order that a search asks them: `searxng`, `duckduckgo` or `firecrawl`. A provider that is not configured is skipped: `searxng` without `search.searxng_url`, and `firecrawl` without its key. A search goes to the next provider when one fails or returns no hit, and the first provider with a hit answers", default_factory=lambda: list(DEFAULT_SEARCH_PROVIDERS), ) language: Annotated[str, Variable()] = Field( @@ -1329,6 +1329,14 @@ class SearchConfig(BaseModel): default=DEFAULT_SEARCH_LANGUAGE, min_length=2, ) + searxng_url: Annotated[HttpUrlStr | None, Variable()] = Field( + default=None, + description="Address of the SearXNG service for web search, such as " + "`http://searxng.devops.svc.cluster.local:8080` in the cluster, or `http://127.0.0.1:8080` " + "on a workstation after `kubectl port-forward -n devops svc/searxng 8080:8080`. A cluster " + "address needs `ai.allow_private_network`. It has no default, and `searxng` is skipped " + "without it", + ) class Settings(BaseSettings): diff --git a/src/devops_cli/roadmap/request_plan.py b/src/devops_cli/roadmap/request_plan.py index 73e654fcd6..7362e35397 100644 --- a/src/devops_cli/roadmap/request_plan.py +++ b/src/devops_cli/roadmap/request_plan.py @@ -468,7 +468,7 @@ def alternatives_requests( PlannedRequest( method=methods["search"].format(provider=provider.name), target=texts.plan_targets["web_search"].format(subject=subject), - argv=("POST", provider.url), + argv=(provider.method, provider.url), repeat=rep["search"].format(limit=CONST_ROADMAP_ALTERNATIVES_MAX_SEARCHES), ) ] diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index c148f46963..48ad1cc91a 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -235,7 +235,7 @@ class Instrument: "provider that returned hits, empty for one that returned none, the HTTP status of a provider " "that refused the search, such as 402 when the account has no credits or 429 at its rate " "limit, degraded for a reply that the provider could not read, error for a provider that " - "did not answer, refused for a query that the guard stopped, and exhausted for a search that " + "did not answer, refused for a query that the guard stopped or an address that the egress check refused, and exhausted for a search that " "no provider answered. The backend of the last two is none", ) CRAWL4AI_FETCHES_TOTAL = Instrument( diff --git a/tests/ai/test_web_search.py b/tests/ai/test_web_search.py index 7e7800d775..4e089b05df 100644 --- a/tests/ai/test_web_search.py +++ b/tests/ai/test_web_search.py @@ -560,7 +560,7 @@ def test_each_provider_has_its_name_and_the_url_of_its_request() -> None: def test_the_registry_holds_a_provider_for_each_name_that_has_one() -> None: - assert sorted(chain.PROVIDERS) == ["duckduckgo", "firecrawl"] + assert sorted(chain.PROVIDERS) == ["duckduckgo", "firecrawl", "searxng"] def test_the_warning_level_is_the_only_level_of_a_failed_attempt( diff --git a/tests/ai/test_web_search_searxng.py b/tests/ai/test_web_search_searxng.py new file mode 100644 index 0000000000..fe2001ac1f --- /dev/null +++ b/tests/ai/test_web_search_searxng.py @@ -0,0 +1,386 @@ +"""Unit tests for the SearXNG provider of the web search chain (#3927). + +The provider sends `GET {search.searxng_url}/search` with `format=json` and reads the `results` of +the reply. The address comes from the setting only, and the client dials a loopback address, or a +private one when `ai.allow_private_network` is set. A reply with a redirect is a failure: SearXNG +answers a query that starts with `!` with a redirect. The reply fixture holds the shape that the +SearXNG search API documents; the live check of #3929 holds the provider to a reply of the pinned +image. +""" + +from __future__ import annotations + +import json +import logging +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import httpx2 +import pytest + +from devops_cli.ai.web_search import PROVIDERS, SearchHit, SearxngProvider, web_search +from devops_cli.config.defaults import DEFAULT_SEARXNG_MAX_REPLY_BYTES +from devops_cli.config.settings import Settings +from devops_cli.exceptions.ai import SearchFailed +from devops_cli.exceptions.config import ConfigurationError +from devops_cli.exceptions.security import SSRFBlockedError +from devops_cli.telemetry.instruments import WEB_SEARCHES_TOTAL +from tests.support.fakes.dns import DnsFake +from tests.support.fakes.http import WebFake +from tests.support.fakes.otlp import FakeCollector + +pytestmark = pytest.mark.usefixtures("keyring_store") + +_REPLY = Path(__file__).parents[1] / "fixtures" / "searxng" / "search_reply.json" +_LOOPBACK = "http://127.0.0.1:8080" +_SERVICE = "http://searxng.devops.svc.cluster.local:8080" +_SERVICE_ADDRESS = "10.0.0.5" +_QUERY = "private roadmap query" +_FROM_FIXTURE = [ + SearchHit("https://example.com/pydantic-ai", "Pydantic AI", "Agents for Python.", "searxng"), + SearchHit("https://example.com/ruff", "Ruff", "A linter.", "searxng"), + SearchHit("https://example.com/mypy", "Mypy", "A type checker.", "searxng"), +] +_DUCKDUCKGO = "https://html.duckduckgo.com/html/" + + +def _reply(**changes: Any) -> bytes: + return json.dumps({**json.loads(_REPLY.read_text(encoding="utf-8")), **changes}).encode() + + +def _answers(web: WebFake, status: int = 200, body: bytes | None = None) -> None: + """Answer every `GET /search` with `status` and `body`, the fixture by default.""" + content = _reply() if body is None else body + + def serve(request: httpx2.Request) -> httpx2.Response | None: + if request.url.path != "/search": + return None + return httpx2.Response( + status, headers={"content-type": "application/json"}, content=content + ) + + web.serve(serve) + + +def _search_fails() -> None: + """Run the search and check that it raised `SearchFailed`, which no provider answered.""" + with pytest.raises(SearchFailed) as raised: + web_search(_QUERY) + assert raised.value.error_code == "WEB_SEARCH_FAILED" + + +def _points(otlp: FakeCollector) -> list[tuple[dict[str, Any], float]]: + return otlp.points(WEB_SEARCHES_TOTAL.name) + + +def _count(backend: str, result: str) -> tuple[dict[str, str], float]: + return ({"backend": backend, "result": result}, 1.0) + + +@pytest.fixture +def searxng(config: Callable[..., Any], monkeypatch: pytest.MonkeyPatch) -> Callable[..., None]: + """Make `searxng` the first provider, at `url`. The test floor sets `ai.allow_private_network` + through its variable; the fixture clears it unless the test passes `private`.""" + + def apply( + url: str | None = _LOOPBACK, *, then: tuple[str, ...] = (), private: bool = False + ) -> None: + monkeypatch.setenv("DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK", str(private).lower()) + config( + search={"providers": ["searxng", *then], "searxng_url": url}, + firecrawl={"api_key": None}, + ) + + return apply + + +def test_a_good_reply_gives_hits_with_the_provider_tag( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng() + _answers(web) + + hits = web_search(_QUERY) + + assert (hits, _points(otlp)) == (_FROM_FIXTURE, [_count("searxng", "ok")]) + + +def test_the_request_is_a_get_of_the_search_path_with_the_json_format( + web: WebFake, searxng: Callable[..., None], config: Callable[..., Any] +) -> None: + searxng() + config(search={"language": "de"}) + _answers(web) + + web_search(_QUERY) + + request = web.sent[0] + assert (request.method, request.url.path, dict(request.url.params), request.content) == ( + "GET", + "/search", + { + "q": _QUERY, + "format": "json", + "language": "de", + "categories": "general,it,science", + "pageno": "1", + }, + b"", + ) + + +def test_the_hits_are_cut_to_the_cap(web: WebFake, searxng: Callable[..., None]) -> None: + searxng() + _answers(web) + + assert web_search(_QUERY, limit=2) == _FROM_FIXTURE[:2] + + +def test_a_result_with_no_url_or_not_an_object_is_dropped( + web: WebFake, searxng: Callable[..., None] +) -> None: + searxng() + results = [ + "text", + {"title": "No URL", "content": "None."}, + {"url": "https://example.com/a", "title": "A", "content": "First."}, + {"url": "https://example.com/b"}, + ] + _answers(web, body=_reply(results=results)) + + assert web_search(_QUERY) == [ + SearchHit("https://example.com/a", "A", "First.", "searxng"), + SearchHit("https://example.com/b", "", "", "searxng"), + ] + + +@pytest.mark.parametrize("status", [403, 429, 500, 503]) +def test_a_status_other_than_200_is_a_failure_with_the_status_as_the_result( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None], status: int +) -> None: + searxng() + _answers(web, status=status, body=b"no") + + _search_fails() + + assert _points(otlp) == [_count("searxng", str(status)), _count("none", "exhausted")] + + +def test_a_failed_search_passes_on_to_the_next_provider( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng(then=("duckduckgo",)) + _answers(web, status=429) + web.respond("POST", _DUCKDUCKGO, 500, "error") + + _search_fails() + + assert _points(otlp) == [ + _count("searxng", "429"), + _count("duckduckgo", "500"), + _count("none", "exhausted"), + ] + + +def test_an_empty_result_list_with_an_unresponsive_engine_is_degraded( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng() + _answers(web, body=_reply(results=[], unresponsive_engines=[["duckduckgo", "Suspended"]])) + + _search_fails() + + assert _points(otlp) == [_count("searxng", "degraded"), _count("none", "exhausted")] + + +def test_an_empty_result_list_with_no_unresponsive_engine_is_empty( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng() + _answers(web, body=_reply(results=[], unresponsive_engines=[])) + + assert (web_search(_QUERY), _points(otlp)) == ([], [_count("searxng", "empty")]) + + +def test_a_result_list_with_an_unresponsive_engine_still_gives_its_hits( + web: WebFake, searxng: Callable[..., None] +) -> None: + searxng() + _answers(web, body=_reply(unresponsive_engines=[["github", "HTTP error"]])) + + assert web_search(_QUERY) == _FROM_FIXTURE + + +@pytest.mark.parametrize( + "body", + [b"not json", b'["a", "list"]', b'{"query": "q"}', b'{"results": "none"}'], + ids=["not-json", "not-an-object", "no-results", "results-not-a-list"], +) +def test_a_reply_that_is_not_a_result_object_is_degraded( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None], body: bytes +) -> None: + searxng() + _answers(web, body=body) + + _search_fails() + + assert _points(otlp) == [_count("searxng", "degraded"), _count("none", "exhausted")] + + +def test_a_reply_over_the_byte_cap_is_degraded( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng() + padding = "x" * DEFAULT_SEARXNG_MAX_REPLY_BYTES + _answers(web, body=_reply(answers=[padding])) + + _search_fails() + + assert _points(otlp) == [_count("searxng", "degraded"), _count("none", "exhausted")] + + +def test_a_redirect_is_a_failure_and_no_second_request_is_sent( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + """SearXNG answers a query that starts with a bang with a redirect to the site of the bang.""" + searxng() + web.serve( + lambda request: httpx2.Response(302, headers={"location": "https://example.com/elsewhere"}) + ) + + _search_fails() + + assert (len(web.sent), _points(otlp)) == ( + 1, + [_count("searxng", "302"), _count("none", "exhausted")], + ) + + +def test_a_failed_attempt_logs_the_status_and_never_the_query_or_the_address( + web: WebFake, searxng: Callable[..., None], caplog: pytest.LogCaptureFixture +) -> None: + searxng() + _answers(web, status=503) + + with caplog.at_level(logging.WARNING, logger="devops_cli.ai.web_search"): + _search_fails() + + assert [r.getMessage() for r in caplog.records if r.name == "devops_cli.ai.web_search"] == [ + "A web search failed on searxng: HTTP 503." + ] + + +def test_a_service_that_does_not_answer_passes_the_search_on_and_counts_error( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + searxng() + + def refuse(request: httpx2.Request) -> httpx2.Response | None: + raise httpx2.ConnectError("Connection refused", request=request) + + web.serve(refuse) + + _search_fails() + + assert _points(otlp) == [_count("searxng", "error"), _count("none", "exhausted")] + + +@pytest.mark.parametrize("url", [None]) +def test_with_no_address_the_provider_is_not_configured_and_is_skipped( + web: WebFake, otlp: FakeCollector, searxng: Callable[..., None], url: str | None +) -> None: + searxng(url, then=("duckduckgo",)) + web.respond("POST", _DUCKDUCKGO, 500, "error") + + _search_fails() + + assert (web.requested, _points(otlp)) == ( + [_DUCKDUCKGO], + [_count("duckduckgo", "500"), _count("none", "exhausted")], + ) + assert SearxngProvider().configured(Settings(search={"searxng_url": url})) is False + + +def test_a_direct_call_with_no_address_names_the_setting( + web: WebFake, searxng: Callable[..., None] +) -> None: + searxng(None) + + with pytest.raises(ConfigurationError, match=r"search\.searxng_url") as raised: + SearxngProvider().search(_QUERY, limit=5) + + assert (raised.value.key, web.sent) == ("search.searxng_url", []) + + +def test_a_workstation_address_on_loopback_needs_no_flag( + web: WebFake, searxng: Callable[..., None] +) -> None: + searxng("http://localhost:8080") + _answers(web) + + assert web_search(_QUERY) == _FROM_FIXTURE + + +def test_a_cluster_service_address_needs_the_private_network_flag( + web: WebFake, dns: DnsFake, searxng: Callable[..., None] +) -> None: + dns.add("searxng.devops.svc.cluster.local", _SERVICE_ADDRESS) + searxng(_SERVICE) + _answers(web) + + with pytest.raises(SSRFBlockedError) as raised: + SearxngProvider().search(_QUERY, limit=5) + + assert (raised.value.error_code, web.sent) == ("SSRF_BLOCKED", []) + + +def test_a_cluster_service_address_works_with_the_private_network_flag( + web: WebFake, dns: DnsFake, searxng: Callable[..., None] +) -> None: + dns.add("searxng.devops.svc.cluster.local", _SERVICE_ADDRESS) + searxng(_SERVICE, private=True) + _answers(web) + + assert web_search(_QUERY) == _FROM_FIXTURE + + +def test_an_address_that_the_egress_check_refuses_passes_the_search_on_and_counts_refused( + web: WebFake, dns: DnsFake, otlp: FakeCollector, searxng: Callable[..., None] +) -> None: + dns.add("searxng.devops.svc.cluster.local", _SERVICE_ADDRESS) + searxng(_SERVICE, then=("duckduckgo",)) + web.respond("POST", _DUCKDUCKGO, 500, "error") + + _search_fails() + + assert _points(otlp) == [ + _count("searxng", "refused"), + _count("duckduckgo", "500"), + _count("none", "exhausted"), + ] + + +def test_a_path_in_the_address_stays_and_an_end_slash_goes( + web: WebFake, searxng: Callable[..., None] +) -> None: + searxng(f"{_LOOPBACK}/") + _answers(web) + + web_search(_QUERY) + + assert web.sent[0].url.path == "/search" + + +def test_the_provider_is_listed_and_its_url_is_the_search_endpoint_of_the_setting( + searxng: Callable[..., None], +) -> None: + searxng() + + provider = PROVIDERS["searxng"] + + assert (provider.name, provider.method, provider.url) == ( + "searxng", + "GET", + f"{_LOOPBACK}/search", + ) diff --git a/tests/fixtures/searxng/search_reply.json b/tests/fixtures/searxng/search_reply.json new file mode 100644 index 0000000000..105ca9aeb4 --- /dev/null +++ b/tests/fixtures/searxng/search_reply.json @@ -0,0 +1,53 @@ +{ + "query": "pydantic ai agents", + "number_of_results": 0, + "results": [ + { + "url": "https://example.com/pydantic-ai", + "title": "Pydantic AI", + "content": "Agents for Python.", + "engine": "duckduckgo", + "parsed_url": ["https", "example.com", "/pydantic-ai", "", "", ""], + "template": "default.html", + "engines": ["duckduckgo", "wikipedia"], + "positions": [1, 2], + "score": 9.0, + "category": "general", + "thumbnail": null, + "publishedDate": null + }, + { + "url": "https://example.com/ruff", + "title": "Ruff", + "content": "A linter.", + "engine": "github", + "parsed_url": ["https", "example.com", "/ruff", "", "", ""], + "template": "default.html", + "engines": ["github"], + "positions": [1], + "score": 3.0, + "category": "it", + "thumbnail": null, + "publishedDate": null + }, + { + "url": "https://example.com/mypy", + "title": "Mypy", + "content": "A type checker.", + "engine": "pypi", + "parsed_url": ["https", "example.com", "/mypy", "", "", ""], + "template": "default.html", + "engines": ["pypi"], + "positions": [1], + "score": 1.0, + "category": "it", + "thumbnail": null, + "publishedDate": null + } + ], + "answers": [], + "corrections": [], + "infoboxes": [], + "suggestions": [], + "unresponsive_engines": [] +} diff --git a/tests/roadmap/test_roadmap_dry_runs.py b/tests/roadmap/test_roadmap_dry_runs.py index 270007323f..5d1b76ba36 100644 --- a/tests/roadmap/test_roadmap_dry_runs.py +++ b/tests/roadmap/test_roadmap_dry_runs.py @@ -428,6 +428,23 @@ def test_the_alternatives_dry_run_lists_the_gh_command_and_the_url_of_each_reque ) == (AlternativesPlan, True, True, True, True, True, True, True, {"model call"}) +def test_the_alternatives_dry_run_lists_the_get_of_the_searxng_search_when_it_is_first( + config: Callable[..., Any], +) -> None: + """The method of the request comes from the provider: SearXNG searches with GET (#3927).""" + from devops_cli.roadmap.alternatives import dry_run_alternatives + + config(search={"providers": ["searxng", "duckduckgo"], "searxng_url": "http://127.0.0.1:8080"}) + + plan = dry_run_alternatives(REPO, item=7) + + argvs = [request.argv for request in plan.requests] + assert ( + ("GET", "http://127.0.0.1:8080/search") in argvs, + ("POST", "https://html.duckduckgo.com/html/") in argvs, + ) == (True, False) + + def test_the_alternatives_dry_run_lists_the_reads_of_the_adrs() -> None: """The run lists `docs/adr` and each file of it once for the run, when it checks an item that is no skip class (#3505).""" From 7412de1831a0816c71b6183481af79be1d649e23 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 7 Nov 2026 13:02:17 +0000 Subject: [PATCH 2/3] test(ai): declare the SearXNG variable and read the fixture by its support path --- tests/ai/test_web_search_searxng.py | 4 ++-- tests/security/test_config_declarations.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/ai/test_web_search_searxng.py b/tests/ai/test_web_search_searxng.py index fe2001ac1f..eb43371bcf 100644 --- a/tests/ai/test_web_search_searxng.py +++ b/tests/ai/test_web_search_searxng.py @@ -13,7 +13,6 @@ import json import logging from collections.abc import Callable -from pathlib import Path from typing import Any import httpx2 @@ -29,10 +28,11 @@ from tests.support.fakes.dns import DnsFake from tests.support.fakes.http import WebFake from tests.support.fakes.otlp import FakeCollector +from tests.support.paths import FIXTURES pytestmark = pytest.mark.usefixtures("keyring_store") -_REPLY = Path(__file__).parents[1] / "fixtures" / "searxng" / "search_reply.json" +_REPLY = FIXTURES / "searxng" / "search_reply.json" _LOOPBACK = "http://127.0.0.1:8080" _SERVICE = "http://searxng.devops.svc.cluster.local:8080" _SERVICE_ADDRESS = "10.0.0.5" diff --git a/tests/security/test_config_declarations.py b/tests/security/test_config_declarations.py index 85164a9462..05b3af2b8d 100644 --- a/tests/security/test_config_declarations.py +++ b/tests/security/test_config_declarations.py @@ -144,6 +144,7 @@ "DEVOPS_CLI_SERVICE_MODEL_CALL_CONCURRENCY", # #2564 "DEVOPS_CLI_SEARCH_LANGUAGE", # #3925 "DEVOPS_CLI_SEARCH_PROVIDERS", # #3925 + "DEVOPS_CLI_SEARCH_SEARXNG_URL", # #3927 "DEVOPS_CLI_ROADMAP_STAGE_STEP_TOKENS", # #2654 "DEVOPS_CLI_ROADMAP_STAGE_PLANNED_LIMIT", # #3487 "DEVOPS_CLI_AI_TASK_STAGE_MODEL", # #3207 From c61c8a5fd0edfb9e860a86421f25b01eca0c286c Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 7 Nov 2026 13:02:29 +0000 Subject: [PATCH 3/3] docs(openspec): archive the SearXNG provider change --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/web-search/spec.md | 0 .../tasks.md | 0 openspec/specs/web-search/spec.md | 68 ++++++++++++++++++- 6 files changed, 67 insertions(+), 1 deletion(-) rename openspec/changes/{3927-searxng-search-provider => archive/2026-11-07-3927-searxng-search-provider}/.openspec.yaml (100%) rename openspec/changes/{3927-searxng-search-provider => archive/2026-11-07-3927-searxng-search-provider}/design.md (100%) rename openspec/changes/{3927-searxng-search-provider => archive/2026-11-07-3927-searxng-search-provider}/proposal.md (100%) rename openspec/changes/{3927-searxng-search-provider => archive/2026-11-07-3927-searxng-search-provider}/specs/web-search/spec.md (100%) rename openspec/changes/{3927-searxng-search-provider => archive/2026-11-07-3927-searxng-search-provider}/tasks.md (100%) diff --git a/openspec/changes/3927-searxng-search-provider/.openspec.yaml b/openspec/changes/archive/2026-11-07-3927-searxng-search-provider/.openspec.yaml similarity index 100% rename from openspec/changes/3927-searxng-search-provider/.openspec.yaml rename to openspec/changes/archive/2026-11-07-3927-searxng-search-provider/.openspec.yaml diff --git a/openspec/changes/3927-searxng-search-provider/design.md b/openspec/changes/archive/2026-11-07-3927-searxng-search-provider/design.md similarity index 100% rename from openspec/changes/3927-searxng-search-provider/design.md rename to openspec/changes/archive/2026-11-07-3927-searxng-search-provider/design.md diff --git a/openspec/changes/3927-searxng-search-provider/proposal.md b/openspec/changes/archive/2026-11-07-3927-searxng-search-provider/proposal.md similarity index 100% rename from openspec/changes/3927-searxng-search-provider/proposal.md rename to openspec/changes/archive/2026-11-07-3927-searxng-search-provider/proposal.md diff --git a/openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md b/openspec/changes/archive/2026-11-07-3927-searxng-search-provider/specs/web-search/spec.md similarity index 100% rename from openspec/changes/3927-searxng-search-provider/specs/web-search/spec.md rename to openspec/changes/archive/2026-11-07-3927-searxng-search-provider/specs/web-search/spec.md diff --git a/openspec/changes/3927-searxng-search-provider/tasks.md b/openspec/changes/archive/2026-11-07-3927-searxng-search-provider/tasks.md similarity index 100% rename from openspec/changes/3927-searxng-search-provider/tasks.md rename to openspec/changes/archive/2026-11-07-3927-searxng-search-provider/tasks.md diff --git a/openspec/specs/web-search/spec.md b/openspec/specs/web-search/spec.md index 852def161b..7a6902af0d 100644 --- a/openspec/specs/web-search/spec.md +++ b/openspec/specs/web-search/spec.md @@ -91,8 +91,74 @@ The requests of DuckDuckGo and Firecrawl SHALL go through the HTTP entry point a - **THEN** the counter has a point with the backend `duckduckgo` and the result `degraded`, and the search goes on ### Requirement: The settings name the providers and the language -The section `search` of the settings SHALL have `providers`, a list of `searxng`, `duckduckgo` and `firecrawl` with the default `searxng`, `duckduckgo`, `firecrawl`, and `language`, with the default `en`. An unknown provider name SHALL be a validation error. The variables SHALL be `DEVOPS_CLI_SEARCH_PROVIDERS` and `DEVOPS_CLI_SEARCH_LANGUAGE`. The text of `providers` SHALL say that `searxng` is skipped until its provider exists. +The section `search` of the settings SHALL have `providers`, a list of `searxng`, `duckduckgo` and `firecrawl` with the default `searxng`, `duckduckgo`, `firecrawl`, `language`, with the default `en`, and `searxng_url`, with no default. An unknown provider name SHALL be a validation error. The variables SHALL be `DEVOPS_CLI_SEARCH_PROVIDERS`, `DEVOPS_CLI_SEARCH_LANGUAGE` and `DEVOPS_CLI_SEARCH_SEARXNG_URL`. The text of `providers` SHALL say that `searxng` is skipped without `search.searxng_url`. #### Scenario: An unknown provider - **WHEN** the settings are built with the providers `duckduckgo` and `bing` - **THEN** the settings raise a validation error that names `providers` + +#### Scenario: The address has no default +- **WHEN** the settings are built with no value for `search.searxng_url` +- **THEN** `search.searxng_url` is not set + +### Requirement: The SearXNG provider is configured by its address +The provider `searxng` SHALL be configured when `search.searxng_url` is set, and SHALL be skipped without it. A direct call without the setting SHALL raise `ConfigurationError` that names `search.searxng_url`. + +#### Scenario: No address +- **WHEN** `search.searxng_url` is not set +- **THEN** no request reaches SearXNG and the counter has no point with the backend `searxng` + +### Requirement: The SearXNG provider searches with a JSON request +The provider SHALL send `GET
/search` with `q`, `format=json`, `language` (the value of `search.language`), `categories` and `pageno=1`. It SHALL map each item of `results` that has a `url` to a hit with `url`, `title`, `content` as the snippet, and the provider `searxng`. + +#### Scenario: A good reply +- **WHEN** the providers are `searxng` and the service answers with three results +- **THEN** `web_search` returns three hits with the provider `searxng`, and the counter has a point with the backend `searxng` and the result `ok` + +#### Scenario: The request +- **WHEN** a search runs for a query with `search.language` set to `de` +- **THEN** one `GET` reaches `/search` with the parameters `q`, `format=json`, `language=de`, `categories` and `pageno=1` + +### Requirement: The SearXNG client dials by the configured egress level +The provider SHALL send its request through the HTTP entry point at the configured level: loopback, or private when `ai.allow_private_network` is set. + +#### Scenario: A loopback address +- **WHEN** `search.searxng_url` is a loopback address and `ai.allow_private_network` is off +- **THEN** the search reaches the service + +#### Scenario: A cluster address +- **WHEN** `search.searxng_url` is a cluster Service address that resolves to a private address and `ai.allow_private_network` is off +- **THEN** a direct call raises `SSRFBlockedError` and no request is sent, and with the setting on the search reaches the service + +### Requirement: The SearXNG client follows no redirect and reads a capped reply +The provider SHALL follow no redirect and SHALL read at most 1 MiB of a reply. A reply with a status other than 200, a redirect included, SHALL count with the status as the result and SHALL pass the search on. + +#### Scenario: A status other than 200 +- **WHEN** the service answers HTTP 403, 429 or 503 +- **THEN** the counter has a point with the backend `searxng` and that status as the result, and the next provider is asked + +#### Scenario: A redirect +- **WHEN** the service answers HTTP 302 +- **THEN** one request was sent, and the counter has a point with the backend `searxng` and the result `302` + +### Requirement: A SearXNG reply that cannot answer passes the search on +A reply over the byte cap, a reply that is not a JSON object with a `results` list, and a reply with no result and a non-empty `unresponsive_engines` SHALL count as `degraded`. A reply with no result and an empty `unresponsive_engines` SHALL count as `empty`. An address that the egress check refuses SHALL count as `refused`. Each SHALL pass the search on. + +#### Scenario: Engines that did not answer +- **WHEN** the service answers with an empty `results` and a non-empty `unresponsive_engines` +- **THEN** the counter has a point with the backend `searxng` and the result `degraded` + +#### Scenario: No result +- **WHEN** the service answers with an empty `results` and an empty `unresponsive_engines` +- **THEN** the counter has a point with the backend `searxng` and the result `empty` + +#### Scenario: A refused address +- **WHEN** the egress check refuses the address of the service +- **THEN** the counter has a point with the backend `searxng` and the result `refused`, and the next provider is asked + +### Requirement: The dry run lists the method of the first provider +The dry run of `devops roadmap alternatives` SHALL list the method and the URL of the request of the first configured provider. + +#### Scenario: SearXNG is first +- **WHEN** `searxng` is the first configured provider +- **THEN** the dry run lists `GET` with the search endpoint of the service, and no request to DuckDuckGo