Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ repos:
rev: 26.3.1
hooks:
- id: black
# The hook runs on the changed files repo-wide (excluding autobot-infrastructure/); the gate
# checks autobot-backend/ autobot-slm-backend/ autobot_shared/ only, the code CI owns. The
# arguments match (--line-length=120), so a file in both sets is formatted the same way by
# either. A file outside the three package dirs is formatted by the hook alone (#21839).
args: [--line-length=120]
language_version: python3.14
exclude: ^autobot-infrastructure/
Expand Down
21 changes: 4 additions & 17 deletions autobot-backend/api/agent_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from autobot_shared.logging_manager import get_logger
from autobot_shared.ssot_config import config
from autobot_shared.time_utils import parse_utc_iso
from services.agent_config_writer import write_agent_enabled, write_agent_model
from services.config_revision_service import ConfigRevisionService
from services.config_service import ConfigService
from services.slm_client import get_slm_client
Expand Down Expand Up @@ -1053,17 +1054,7 @@ async def _apply_agent_model_update(

Returns the ``updated_config`` dict ready for the API response.
"""
base = DEFAULT_AGENT_CONFIGS[agent_id]
before_config = {
"model": config_manager.get_nested(f"agents.{agent_id}.model", base["default_model"]),
"provider": config_manager.get_nested(f"agents.{agent_id}.provider", base["provider"]),
}

# Persist changes
config_manager.set_nested(f"agents.{agent_id}.model", update.model)
if update.provider:
config_manager.set_nested(f"agents.{agent_id}.provider", update.provider)
config_manager.save_settings()
before_config = write_agent_model(config_manager, agent_id, DEFAULT_AGENT_CONFIGS[agent_id], update)
ConfigService.clear_cache()

# Issue #1747: Record audit revision
Expand Down Expand Up @@ -1157,9 +1148,7 @@ async def enable_agent(

from config import config_manager

before_enabled = config_manager.get_nested(f"agents.{agent_id}.enabled", True)
config_manager.set_nested(f"agents.{agent_id}.enabled", True)
config_manager.save_settings()
before_enabled = write_agent_enabled(config_manager, agent_id, True)
ConfigService.clear_cache()

# Issue #1747: Record audit revision
Expand Down Expand Up @@ -1206,9 +1195,7 @@ async def disable_agent(

from config import config_manager

before_enabled = config_manager.get_nested(f"agents.{agent_id}.enabled", True)
config_manager.set_nested(f"agents.{agent_id}.enabled", False)
config_manager.save_settings()
before_enabled = write_agent_enabled(config_manager, agent_id, False)
ConfigService.clear_cache()

# Issue #1747: Record audit revision
Expand Down
124 changes: 124 additions & 0 deletions autobot-backend/api/agent_config_write_lock_21742_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""An agent-config edit and a rollback serialise under the one config write lock (#21742)."""

import threading
from types import SimpleNamespace

import config as config_pkg
from api.agent_config import DEFAULT_AGENT_CONFIGS
from services import config_rollback
from services.agent_config_writer import write_agent_enabled, write_agent_model
from services.config_rollback import rollback_locked

_AGENT = next(iter(DEFAULT_AGENT_CONFIGS))
_BASE = DEFAULT_AGENT_CONFIGS[_AGENT]


#: Longest the test waits to see the second writer NOT enter. Only the negative check is bounded by time;
#: the ordering itself comes from the events below.
_NEGATIVE_WAIT_SECONDS = 0.3
_PARK_TIMEOUT_SECONDS = 10


class _ParkingStore:
"""Settings store whose first write parks inside the locked operation until released."""

def __init__(self):
self.values = {}
self.owners = []
self.parked = threading.Event()
self.release = threading.Event()
self.second_entered = threading.Event()
self._first = None

def get_nested(self, key, default=None):
return self.values.get(key, default)

def set_nested(self, key, value):
me = threading.current_thread().name
self.owners.append(me)
if self._first is None:
self._first = me
self.parked.set()
assert self.release.wait(_PARK_TIMEOUT_SECONDS), "writer A was never released"
elif me != self._first:
self.second_entered.set()
self.values[key] = value

def save_settings(self):
pass


class _Workers:
"""Threads that capture their exception and re-raise it from ``join``."""

def __init__(self):
self.errors = []
self.threads = []

def start(self, name, target):
def run():
try:
target()
except BaseException as exc: # noqa: BLE001 - re-raised in join()
self.errors.append(exc)

thread = threading.Thread(target=run, name=name)
self.threads.append(thread)
thread.start()

def join(self):
for thread in self.threads:
thread.join(_PARK_TIMEOUT_SECONDS)
assert not thread.is_alive(), f"{thread.name} did not finish"
if self.errors:
raise self.errors[0]


def _run_serialised(store, writer_a, writer_b):
"""Park A inside its locked write, start B, prove B has not entered, release A, join both."""
workers = _Workers()
workers.start("writer-a", writer_a)
assert store.parked.wait(_PARK_TIMEOUT_SECONDS), "writer A never reached its write"
workers.start("writer-b", writer_b)
entered = store.second_entered.wait(_NEGATIVE_WAIT_SECONDS)
store.release.set()
workers.join()
assert not entered, "writer B entered its write while writer A held the config write lock"


def test_agent_edit_and_rollback_do_not_lose_either_write(monkeypatch):
store = _ParkingStore()
monkeypatch.setattr(config_pkg, "config_manager", store)
monkeypatch.setattr(config_rollback.ConfigService, "clear_cache", lambda: None)
update = SimpleNamespace(model="edited", provider="edited-provider")
snapshot = {"model": "rolled-back", "provider": "rolled-provider", "enabled": False}

_run_serialised(
store,
lambda: write_agent_model(store, _AGENT, _BASE, update),
lambda: rollback_locked("agent", _AGENT, snapshot),
)

assert store.owners.index("writer-b") > max(i for i, o in enumerate(store.owners) if o == "writer-a")
assert store.values[f"agents.{_AGENT}.enabled"] is False
pair = (store.values[f"agents.{_AGENT}.model"], store.values[f"agents.{_AGENT}.provider"])
assert pair == ("rolled-back", "rolled-provider"), f"B ran second, so its pair must win: {pair}"


def test_two_agent_edits_do_not_interleave():
store = _ParkingStore()
update = SimpleNamespace(model="m", provider="p")
_run_serialised(
store,
lambda: write_agent_model(store, _AGENT, _BASE, update),
lambda: write_agent_enabled(store, _AGENT, False),
)
assert store.values == {
f"agents.{_AGENT}.model": "m",
f"agents.{_AGENT}.provider": "p",
f"agents.{_AGENT}.enabled": False,
}
5 changes: 3 additions & 2 deletions autobot-backend/code_analysis/src/env_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from autobot_shared.async_compat import run_or_schedule
from autobot_shared.logging_manager import get_logger
from autobot_shared.ollama_urls import ollama_generate_url, ollama_tags_url
from autobot_shared.slug import sanitize_token
from autobot_shared.ssot_config import QUALITY_MODEL, config
from autobot_shared.ssot_constants import TTL_1_HOUR
Expand Down Expand Up @@ -1312,7 +1313,7 @@ async def llm_filter_hardcoded(

ollama_host = config.ollama_host
ollama_port = config.port.ollama
ollama_url = f"http://{ollama_host}:{ollama_port}/api/generate"
ollama_url = ollama_generate_url(f"http://{ollama_host}:{ollama_port}")

candidates = self._select_llm_candidates(hardcoded_values, priority_filter)
if not candidates:
Expand Down Expand Up @@ -1358,7 +1359,7 @@ async def _check_ollama_health(self, host: str, port: str) -> bool:
try:
async with get_http_client().tracked_request(
"GET",
f"http://{host}:{port}/api/tags",
ollama_tags_url(f"http://{host}:{port}"),
timeout=aiohttp.ClientTimeout(total=5),
suppress_error_log=True,
) as resp:
Expand Down
6 changes: 4 additions & 2 deletions autobot-backend/config/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
from typing import Any, Dict

from autobot_shared import deployment_profile
from autobot_shared.ollama_urls import ollama_api_url, ollama_generate_url
from autobot_shared.ssot_config import config
from autobot_shared.ssot_constants import PATH_OLLAMA_EMBEDDINGS
from config.registry import ConfigRegistry


Expand All @@ -40,7 +42,7 @@ def _get_backend_config(llm_host: str, llm_port: int, bind_host: str, backend_po
"provider": "ollama",
"providers": {
"ollama": {
"endpoint": f"{llm_base_url}/api/generate",
"endpoint": ollama_generate_url(llm_base_url),
"host": llm_base_url,
"models": [],
"selected_model": config.llm.default_model or ModelConstants.DEFAULT_OLLAMA_MODEL,
Expand All @@ -51,7 +53,7 @@ def _get_backend_config(llm_host: str, llm_port: int, bind_host: str, backend_po
"provider": "ollama",
"providers": {
"ollama": {
"endpoint": f"{llm_base_url}/api/embeddings",
"endpoint": ollama_api_url(llm_base_url, PATH_OLLAMA_EMBEDDINGS),
"host": llm_base_url,
"models": [],
# #20008: the configured default, not the override. This runs while logging starts, as early as
Expand Down
8 changes: 4 additions & 4 deletions autobot-backend/config/model_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import logging # stdlib: avoids deadlock — config is on the logging-manager init path (GH#7765 pattern)
from typing import Any, Dict, Tuple

from autobot_shared.ollama_urls import ollama_generate_url
from autobot_shared.ssot_config import config

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -98,6 +99,7 @@ def _create_default_llm_structure(self) -> Dict[str, Any]:
# Lazy import to avoid circular dependency
from constants.network_constants import NetworkConstants

local_host = f"http://{NetworkConstants.LOCALHOST_NAME}:{NetworkConstants.OLLAMA_PORT}"
return {
"provider_type": "local",
"local": {
Expand All @@ -106,10 +108,8 @@ def _create_default_llm_structure(self) -> Dict[str, Any]:
"ollama": {
"selected_model": self.get_selected_model(),
"models": [],
"endpoint": (
f"http://{NetworkConstants.LOCALHOST_NAME}" f":{NetworkConstants.OLLAMA_PORT}/api/generate"
),
"host": (f"http://{NetworkConstants.LOCALHOST_NAME}" f":{NetworkConstants.OLLAMA_PORT}"),
"endpoint": ollama_generate_url(local_host),
"host": local_host,
}
},
},
Expand Down
35 changes: 35 additions & 0 deletions autobot-backend/services/agent_config_writer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Agent-config read-modify-write under the one config write lock (#21742).

Each writer holds ``services.config_write_lock.CONFIG_WRITE_LOCK`` for its whole
read, write and save, so a concurrent edit or rollback cannot interleave. Synchronous
and lock-holding: never call these while holding an await point open.
"""

from services.config_write_lock import locked_config_write


@locked_config_write
def write_agent_model(config_manager, agent_id: str, base: dict, update) -> dict:
"""Write the new model/provider, save, and return the prior values; *base* holds the defaults."""
before_config = {
"model": config_manager.get_nested(f"agents.{agent_id}.model", base["default_model"]),
"provider": config_manager.get_nested(f"agents.{agent_id}.provider", base["provider"]),
}
config_manager.set_nested(f"agents.{agent_id}.model", update.model)
if update.provider:
config_manager.set_nested(f"agents.{agent_id}.provider", update.provider)
config_manager.save_settings()
return before_config


@locked_config_write
def write_agent_enabled(config_manager, agent_id: str, enabled: bool) -> bool:
"""Write the enabled flag, save, and return the prior flag."""
before_enabled = config_manager.get_nested(f"agents.{agent_id}.enabled", True)
config_manager.set_nested(f"agents.{agent_id}.enabled", enabled)
config_manager.save_settings()
return before_enabled
9 changes: 5 additions & 4 deletions autobot-backend/services/config_write_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

Held for the whole read-modify-write of ``ConfigService.update_llm_config``,
``update_redis_config``, ``save_full_config`` and ``update_backend_settings``,
and by the config rollback across its live read, apply and read. Reentrant, so
the inner ``_save_config_to_file`` takes it again on the same thread. It does
not cover writes made straight through ``config_manager`` (for example the
agent-config routes), and is a threading lock: never hold it across an await.
the agent-config writes (model/provider update, enable, disable; #21742), and by
the config rollback across its live read, apply and read. Reentrant, so the inner
``_save_config_to_file`` takes it again on the same thread. It does not cover
writes made straight through ``config_manager`` by other routes (developer,
embeddings, auth; #21858), and is a threading lock: never hold it across an await.
"""

import functools
Expand Down
4 changes: 3 additions & 1 deletion autobot-backend/services/npu_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
from autobot_shared.http_client import get_http_client
from autobot_shared.http_egress_guard import assert_egress_policy
from autobot_shared.logging_manager import get_logger
from autobot_shared.ollama_urls import ollama_api_url
from autobot_shared.ssot_config import config, get_config
from autobot_shared.ssot_constants import PATH_OLLAMA_EMBEDDINGS
from services.npu_worker_routing import npu_worker_urls, worker_attempts

logger = get_logger(__name__)
Expand Down Expand Up @@ -496,7 +498,7 @@ async def generate_embedding_with_fallback(
# config.port.ollama is the canonical path for the port (MVA-1454 / 6c0726ec1).
ollama_host = ollama_host or config.ollama_host
ollama_port = ollama_port or config.port.ollama
ollama_url = f"http://{ollama_host}:{ollama_port}/api/embeddings"
ollama_url = ollama_api_url(f"http://{ollama_host}:{ollama_port}", PATH_OLLAMA_EMBEDDINGS)

last_reason = "no attempts made"
for attempt in range(1, max_attempts + 1):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@
import asyncio
import json
import logging
import sys
import time
from pathlib import Path

import aiohttp

# Runs from any directory with no PYTHONPATH: the repository root goes on the path for `autobot_shared` (#18289).
_REPO_ROOT = Path(__file__).resolve().parents[4]
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))

from autobot_shared.network_constants import ServiceURLs # noqa: E402
from autobot_shared.ollama_urls import ollama_chat_url # noqa: E402

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -117,7 +127,7 @@ async def _process_streaming_response(response, stream_timeout: float = 10.0, ma

async def test_ollama_streaming():
"""Test the exact same request that hangs in the backend (Issue #315: refactored)."""
url = "http://127.0.0.1:11434/api/chat"
url = ollama_chat_url(ServiceURLs.OLLAMA_LOCAL)
headers = {"Content-Type": "application/json"}
data = _build_test_request_data()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
from pathlib import Path
from typing import Any, Dict, List, Tuple

from autobot_shared.paths import project_root
from autobot_shared.network_constants import ServiceURLs
from autobot_shared.ollama_urls import ollama_tags_url
from autobot_shared.paths import project_root
from autobot_shared.redis_client import RedisDatabase, require_redis_client

# The sibling helper module lives beside this script; put its directory on the path so the import
Expand Down Expand Up @@ -182,7 +183,7 @@ async def get_available_models(self) -> List[str]:

async with httpx.AsyncClient() as client:
response = await client.get(
"%s/api/tags" % self.ollama_base_url,
ollama_tags_url(self.ollama_base_url),
)
if response.status_code == 200:
data = response.json()
Expand Down
Loading
Loading