Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /als-apg_osprey /tests /interfaces /ariel /test_routes.py
"""Tests for ARIEL web API routes."""
from __future__ import annotations
import types
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from osprey.interfaces.ariel.api import routes
from osprey.services.ariel_search.config import ARIELConfig
from osprey.services.ariel_search.search.base import SearchToolDescriptor
def _build_mock_registry():
"""Build a mock registry that provides ARIEL search modules and pipelines."""
registry = MagicMock()
# Build mock search modules
keyword_mod = types.ModuleType("keyword")
keyword_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="keyword_search",
description="Full-text keyword search",
search_mode="keyword",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
)
keyword_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
semantic_mod = types.ModuleType("semantic")
semantic_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="semantic_search",
description="Semantic similarity search",
search_mode="semantic",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
needs_embedder=True,
)
semantic_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
# Registered but left disabled by the shared fixture config, so it stays out
# of every existing test's capabilities; the hybrid tests enable it locally.
hybrid_mod = types.ModuleType("hybrid")
hybrid_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="hybrid_search",
description="Hybrid retrieval with optional reranking",
search_mode="hybrid",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
)
hybrid_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
registry.list_ariel_search_modules.return_value = ["keyword", "semantic", "hybrid"]
registry.get_ariel_search_module.side_effect = lambda n: {
"keyword": keyword_mod,
"semantic": semantic_mod,
"hybrid": hybrid_mod,
}.get(n)
return registry
def _enable_hybrid(service) -> None:
"""Give the mock service a config in which the hybrid module is enabled.
Applied per test rather than in the shared ``mock_ariel_service`` fixture,
whose config several other tests assert against verbatim.
"""
service.config = ARIELConfig.from_dict(
{
"database": {"uri": "postgresql://localhost:5432/test"},
"search_modules": {
"keyword": {"enabled": True},
"semantic": {"enabled": True, "model": "test-model"},
"hybrid": {"enabled": True},
},
"default_search_mode": "keyword",
}
)
@pytest.fixture(autouse=True)
def _mock_registry():
"""Provide a mock registry for all ARIEL route tests."""
registry = _build_mock_registry()
with patch(
"osprey.registry.get_registry",
return_value=registry,
):
yield
@pytest.fixture
def mock_ariel_service():
"""Mock ARIEL service."""
service = AsyncMock()
service.health_check = AsyncMock(return_value=(True, "Service healthy"))
service.repository = AsyncMock()
# Provide a real config so /api/capabilities works
service.config = ARIELConfig.from_dict(
{
"database": {"uri": "postgresql://localhost:5432/test"},
"search_modules": {
"keyword": {"enabled": True},
"semantic": {"enabled": True, "model": "test-model"},
},
}
)
# Mock search result
mock_result = MagicMock()
mock_result.entries = []
mock_result.answer = "Test answer"
mock_result.sources = []
mock_result.search_modes_used = []
mock_result.reasoning = ""
service.search = AsyncMock(return_value=mock_result)
# Mock status
mock_status = MagicMock()
mock_status.healthy = True
mock_status.database_connected = True
mock_status.database_uri = "postgresql://localhost/ariel"
mock_status.entry_count = 100
mock_status.embedding_tables = []
mock_status.active_embedding_model = "text-embedding-3-small"
mock_status.enabled_search_modules = ["keyword", "semantic"]
mock_status.enabled_enhancement_modules = []
mock_status.last_ingestion = None
mock_status.errors = []
service.get_status = AsyncMock(return_value=mock_status)
return service
@pytest.fixture
def test_app(mock_ariel_service):
"""Create a test FastAPI app with mocked service."""
app = FastAPI()
# Add the router
app.include_router(routes.router)
# Mock the service in app state
app.state.ariel_service = mock_ariel_service
return app
@pytest.fixture
def client(test_app):
"""Create test client."""
return TestClient(test_app)
def test_search_endpoint_basic(client, mock_ariel_service):
"""Test basic search endpoint."""
response = client.post(
"/api/search",
json={
"query": "test query",
"mode": "keyword",
"max_results": 10,
},
)
assert response.status_code == 200
data = response.json()
assert "entries" in data
assert "answer" in data
assert data["answer"] == "Test answer"
assert "execution_time_ms" in data
# Verify service was called
mock_ariel_service.search.assert_called_once()
def test_search_endpoint_with_time_range(client, mock_ariel_service):
"""Test search with time range filter."""
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "keyword",
"max_results": 5,
"start_date": "2024-01-01T00:00:00",
"end_date": "2024-12-31T23:59:59",
},
)
assert response.status_code == 200
# Check that time_range was passed to service
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["time_range"] is not None
def test_list_entries_endpoint(client, mock_ariel_service):
"""Test list entries endpoint."""
# Mock repository methods
mock_ariel_service.repository.count_entries = AsyncMock(return_value=100)
mock_ariel_service.repository.search_by_time_range = AsyncMock(return_value=[])
response = client.get("/api/entries?page=1&page_size=20")
assert response.status_code == 200
data = response.json()
assert "entries" in data
assert "total" in data
assert data["total"] == 100
assert "page" in data
assert "page_size" in data
assert "total_pages" in data
def test_list_entries_passes_pagination_and_filters(client, mock_ariel_service):
"""list_entries forwards offset (derived from page) and author/source filters
to the repository, instead of silently dropping page/author/source_system."""
mock_ariel_service.repository.count_entries = AsyncMock(return_value=100)
mock_ariel_service.repository.search_by_time_range = AsyncMock(return_value=[])
response = client.get("/api/entries?page=3&page_size=20&author=alice&source_system=ALS")
assert response.status_code == 200
_args, kwargs = mock_ariel_service.repository.search_by_time_range.call_args
assert kwargs["limit"] == 20
assert kwargs["offset"] == 40 # (page - 1) * page_size
assert kwargs["author"] == "alice"
assert kwargs["source_system"] == "ALS"
# total_pages must reflect the filtered set, so count_entries gets the same
# author/source filters (not an unfiltered whole-table count).
_cargs, ckwargs = mock_ariel_service.repository.count_entries.call_args
assert ckwargs["author"] == "alice"
assert ckwargs["source_system"] == "ALS"
def test_get_entry_endpoint(client, mock_ariel_service):
"""Test get single entry endpoint."""
# Mock entry
mock_entry = {
"entry_id": "test-123",
"source_system": "Test",
"timestamp": datetime.now(),
"author": "Test Author",
"raw_text": "Test entry content",
"attachments": [],
"metadata": {},
"created_at": datetime.now(),
"updated_at": datetime.now(),
"summary": None,
"keywords": [],
}
mock_ariel_service.repository.get_entry = AsyncMock(return_value=mock_entry)
response = client.get("/api/entries/test-123")
assert response.status_code == 200
data = response.json()
assert data["entry_id"] == "test-123"
assert data["author"] == "Test Author"
def test_get_entry_not_found(client, mock_ariel_service):
"""Test get entry returns 404 when not found."""
mock_ariel_service.repository.get_entry = AsyncMock(return_value=None)
response = client.get("/api/entries/nonexistent")
assert response.status_code == 404
assert "not found" in response.json()["detail"]
def test_create_entry_endpoint_via_service(client, mock_ariel_service):
"""Test create entry delegates to service.create_entry()."""
from osprey.services.ariel_search.models import (
FacilityEntryCreateResult,
SyncStatus,
)
mock_ariel_service.create_entry = AsyncMock(
return_value=FacilityEntryCreateResult(
entry_id="local-abc123def456",
source_system="Generic JSON",
sync_status=SyncStatus.LOCAL_ONLY,
message="Entry local-abc123def456 created in Generic JSON",
)
)
response = client.post(
"/api/entries",
json={
"subject": "Test Entry",
"details": "Test details",
"author": "Test Author",
"logbook": "Test Logbook",
"tags": ["test", "example"],
},
)
assert response.status_code == 200
data = response.json()
assert data["entry_id"] == "local-abc123def456"
assert data["sync_status"] == "local_only"
assert data["source_system"] == "Generic JSON"
assert "message" in data
# Verify service.create_entry was called (not repository directly)
mock_ariel_service.create_entry.assert_called_once()
def test_create_entry_endpoint_fallback(client, mock_ariel_service):
"""Test create entry falls back to direct DB insert when adapter doesn't support writes."""
mock_ariel_service.create_entry = AsyncMock(
side_effect=NotImplementedError("Adapter does not support writes")
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
response = client.post(
"/api/entries",
json={
"subject": "Test Entry",
"details": "Test details",
"author": "Test Author",
"logbook": "Test Logbook",
"tags": ["test", "example"],
},
)
assert response.status_code == 200
data = response.json()
assert data["entry_id"].startswith("ariel-")
assert data["sync_status"] == "local_only"
assert data["source_system"] == "ARIEL Web"
assert "saved locally" in data["message"]
# Verify fallback path used repository directly
mock_ariel_service.repository.upsert_entry.assert_called_once()
def test_create_entry_auth_required_returns_401(client, mock_ariel_service):
"""Missing logbook credentials surface as 401 auth_required, NOT a local save.
This is the core of the fix: AuthenticationRequiredError must not be conflated
with the read-only-adapter fallback, so nothing is saved and the UI can prompt.
"""
from osprey.services.ariel_search.exceptions import AuthenticationRequiredError
mock_ariel_service.create_entry = AsyncMock(
side_effect=AuthenticationRequiredError(
"OLOG publishing requires credentials.",
source_system="ALS eLog",
)
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
response = client.post(
"/api/entries",
json={"subject": "Test", "details": "Test details"},
)
assert response.status_code == 401
body = response.json()
assert body["code"] == "auth_required"
assert "credentials" in body["detail"].lower()
# Nothing was saved locally.
mock_ariel_service.repository.upsert_entry.assert_not_called()
def test_create_entry_publish_failure_returns_502(client, mock_ariel_service):
"""A genuine publish failure surfaces an error, NOT a silent local save."""
from osprey.services.ariel_search.exceptions import IngestionError
mock_ariel_service.create_entry = AsyncMock(
side_effect=IngestionError(
"ALS olog write failed with HTTP 403: bad password",
source_system="ALS eLog",
)
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
response = client.post(
"/api/entries",
json={"subject": "Test", "details": "Test details"},
)
assert response.status_code == 502
assert "publish failed" in response.json()["detail"].lower()
mock_ariel_service.repository.upsert_entry.assert_not_called()
def _upload_files():
"""A single small file payload for multipart upload tests."""
return [("files", ("shot.png", b"\x89PNG\r\n\x1a\nfakeimage", "image/png"))]
def test_upload_auth_required_returns_401(client, mock_ariel_service):
"""Attachment-bearing submit also prompts for credentials instead of saving local."""
from osprey.services.ariel_search.exceptions import AuthenticationRequiredError
mock_ariel_service.create_entry = AsyncMock(
side_effect=AuthenticationRequiredError("creds required", source_system="ALS eLog")
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
mock_ariel_service.repository.store_attachment = AsyncMock()
response = client.post(
"/api/entries/upload",
data={"subject": "Test", "details": "Body"},
files=_upload_files(),
)
assert response.status_code == 401
assert response.json()["code"] == "auth_required"
# Nothing persisted: no entry, no attachment.
mock_ariel_service.repository.upsert_entry.assert_not_called()
mock_ariel_service.repository.store_attachment.assert_not_called()
def test_upload_publish_failure_returns_502(client, mock_ariel_service):
"""Upload route surfaces a real publish failure instead of saving local-only."""
from osprey.services.ariel_search.exceptions import IngestionError
mock_ariel_service.create_entry = AsyncMock(
side_effect=IngestionError("olog down", source_system="ALS eLog")
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
mock_ariel_service.repository.store_attachment = AsyncMock()
response = client.post(
"/api/entries/upload",
data={"subject": "Test", "details": "Body"},
files=_upload_files(),
)
assert response.status_code == 502
mock_ariel_service.repository.store_attachment.assert_not_called()
def test_upload_falls_back_local_with_attachments(client, mock_ariel_service):
"""Read-only adapter: upload saves local AND stores its attachments."""
mock_ariel_service.create_entry = AsyncMock(
side_effect=NotImplementedError("Adapter does not support writes")
)
mock_ariel_service.repository.upsert_entry = AsyncMock()
mock_ariel_service.repository.store_attachment = AsyncMock()
mock_ariel_service.repository.get_entry = AsyncMock(
return_value={
"entry_id": "ariel-xyz",
"source_system": "ARIEL Web",
"timestamp": datetime.now(),
"author": "Anonymous",
"raw_text": "Test\n\nBody",
"attachments": [],
"metadata": {},
}
)
response = client.post(
"/api/entries/upload",
data={"subject": "Test", "details": "Body"},
files=_upload_files(),
)
assert response.status_code == 200
data = response.json()
assert data["sync_status"] == "local_only"
assert data["attachment_count"] == 1
mock_ariel_service.repository.store_attachment.assert_called_once()
def test_upload_publish_success_stores_attachments_locally(client, mock_ariel_service):
"""Published entry: text goes to OLOG, files stay in ARIEL (API can't take files)."""
from osprey.services.ariel_search.models import FacilityEntryCreateResult, SyncStatus
mock_ariel_service.create_entry = AsyncMock(
return_value=FacilityEntryCreateResult(
entry_id="99999",
source_system="ALS eLog",
sync_status=SyncStatus.PENDING_SYNC,
message="Entry 99999 created in ALS eLog",
)
)
mock_ariel_service.repository.store_attachment = AsyncMock()
mock_ariel_service.repository.upsert_entry = AsyncMock()
mock_ariel_service.repository.get_entry = AsyncMock(
return_value={
"entry_id": "99999",
"source_system": "ALS eLog",
"timestamp": datetime.now(),
"author": "op",
"raw_text": "Test\n\nBody",
"attachments": [],
"metadata": {},
}
)
response = client.post(
"/api/entries/upload",
data={"subject": "Test", "details": "Body", "auth_user": "op", "auth_password": "pw"},
files=_upload_files(),
)
assert response.status_code == 200
data = response.json()
assert data["entry_id"] == "99999"
assert data["sync_status"] == "pending_sync"
assert data["attachment_count"] == 1
# Files were stored in ARIEL and the operator is told they were not published.
mock_ariel_service.repository.store_attachment.assert_called_once()
assert "ariel" in data["message"].lower()
def _mock_adapter(*, supports_write, requires_write_auth, source_system):
adapter = MagicMock()
adapter.supports_write = supports_write
adapter.requires_write_auth = requires_write_auth
adapter.source_system_name = source_system
return adapter
def test_publish_info_requires_auth(client, mock_ariel_service):
"""A write adapter that needs credentials reports requires_auth=True."""
adapter = _mock_adapter(supports_write=True, requires_write_auth=True, source_system="ALS eLog")
with patch("osprey.services.ariel_search.ingestion.get_adapter", return_value=adapter):
response = client.get("/api/publish-info")
assert response.status_code == 200
data = response.json()
assert data["supports_write"] is True
assert data["requires_auth"] is True
assert data["source_system"] == "ALS eLog"
def test_publish_info_no_auth(client, mock_ariel_service):
"""A no-auth write adapter reports requires_auth=False (publishes without creds)."""
adapter = _mock_adapter(
supports_write=True, requires_write_auth=False, source_system="Generic JSON"
)
with patch("osprey.services.ariel_search.ingestion.get_adapter", return_value=adapter):
response = client.get("/api/publish-info")
data = response.json()
assert data["supports_write"] is True
assert data["requires_auth"] is False
def test_publish_info_read_only(client, mock_ariel_service):
"""A read-only adapter reports requires_auth=False — credentials are irrelevant."""
adapter = _mock_adapter(
supports_write=False, requires_write_auth=True, source_system="JLab Logbook"
)
with patch("osprey.services.ariel_search.ingestion.get_adapter", return_value=adapter):
response = client.get("/api/publish-info")
data = response.json()
assert data["supports_write"] is False
assert data["requires_auth"] is False
def test_publish_info_no_adapter_configured(client, mock_ariel_service):
"""No ingestion adapter configured degrades gracefully to read-only."""
response = client.get("/api/publish-info")
assert response.status_code == 200
data = response.json()
assert data["supports_write"] is False
assert data["requires_auth"] is False
def test_status_endpoint(client, mock_ariel_service):
"""Test status endpoint."""
response = client.get("/api/status")
assert response.status_code == 200
data = response.json()
assert data["healthy"] is True
assert data["database_connected"] is True
assert data["entry_count"] == 100
assert data["active_embedding_model"] == "text-embedding-3-small"
assert "keyword" in data["enabled_search_modules"]
def test_entry_to_response_helper():
"""Test _entry_to_response helper function."""
entry = {
"entry_id": "test-123",
"source_system": "Test",
"timestamp": datetime(2024, 1, 1, 12, 0, 0),
"author": "Test Author",
"raw_text": "Test content",
"attachments": [],
"metadata": {"key": "value"},
"created_at": datetime(2024, 1, 1, 12, 0, 0),
"updated_at": datetime(2024, 1, 1, 12, 0, 0),
"summary": "Test summary",
"keywords": ["test"],
}
result = routes._entry_to_response(entry, score=0.95, highlights=["highlight1"])
assert result.entry_id == "test-123"
assert result.author == "Test Author"
assert result.score == 0.95
assert result.highlights == ["highlight1"]
assert result.metadata == {"key": "value"}
@pytest.mark.parametrize("mode", ["keyword", "semantic"])
def test_search_enabled_mode_reaches_service(client, mock_ariel_service, mode):
"""An enabled module name is forwarded to the service verbatim."""
response = client.post(
"/api/search",
json={"query": "test", "mode": mode, "max_results": 10},
)
assert response.status_code == 200
assert mock_ariel_service.search.call_args.kwargs["mode"] == mode
def test_search_unknown_mode_rejected_with_available_modes(client, mock_ariel_service):
"""An unknown mode is a 400 listing the enabled modes, not a silent fallback.
The API used to map anything it did not recognize onto keyword search, so a
typo returned plausible-looking results for the wrong mode.
"""
response = client.post(
"/api/search",
json={"query": "test", "mode": "keywrod", "max_results": 10},
)
assert response.status_code == 400
detail = response.json()["detail"]
assert "Unknown search mode 'keywrod'" in detail
assert "keyword" in detail.split("Available modes:")[1]
assert "semantic" in detail.split("Available modes:")[1]
mock_ariel_service.search.assert_not_called()
def test_search_blank_mode_rejected(client, mock_ariel_service):
"""A malformed (blank) mode is rejected before the service is consulted."""
response = client.post(
"/api/search",
json={"query": "test", "mode": " ", "max_results": 10},
)
assert response.status_code == 400
assert "search mode cannot be empty" in response.json()["detail"]
mock_ariel_service.search.assert_not_called()
def test_capabilities_endpoint(client):
"""Test capabilities endpoint returns valid structure."""
response = client.get("/api/capabilities")
assert response.status_code == 200
data = response.json()
assert "categories" in data
assert "shared_parameters" in data
assert "direct" in data["categories"]
# Should have keyword and semantic in direct category
direct_names = [m["name"] for m in data["categories"]["direct"]["modes"]]
assert "keyword" in direct_names
assert "semantic" in direct_names
# Shared parameters should include max_results
param_names = [p["name"] for p in data["shared_parameters"]]
assert "max_results" in param_names
def test_search_with_advanced_params(client, mock_ariel_service):
"""Test that advanced_params are forwarded to service."""
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "keyword",
"max_results": 10,
"advanced_params": {"temperature": 0.5, "similarity_threshold": 0.8},
},
)
assert response.status_code == 200
# Verify advanced_params were forwarded
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["advanced_params"] == {
"temperature": 0.5,
"similarity_threshold": 0.8,
}
def test_search_defaults_to_keyword_mode(client, mock_ariel_service):
"""Test that omitting mode defaults to KEYWORD."""
response = client.post(
"/api/search",
json={
"query": "test",
"max_results": 10,
},
)
assert response.status_code == 200
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["mode"] == "keyword"
def test_search_honors_configured_default_mode(client, mock_ariel_service):
"""Omitting mode follows ariel.default_search_mode, not a fixed name."""
mock_ariel_service.config = ARIELConfig.from_dict(
{
"database": {"uri": "postgresql://localhost:5432/test"},
"search_modules": {
"keyword": {"enabled": True},
"semantic": {"enabled": True, "model": "test-model"},
},
"default_search_mode": "semantic",
}
)
response = client.post("/api/search", json={"query": "test", "max_results": 10})
assert response.status_code == 200
assert mock_ariel_service.search.call_args.kwargs["mode"] == "semantic"
@pytest.mark.parametrize("value", ["yes", "false", 1, 0, 1.0, []])
def test_search_hybrid_rejects_non_boolean_rerank(client, mock_ariel_service, value):
"""A non-boolean ``rerank`` override is a 400, not a truthiness accident.
The panel sends the toggle's boolean, but a hand-written caller can send
``"false"`` -- which is truthy everywhere downstream and would silently run
the slow reranked path the caller asked to skip.
"""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "hybrid",
"max_results": 10,
"advanced_params": {"rerank": value},
},
)
assert response.status_code == 400
detail = response.json()["detail"]
assert "rerank must be a boolean" in detail
assert repr(value) in detail
mock_ariel_service.search.assert_not_called()
@pytest.mark.parametrize("value", [0, -1, "40", 12.5, True])
def test_search_hybrid_rejects_bad_candidate_limit(client, mock_ariel_service, value):
"""``candidate_limit`` must be a positive int -- booleans and zero included."""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "hybrid",
"max_results": 10,
"advanced_params": {"candidate_limit": value},
},
)
assert response.status_code == 400
detail = response.json()["detail"]
assert "candidate_limit must be a positive integer" in detail
assert repr(value) in detail
mock_ariel_service.search.assert_not_called()
def test_search_hybrid_forwards_valid_overrides_verbatim(client, mock_ariel_service):
"""Well-formed overrides reach the service untouched -- ``False`` included.
``rerank: false`` is the whole point of the override, so it must survive as
the boolean ``False`` rather than being dropped as falsy.
"""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "hybrid",
"max_results": 10,
"advanced_params": {"rerank": False, "candidate_limit": 12},
},
)
assert response.status_code == 200
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["mode"] == "hybrid"
assert call_kwargs["advanced_params"]["rerank"] is False
assert call_kwargs["advanced_params"]["candidate_limit"] == 12
def test_search_hybrid_without_overrides_is_accepted(client, mock_ariel_service):
"""Absent keys mean "use the configured default" and are not rejected."""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={"query": "test", "mode": "hybrid", "max_results": 10},
)
assert response.status_code == 200
assert mock_ariel_service.search.call_args.kwargs["mode"] == "hybrid"
def test_search_hybrid_accepts_explicit_null_overrides(client, mock_ariel_service):
"""An explicit ``null`` says "no override" just as an absent key does."""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "hybrid",
"max_results": 10,
"advanced_params": {"rerank": None, "candidate_limit": None},
},
)
assert response.status_code == 200
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["advanced_params"]["rerank"] is None
assert call_kwargs["advanced_params"]["candidate_limit"] is None
@pytest.mark.parametrize("mode", ["keyword", "semantic"])
def test_search_non_hybrid_modes_ignore_hybrid_overrides(client, mock_ariel_service, mode):
"""The check is hybrid-only: other modes never see these keys as theirs.
``rerank`` and ``candidate_limit`` are hybrid's parameter names. Another
module is free to give them any meaning, so validating them everywhere
would reject requests this route has no business judging.
"""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": mode,
"max_results": 10,
"advanced_params": {"rerank": "yes", "candidate_limit": 0},
},
)
assert response.status_code == 200
call_kwargs = mock_ariel_service.search.call_args.kwargs
assert call_kwargs["advanced_params"]["rerank"] == "yes"
assert call_kwargs["advanced_params"]["candidate_limit"] == 0
def test_search_hybrid_leaves_expand_query_alone(client, mock_ariel_service):
"""Only the two hybrid keys are judged; ``expand_query`` passes through."""
_enable_hybrid(mock_ariel_service)
response = client.post(
"/api/search",
json={
"query": "test",
"mode": "hybrid",
"max_results": 10,
"advanced_params": {"expand_query": "yes", "rerank": True},
},
)
assert response.status_code == 200
assert mock_ariel_service.search.call_args.kwargs["advanced_params"]["expand_query"] == "yes"
def test_capabilities_advertises_default_mode(client, mock_ariel_service):
"""The capabilities payload carries the mode the UI should open on."""
response = client.get("/api/capabilities")
assert response.status_code == 200
assert response.json()["default_mode"] == "keyword"
def test_put_config_backs_up_into_the_state_zone(client, tmp_path):
"""ARIEL's config save copies the old file into the agent-data state zone.
Not beside ``config.yml``. That file lives in the render, which the container
split makes root-owned: creating a *new* file next to it needs write
permission on the render directory that the admin image will not have, and
the backup runs before a byte of the save is written -- so the old sibling
scheme would have turned every ARIEL config save in that image into a 500.
Anchored on the directory the route already resolves its config path in.
"""
from osprey.utils.config_writer import config_backup_path
config_path = tmp_path / "config.yml"
original = "project_name: original\n"
config_path.write_text(original)
client.app.state.config_path = config_path
response = client.put("/api/config", json={"content": "project_name: updated\n"})
assert response.status_code == 200
assert config_path.read_text() == "project_name: updated\n"
backup = config_backup_path(config_path)
assert backup.read_text() == original
assert backup.parent.name == "config-backups"
# The point of the move: nothing new lands next to the config itself.
assert not (tmp_path / "config.yml.bak").exists()
assert [f.name for f in tmp_path.iterdir() if f.suffix == ".bak"] == []
def test_put_config_backup_follows_a_relocated_agent_data_root(client, tmp_path):
"""The zone is read from the config being written, never assumed.
Resolved from the *pre-write* file, which is the only reading that makes
sense: the backup is a copy of what is there now, so it belongs in the zone
that config names now.
The saved document carries ``agent_data`` through unchanged, because it has
to: ``agent_data.*`` is in the protected set, so a body that dropped it
would be refused before the backup ran and this would stop being a test of
where the backup lands.
"""
from osprey.utils.config_writer import config_backup_path
relocated = tmp_path / "elsewhere" / "state"
config_path = tmp_path / "config.yml"
original = f"agent_data:\n base_dir: {relocated}\nproject_name: original\n"
config_path.write_text(original)
expected = config_backup_path(config_path)
assert expected == relocated / "config-backups" / "config.yml.bak"
client.app.state.config_path = config_path
response = client.put(
"/api/config",
json={"content": original.replace("project_name: original", "project_name: updated")},
)
assert response.status_code == 200
assert expected.read_text() == original
assert not (tmp_path / "var").exists()
# --------------------------------------------------------------------------
# PUT /api/config and the protected set
#
# ARIEL's Raw YAML save replaces the whole document, so it is the widest write
# surface onto the file that carries the write gate, the approval gate and the
# paths the safety layers derive their zones from. It is gated exactly the way
# the Web Terminal's ``PUT /api/config`` is -- same protected set, same 403,
# same ``http_config`` audit record -- because the protected set is
# consulted by *every* framework writer, not just the terminal's.
# --------------------------------------------------------------------------
_PROTECTED_DOC = (
"agent_data:\n"
" base_dir: {state}\n"
"control_system:\n"
" writes_enabled: false\n"
"project_name: original\n"
)
@pytest.fixture
def audit_zone(tmp_path, monkeypatch):
"""Redirect the audit zone. ``writer.audit_dir`` is the ledger's one seam."""
from osprey.audit import writer
zone = tmp_path / "audit-zone" / "var" / "audit"
monkeypatch.setattr(writer, "audit_dir", lambda: zone)
return zone
def _audit_records(zone):
import json
from osprey.audit.protected import SURFACE_HTTP_CONFIG
from osprey.utils.identity import acting_identity
path = zone / acting_identity() / f"{SURFACE_HTTP_CONFIG}.jsonl"
if not path.is_file():
return []
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
@pytest.fixture
def gated_config(client, tmp_path):
"""A config.yml carrying protected keys, wired into the ARIEL app state."""
config_path = tmp_path / "config.yml"
config_path.write_text(_PROTECTED_DOC.format(state=tmp_path / "state"))
client.app.state.config_path = config_path
return config_path
def test_put_config_refuses_a_removed_protected_key(client, gated_config, audit_zone):
"""Dropping ``agent_data`` on the way past is a protected-key change, not a save."""
before = gated_config.read_bytes()
response = client.put(
"/api/config",
json={"content": "control_system:\n writes_enabled: false\nproject_name: updated\n"},
)
assert response.status_code == 403
detail = response.json()["detail"]
assert "agent_data.base_dir" in detail
assert "config.yml is unchanged" in detail
# The operator is pointed at the channel that *can* carry the change.
assert "`config:` block" in detail
# Byte-identical: no write, and no backup either -- a backup is a copy of a
# file this request may turn out not to be allowed to replace.
assert gated_config.read_bytes() == before
assert not (gated_config.parent / "state").exists()
records = _audit_records(audit_zone)
assert len(records) == 1
assert records[0]["surface"] == "http_config"
assert "target=config.yml" in records[0]["detail"]
assert records[0]["subject"] == "agent_data.base_dir"
assert records[0]["reason"] == "protected_key"
def test_put_config_refuses_a_changed_protected_value(client, gated_config, audit_zone):
"""Flipping the write gate through the YAML editor is the write that must not land."""
before = gated_config.read_bytes()
flipped = _PROTECTED_DOC.format(state=gated_config.parent / "state").replace(
"writes_enabled: false", "writes_enabled: true"
)
response = client.put("/api/config", json={"content": flipped})
assert response.status_code == 403
assert "control_system.writes_enabled" in response.json()["detail"]
assert gated_config.read_bytes() == before
records = _audit_records(audit_zone)
assert [r["subject"] for r in records] == ["control_system.writes_enabled"]
def test_put_config_refusal_leaks_no_value(client, gated_config, audit_zone):
"""Config values are secrets; a refusal reports the key, never the value."""
import json as _j
sentinel = "qqzzSENTINELvalue77"
planted = _PROTECTED_DOC.format(state=sentinel)
response = client.put("/api/config", json={"content": planted})
assert response.status_code == 403
assert sentinel not in response.text
assert sentinel not in _j.dumps(_audit_records(audit_zone))
def test_put_config_allows_an_unprotected_edit(client, gated_config, audit_zone):
"""An edit that leaves every protected key alone still saves, and still backs up."""
from osprey.utils.config_writer import config_backup_path
before = gated_config.read_text()
updated = before.replace("project_name: original", "project_name: updated")
response = client.put("/api/config", json={"content": updated})
assert response.status_code == 200
assert gated_config.read_text() == updated
assert config_backup_path(gated_config).read_text() == before
assert _audit_records(audit_zone) == []
class TestConfigPanelTierGate:
"""``web.config_panel.enabled: false`` closes the settings editor's server surface."""
def test_get_config_is_refused_when_the_panel_is_disabled(self, client, gated_config):
"""A read is gated too: the document carries the provider base_urls."""
client.app.state.config_panel_enabled = False
response = client.get("/api/config")
assert response.status_code == 403
assert "web.config_panel.enabled" in response.json()["detail"]
def test_put_config_is_refused_when_the_panel_is_disabled(self, client, gated_config):
"""The write is refused before the file is read, so nothing changes."""
before = gated_config.read_bytes()
client.app.state.config_panel_enabled = False
response = client.put("/api/config", json={"content": "project_name: updated\n"})
assert response.status_code == 403
assert "web.config_panel.enabled" in response.json()["detail"]
assert gated_config.read_bytes() == before
def test_the_gate_runs_before_the_protected_set(self, client, gated_config):
"""A disabled panel never gets as far as having a key to judge."""
client.app.state.config_panel_enabled = False
response = client.put(
"/api/config",
json={"content": "control_system:\n writes_enabled: false\nproject_name: x\n"},
)
assert response.status_code == 403
assert "agent_data.base_dir" not in response.json()["detail"]
def test_an_absent_key_leaves_the_panel_open(self, client, gated_config):
"""An app whose lifespan never set the flag behaves as it always did."""
assert not hasattr(client.app.state, "config_panel_enabled")
assert client.get("/api/config").status_code == 200
def test_capabilities_reports_the_gate(self, client):
"""The frontend gets the flag it needs to drop the Settings entry."""
client.app.state.config_panel_enabled = False
payload = client.get("/api/capabilities").json()
assert payload["config_panel_enabled"] is False
def test_capabilities_reports_an_open_panel_by_default(self, client):
"""No flag on app.state reads as open, matching the server's own default."""
payload = client.get("/api/capabilities").json()
assert payload["config_panel_enabled"] is True
"""Tests for ARIEL web API routes."""
from __future__ import annotations
import types
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from osprey.interfaces.ariel.api import routes
from osprey.services.ariel_search.config import ARIELConfig
from osprey.services.ariel_search.search.base import SearchToolDescriptor
def _build_mock_registry():
"""Build a mock registry that provides ARIEL search modules and pipelines."""
registry = MagicMock()
# Build mock search modules
keyword_mod = types.ModuleType("keyword")
keyword_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="keyword_search",
description="Full-text keyword search",
search_mode="keyword",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
)
keyword_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
semantic_mod = types.ModuleType("semantic")
semantic_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="semantic_search",
description="Semantic similarity search",
search_mode="semantic",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
needs_embedder=True,
)
semantic_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
# Registered but left disabled by the shared fixture config, so it stays out
# of every existing test's capabilities; the hybrid tests enable it locally.
hybrid_mod = types.ModuleType("hybrid")
hybrid_mod.get_tool_descriptor = lambda: SearchToolDescriptor( # type: ignore[attr-defined]
name="hybrid_search",
description="Hybrid retrieval with optional reranking",
search_mode="hybrid",
args_schema=MagicMock(),
execute=AsyncMock(),
format_result=MagicMock(),
)
hybrid_mod.get_parameter_descriptors = None # type: ignore[attr-defined]
registry.list_ariel_search_modules.return_value = ["keyword", "semantic", "hybrid"]
registry.get_ariel_search_module.side_effect = lambda n: {
"keyword": keyword_mod,
"semantic": semantic_mod,
"hybrid": hybrid_mod,
}.get(n)
return registry
def _enable_hybrid(service) -> None:
"""Give the mock service a config in which the hybrid module is enabled.
Applied per test rather than in the shared ``mock_ariel_service`` fixture,
whose config several other tests assert against verbatim.
"""
service.config = ARIELConfig.from_dict(
{
"database": {"uri": "postgresql://localhost:5432/test"},
"search_modules": {
"keyword": {"enabled": True},
"semantic": {"enabled": True, "model": "test-model"},
"hybrid": {"enabled": True},
},
"default_search_mode": "keyword",
}
)
def _mock_registry():
"""Provide a mock registry for all ARIEL route tests."""
registry = _build_mock_registry()
with patch(
"osprey.registry.get_registry",
return_value=registry,
):
yield
def mock_ariel_service():
Xet Storage Details
- Size:
- 40.9 kB
- Xet hash:
- e5ef36d28b250e837bd6c37755c0f24987504b3da2c58c301198ced60c84796d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.